/** * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge"> * How To Remove Whitespace on Merge * </a> * <p> * Testing {@link PdfDenseMergeTool} using the OP's files. * </p> */ @Test public void testMergeGrandizerFiles() throws DocumentException, IOException { try ( InputStream docA = getClass().getResourceAsStream("Header.pdf"); InputStream docB = getClass().getResourceAsStream("Body.pdf"); InputStream docC = getClass().getResourceAsStream("Footer.pdf"); ) { PdfDenseMergeTool tool = new PdfDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // TODO: force iText to respect the order in which content is added writer.setStrictImageSequence(true); document.open(); // step 4 - add content into document String[] imageNames = { "35_Cal_Crutchlow.jpg", "38_Bradley_Smith.jpg", "46_Valentino_Rossi.jpg", "99_Jorge_Lorenzo.jpg" }; for (int i = 0; i < 4; i++) { Image image = Image.getInstance("resources/img/" + imageNames[i]); // TODO: scale image image.scaleToFit(500, 500); // scale size document.add(image); document.add(new Paragraph(imageNames[i])); } document.close(); }
/** * adds an image to the document. * * @param doc * @param iji * @return * @throws InterruptedException * @throws ExecutionException * @throws IOException * @throws DocumentException */ public Document addImage(Document doc, ImageJobDescription iji) throws InterruptedException, ExecutionException, IOException, DocumentException { // create image worker ImageWorker job = new ImageWorker(dlConfig, iji); // submit Future<DocuImage> jobTicket = imageJobCenter.submit(job); // wait for result DocuImage img = jobTicket.get(); // scale the image Image pdfimg = Image.getInstance(img.getAwtImage(), null); float docW = PageSize.A4.getWidth() - 2 * PageSize.A4.getBorder(); float docH = PageSize.A4.getHeight() - 2 * PageSize.A4.getBorder(); // fit the image to the page pdfimg.scaleToFit(docW, docH); // add to PDF doc.add(pdfimg); return doc; }
public static String GetPDFBin(HttpServletResponse response, String docText) { Document document = new Document(PageSize.A4, 36, 36, 36, 36); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); InputStream is = new ByteArrayInputStream(docText.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, is); document.close(); return(new String(Base64.encodeBase64(baos.toByteArray()))); } catch (Exception e) { logger.error("Unexpected error", e); } return null; }
public static void PrintPDFFromHTMLString(HttpServletResponse response, String docText) { Document document = new Document(PageSize.A4, 36, 36, 36, 36); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); InputStream is = new ByteArrayInputStream(docText.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, is); document.close(); byte[] binArray = baos.toByteArray(); PrintPDFFromBytes(response, binArray); } catch (Exception e) { logger.error("Unexpected error", e); } }
public Document createDocument(File pdfFile) throws DocumentException, IOException{ Document document = new Document(new Rectangle(pageWidth, pageHeight)); document.setPageSize(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); //写入页尾 this.setFooter(writer); writer.setFullCompression(); writer.setPdfVersion(PdfWriter.VERSION_1_4); document.open(); // //加入二维码图片 // Image image = Image.getInstance(System.getProperty(appConfig.getValue("app.root"))+"/images/logoqrcode.png"); // image.scaleAbsolute(40,40);//控制图片大小 // image.setAlignment(Image.LEFT); // document.add(image); return document; }
/** * Save the chart as pdf. * * @param chart * chart that should be saved. * @param fileName * file name under which the chart should be saved. * @throws IOException * i/o exception */ public static void saveGraph(final Chart chart, final String fileName) throws IOException { final int width = (int) PageSize.A4.getWidth(); final int height = (int) PageSize.A4.getHeight(); VectorGraphics2D g = new PDFGraphics2D(0.0, 0.0, width, height); chart.paint(g, width, height); // Write the vector graphic output to a file FileOutputStream file = new FileOutputStream(fileName + ".pdf"); try { file.write(g.getBytes()); } finally { file.close(); } }
/** Shows a blank document, in case of a problem in generating the PDF */ private byte[] showBlank() throws DocumentException { final Document document = new Document(PageSize.LETTER); // FIXME - get PageSize from label definition final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); document.add(new Paragraph("No data have been uploaded. The time is: " + new Date())); final Barcode128 code128 = new Barcode128(); code128.setGenerateChecksum(true); code128.setCode(new Date().toString()); document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null)); document.close(); return baos.toByteArray(); }
private static void makePDF(Bitmap bmp, File file) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor(FullscreenActivity.mAuthor.toString()); document.addTitle(FullscreenActivity.mTitle.toString()); document.addCreator("OpenSongApp"); if (bmp!=null && bmp.getWidth()>bmp.getHeight()) { document.setPageSize(PageSize.A4.rotate()); } else { document.setPageSize(PageSize.A4); } document.addTitle(FullscreenActivity.mTitle.toString()); document.open();//document.add(new Header("Song title",FullscreenActivity.mTitle.toString())); BaseFont urName = BaseFont.createFont("assets/fonts/Lato-Reg.ttf", "UTF-8",BaseFont.EMBEDDED); Font TitleFontName = new Font(urName, 14); Font AuthorFontName = new Font(urName, 10); document.add(new Paragraph(FullscreenActivity.mTitle.toString(),TitleFontName)); document.add(new Paragraph(FullscreenActivity.mAuthor.toString(),AuthorFontName)); addImage(document,bmp); document.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment"> * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment * </a> * <p> * Indeed, the coordinates do not line up. The y coordinate of * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)} * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds * the text to come. * </p> */ @Test public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException { Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf"))); document.open(); Font fontQouteItems = new Font(BaseFont.createFont(), 12); PdfContentByte canvas = writer.getDirectContent(); // Item Number ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0); // Estimated Qty ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0); // Item Description ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping ct.setSimpleColumn(new Rectangle(193, 070, 390, 450)); ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems)); ct.go(); document.close(); }
private static void drawSexyTriangle(PdfWriter writer, boolean rotated) { PdfContentByte canvas = writer.getDirectContent(); float x = 36; float y = 400; float side = 70; PdfShading axial = rotated ? PdfShading.simpleAxial(writer, PageSize.A4.getRight() - y, x, PageSize.A4.getRight() - y, x + side, BaseColor.PINK, BaseColor.BLUE) : PdfShading.simpleAxial(writer, x, y, x + side, y, BaseColor.PINK, BaseColor.BLUE); PdfShadingPattern shading = new PdfShadingPattern(axial); canvas.setShadingFill(shading); canvas.moveTo(x,y); canvas.lineTo(x + side, y); canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3)))); canvas.closePathFillStroke(); }
/** * <a href="https://stackoverflow.com/questions/46466747/how-to-split-a-pdf-page-in-java"> * How to split a PDF page in java? * </a> * <p> * This test shows how to split the pages of a document into tiles of A6 * size using the {@link Abstract2DPdfPageSplittingTool}. * </p> */ @Test public void testSplitDocumentA6() throws IOException, DocumentException { try (InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-A6.pdf"))) { Abstract2DPdfPageSplittingTool tool = new Abstract2DPdfPageSplittingTool() { @Override protected Iterable<Rectangle> determineSplitRectangles(PdfReader reader, int page) { Rectangle targetSize = PageSize.A6; List<Rectangle> rectangles = new ArrayList<>(); Rectangle pageSize = reader.getPageSize(page); for (float y = pageSize.getTop(); y > pageSize.getBottom() + 5; y-=targetSize.getHeight()) { for (float x = pageSize.getLeft(); x < pageSize.getRight() - 5; x+=targetSize.getWidth()) { rectangles.add(new Rectangle(x, y - targetSize.getHeight(), x + targetSize.getWidth(), y)); } } return rectangles; } }; tool.split(result, new PdfReader(resource)); } }
/** * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and"> * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4 * </a> * <p> * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page. * </p> */ @Test public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf")) ) { PdfReader reader = new PdfReader(resource); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, result); document.open(); double sqrt2 = Math.sqrt(2); Rectangle pageSize = reader.getPageSize(1); PdfImportedPage importedPage = writer.getImportedPage(reader, 1); writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2); document.close(); } }
/** * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf"> * Double space not being preserved in PDF * </a> * <p> * Indeed, the double space collapses into a single one when copying&pasting from the * generated PDF displayed in Adobe Reader. On the other hand the gap for the double * space is twice as wide as for the single space. So this essentially is a quirk of * copy&paste of Adobe Reader (and some other PDF viewers, too). * </p> */ @Test public void testDoubleSpace() throws DocumentException, IOException { try ( OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf"))) { PdfPTable table = new PdfPTable(1); table.getDefaultCell().setBorderWidth(0.5f); table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36))); table.addCell(new Phrase("DOUBLE SPACED", new Font(BaseFont.createFont(), 36))); table.addCell(new Phrase("TRIPLE SPACED", new Font(BaseFont.createFont(), 36))); Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter.getInstance(pdfDocument, pdfStream); pdfDocument.open(); pdfDocument.add(table); pdfDocument.close(); } }
/** * <a href="http://stackoverflow.com/questions/38057241/itextpdf-different-margin-on-specific-page"> * itextpdf different margin on specific page * </a> * <p> * This test shows how to set different margins to separate pages. * </p> */ @Test public void testChangingMargins() throws IOException, DocumentException { StringBuilder builder = new StringBuilder("test"); for (int i = 0; i < 100; i++) builder.append(" test"); String test = builder.toString(); try ( OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "ChangingMargins.pdf"))) { Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter.getInstance(pdfDocument, pdfStream); pdfDocument.open(); for (int m = 0; m < pdfDocument.getPageSize().getWidth() / 2 && m < pdfDocument.getPageSize().getHeight() / 2; m += 100) { // pdfDocument.setMargins(m, m, 100, 100); pdfDocument.setMargins(m, m, m, m); pdfDocument.newPage(); pdfDocument.add(new Paragraph(test)); } pdfDocument.close(); } }
/** * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge"> * How To Remove Whitespace on Merge * </a> * <p> * Testing {@link PdfVeryDenseMergeTool} using the OP's files. * </p> */ @Test public void testMergeGrandizerFiles() throws DocumentException, IOException { try ( InputStream docA = getClass().getResourceAsStream("Header.pdf"); InputStream docB = getClass().getResourceAsStream("Body.pdf"); InputStream docC = getClass().getResourceAsStream("Footer.pdf"); ) { PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 5); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
/** * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge"> * How To Remove Whitespace on Merge * </a> * <p> * Testing {@link PdfVeryDenseMergeTool} using the OP's files and a gap of 10. This was the * OP's gap value of choice resulting in lost lines. Cannot reproduce... * </p> */ @Test public void testMergeGrandizerFilesGap10() throws DocumentException, IOException { try ( InputStream docA = getClass().getResourceAsStream("Header.pdf"); InputStream docB = getClass().getResourceAsStream("Body.pdf"); InputStream docC = getClass().getResourceAsStream("Footer.pdf"); ) { PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PageSize.A4, 18, 18, 10); PdfReader readerA = new PdfReader(docA); PdfReader readerB = new PdfReader(docB); PdfReader readerC = new PdfReader(docC); try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "GrandizerMerge-veryDense-gap10.pdf"))) { List<PdfReader> inputs = Arrays.asList(readerA, readerB, readerC); tool.merge(fos, inputs); } finally { readerA.close(); readerB.close(); readerC.close(); } } }
/** * Generates a document with a header containing Page x of y and with a Watermark on every page. * @param args no arguments needed */ public static void main(String args[]) { try { // step 1: creating the document Document doc = new Document(PageSize.A4, 50, 50, 100, 72); // step 2: creating the writer PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("pageNumbersWatermark.pdf")); // step 3: initialisations + opening the document writer.setPageEvent(new PageNumbersWatermark()); doc.open(); // step 4: adding content String text = "some padding text "; for (int k = 0; k < 10; ++k) text += text; Paragraph p = new Paragraph(text); p.setAlignment(Element.ALIGN_JUSTIFIED); doc.add(p); // step 5: closing the document doc.close(); } catch ( Exception e ) { e.printStackTrace(); } }
@Override public void createDocument( GenerationDataBean bean, Properties scheduleProperties, String documentTitle, String documentName ) throws Exception { // Create the document File outputFile = new File( "./pdf/" + documentName + ".pdf" ); if( ! outputFile.getParentFile().exists() && ! outputFile.getParentFile().mkdirs()) throw new IOException( outputFile.getParentFile() + " could not be created." ); final Document doc = new Document( PageSize.A4.rotate()); PdfWriter.getInstance( doc, new FileOutputStream( outputFile )); doc.open(); doc.addAuthor( bean.getName()); doc.addCreator( bean.getName()); doc.addTitle( documentTitle ); doc.addSubject( documentTitle ); // Add pages for( int i=bean.getStartWeek(); i<=bean.getEndWeek(); i++ ) addPageForWeek( i, doc, bean, scheduleProperties ); // That's it! doc.close(); }
/** * @see org.displaytag.export.BinaryExportView#doExport(OutputStream) */ @Override public void doExport(OutputStream out) throws JspException { try { Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40); PdfWriter w = initItextWriter(document, out); document.open(); if (model.getRowIterator(true).hasNext()) { PdfPTable table = new PdfPTable(this.model.getNumberOfColumns()); ItextTableWriter writer = new ItextTableWriter(table, document); writer.writeTable(this.model, "-1"); document.add(table); }else{ w.setPageEmpty(false); document.newPage(); } document.close(); } catch (Exception e) { throw new ItextGenerationException(e); } }
public static void createPdf(String filename, String dbTable) throws SQLException, DocumentException, IOException { // step 1 Document document = new Document(PageSize.A4); // System.out.println(Tax.class.getResource("fonts/arial.ttf").getPath()); BaseFont bf = BaseFont.createFont("etc/Arial.ttf", "Cp1253", BaseFont.EMBEDDED); // step 2 PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfPTableEvent event = new Printer(); PdfPTable table = getTable(dbTable, bf); table.setTableEvent(event); document.add(table); document.newPage(); // step 5 document.close(); }
public void CreatePDF() throws IOException { Document doc = null; OutputStream outStream = null; try { doc = new Document(PageSize.A4, 72, 72, 72, 72); outStream = new FileOutputStream(fileName); PdfWriter.getInstance(doc, outStream); doc.open(); doc.add(new Paragraph(getHeader())); doc.add(table); doc.add(new Paragraph(descricao)); } catch (FileNotFoundException | DocumentException ex) { Logger.getLogger(OutPDF.class.getName()).log(Level.SEVERE, null, ex); } finally { if (doc != null) { doc.close(); } if (outStream != null) { outStream.close(); } // table.getRows().add(null) } JOptionPane.showMessageDialog(null, "PDF Salvo com sucesso!"); }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // step 4 - add content into document for (int i = 0; i < 5; i++) { document.add(new Phrase("Hello", new Font(FontFamily.HELVETICA, 32, Font.BOLD))); document.add(new Phrase("World", new Font(FontFamily.COURIER, 40, Font.ITALIC))); document.add(new Phrase("!!!", new Font(FontFamily.TIMES_ROMAN, 40))); document.add(Chunk.NEWLINE); } document.close(); }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // TODO: 1. get direct content PdfContentByte canvas = writer.getDirectContent(); Font font = new Font(FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.ORANGE); Phrase headerText = new Phrase("PSEG DP&C", font); int alignLeft = Element.ALIGN_LEFT; float right = document.getPageSize().getRight(); float top = document.getPageSize().getTop(); // TODO: 2. use ColumnText ColumnText.showTextAligned(canvas, alignLeft, headerText, right - 180, top - 36, 0); document.close(); }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); PdfPTable table = new PdfPTable(2); PdfReader reader = new PdfReader(T08_Chapter.RESULT); int n = reader.getNumberOfPages(); for (int pageNumber = 1; pageNumber <= n; pageNumber++) { // TODO: import page as image PdfImportedPage page = writer.getImportedPage(reader, pageNumber); table.addCell(Image.getInstance(page)); } document.add(table); document.close(); }
public void createPdf(String filename) throws DocumentException, IOException { Document document = new Document(PageSize.LETTER); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // step 4 - add content into document for (int i = 1; i <= 10; i++) { Chapter chapter = new Chapter(String.format("Chapter %s", i), i); Section section = chapter.addSection("Section"); section.setIndentation(18); section.add(new Paragraph("TestTestTestTestTestTestTestTestTestTestTestTest")); for (int j = 1; j <= 3; j++) { Section subSection = section.addSection("Sub Section"); subSection.add(new Paragraph("TestTestTestTestTestTestTestTestTestTestTestTest")); } document.add(chapter); } document.close(); }
public void createPdf(String filename) throws DocumentException, IOException { // step 1 - create PDF document Document document = new Document(PageSize.LETTER); // step 2 - bind PDF document with output stream PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 - open document document.open(); // step 4 - add content into document document.add(new Paragraph("Hello World!")); // step 5 - close document document.close(); }
/** * Create the PDF from a {@link Component}. * * @param component */ private void createPdf(Component component) { if (component == null) { return; } // prompt user for pdf location File file = promptForPdfLocation(); if (file == null) { return; } try { // create pdf document Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte cb = writer.getDirectContent(); createPdfViaTemplate(component, document, cb); document.close(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage()); } }
/** * Create the PDF from a {@link PlotterTemplate}. * * @param template */ private void createPdf(PlotterTemplate template) { if (template == null) { return; } // prompt user for pdf location File file = promptForPdfLocation(); if (file == null) { return; } try { // create pdf document Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte cb = writer.getDirectContent(); createPdfViaTemplate(template, document, cb); document.close(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("cannot_export_pdf", e, e.getMessage()); } }
private Rectangle getPageSize(String quality) { if (quality == null) { quality = "a2"; } logger.info("Setting PDF Quality to : " + quality); logWindow.log("Setting PDF Quality to : " + quality); switch (quality.toLowerCase()) { case "a2": return PageSize.A2; case "a3": return PageSize.A3; case "a4": return PageSize.A4; case "a5": return PageSize.A5; case "a6": return PageSize.A6; case "a7": return PageSize.A7; default: return PageSize.A3; } }
public String savePageAsPdf(boolean scaled) throws IOException, DocumentException { String pdfName = ""; // Define test screenshot root String test = ""; if (TestNamingUtil.isTestNameRegistered()) { test = TestNamingUtil.getTestNameByThread(); } else { test = "undefined"; } File testRootDir = ReportContext.getTestDir(); File artifactsFolder = ReportContext.getArtifactsFolder(); String fileID = test.replaceAll("\\W+", "_") + "-" + System.currentTimeMillis(); pdfName = fileID + ".pdf"; String fullPdfPath = artifactsFolder.getAbsolutePath() + "/" + pdfName; // TODO: test this implementation and change back to capture if necessary Image image = Image.getInstance(testRootDir.getAbsolutePath() + "/" + Screenshot.captureFailure(driver, "")); Document document = null; if (scaled) { document = new Document(PageSize.A4, 10, 10, 10, 10); if (image.getHeight() > (document.getPageSize().getHeight() - 20) || image.getScaledWidth() > (document.getPageSize().getWidth() - 20)) { image.scaleToFit(document.getPageSize().getWidth() - 20, document.getPageSize().getHeight() - 20); } } else { document = new Document(new RectangleReadOnly(image.getScaledWidth(), image.getScaledHeight())); } PdfWriter.getInstance(document, new FileOutputStream(fullPdfPath)); document.open(); document.add(image); document.close(); return fullPdfPath; }
public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer, PageCounter pagecounter, int maximumPageNumber, String inputFolder) throws DocumentException, IOException { _inputFolder = inputFolder; Document document = new Document(PageSize.A4, 50, 50, 70, 50); PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788)); pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber)); if (pagecounter != null) { pdfwriter.setPageEvent(pagecounter); } document.open(); Paragraph p = new Paragraph(); // p.setSpacingBefore(SPACING); p.setSpacingAfter(SPACING); p.setIndentationLeft(INDENTATION); writeQuestions(p, document, showCorrectAnswer, qlist); document.close(); }
public static void main(String[] args) throws FileNotFoundException, DocumentException { Document d = new Document(PageSize.A4); FileOutputStream fos = new FileOutputStream("teste.pdf"); PdfWriter.getInstance(d, fos); d.open(); PdfPTable pTable = new PdfPTable(3); PdfPCell cell1 = new PdfPCell(new Phrase("111111111")); PdfPCell cell2 = new PdfPCell(new Phrase("222222222")); cell2.setRowspan(5); PdfPCell cell3 = new PdfPCell(new Phrase("333333333")); pTable.addCell(cell1); pTable.addCell(cell2); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); pTable.addCell(cell1); pTable.addCell(cell3); d.add(pTable); d.close(); }
public static void writeSimplePdf() throws Exception{ //1.新建document对象 //第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。 Document document = new Document(PageSize.A4, 50, 50, 50, 50); //2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。 //创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\Documents\\ITextTest.pdf")); //3.打开文档 document.open(); //4.向文档中添加内容 //通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落 BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font fontChinese = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK); document.add(new Paragraph("sdfsdfsd全是中文显示了没.fsdfsfs",fontChinese)); document.add(new Paragraph("Some more text on the first page with different color and font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new BaseColor(255, 150, 200)))); Paragraph pragraph=new Paragraph("你这里有中亠好", fontChinese); document.add(pragraph); //图像支持格式 GIF, Jpeg, PNG, wmf Image gif = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); gif.setBorder(5); gif.scaleAbsolute(30,30); gif.setAlignment(Image.RIGHT|Image.TEXTWRAP); document.add(gif); Paragraph pragraph11=new Paragraph("你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好你这里有中亠好", fontChinese); document.add(pragraph11); Image gif15 = Image.getInstance("F:/keyworkspace/survey/WebRoot/images/logo/snlogo.png"); // gif15.setBorder(50); gif15.setBorder(Image.BOX); gif15.setBorderColor(BaseColor.RED); // gif15.setBorderColorBottom(borderColorBottom) gif15.setBorderWidth(1); gif15.scalePercent(50); document.add(gif15); //5.关闭文档 document.close(); }
private void setFooter(PdfWriter writer) throws DocumentException, IOException { //HeaderFooter headerFooter = new HeaderFooter("海南国保", 10, PageSize.A4); // 更改事件,瞬间变身 第几页/共几页 模式。 HeaderFooter headerFooter = new HeaderFooter();// 就是上面那个类 writer.setBoxSize("art", PageSize.A4); writer.setPageEvent(headerFooter); }
/** * Exports the 3d graph as a pdf * * @param file The pdf file to which the data should be written * @param panel The chart panel that has to be exported */ public static void exportToPDF(File file, Chart3DPanel panel){ PdfWriter out = null; Document document = new com.itextpdf.text.Document(PageSize.A4.rotate()); int width = 800, height = 500; try{ out = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = out.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); @SuppressWarnings("deprecation") Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height); panel.getChart().draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch(Exception e){ // in case any error occurs tell the user what the error is (sometimes useful if there is a problem of writing rights) JOptionPane.showMessageDialog(GUIPrism.getGUI(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return; } document.close(); }
/** * Create State Transition Matrix. * * @param eList * list with possible events * @param seqList * list with sequences * @return JTable */ public static Container createStateTrans(final EventList eList, final List<EventList> seqList) { // Create frame final Dimension frameDimension = new Dimension( (int) (PageSize.A4.getWidth()), (int) (PageSize.A4.getHeight())); ApplicationFrame frame = new ApplicationFrame("Vidney"); frame.setSize(frameDimension); String[][] matrix = setUp(eList); String[][] matrixUse = fillMatrix(matrix, seqList); String[][] outputM = new String[matrixUse.length - 1][matrixUse.length]; for (int i = 1; i < matrixUse[0].length; i++) { for (int j = 0; j < matrixUse[1].length; j++) { outputM[i - 1][j] = matrixUse[i][j]; } } JTable table = new JTable(outputM, matrixUse[0]); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setColumnHeaderView(table.getTableHeader()); scrollPane.setPreferredSize(table.getPreferredSize()); JPanel p = new JPanel(new BorderLayout()); p.add(scrollPane, BorderLayout.CENTER); // Not a very clean way frame.setContentPane(p); frame.setVisible(true); frame.setVisible(false); return scrollPane; }