/** * Increase the page number. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ @Override public void onStartPage(PdfWriter writer, Document document) { pagenumber++; System.out.println("ON Start Page PDF"); Rectangle rect = writer.getBoxSize("art"); /* header ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_RIGHT, header[0], rect.getRight(), rect.getTop(), 0); */ Font font = new Font(); font.setSize(8); if (G.licensePDF) { ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA")),font), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0); ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER, new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA2")),font), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 9, 0); } }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader. With a different starting file, though, it doesn't, cf. * {@link #testAddUnicodeStampEg_01()}. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With * a different starting file, though, it doesn't as this test shows. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampEg_01() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("eg_01.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
/** * <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(); }
@Override public void onEndPage(PdfWriter writer, Document document) { PdfPTable table = new PdfPTable(2); table.setTotalWidth(527); table.setWidthPercentage(100); table.setLockedWidth(true); table.getDefaultCell().setFixedHeight(105f); table.getDefaultCell().setBorderWidth(0); table.addCell(""); table.addCell(csmLogoImage); table.writeSelectedRows(0, -1, 100, 840, writer.getDirectContent()); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(lebData.getSchuelername() + " " + lebData.getSchuljahr() + " " + lebData.getSchulhalbjahr().getId() + " Seite " + document.getPageNumber(), fusszeilenFont), 100, 75, 0); }
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(); }
@SuppressWarnings("unchecked") protected void fillColumnText(List<HashMap<String, Object>> bookmarkList, ColumnText ct, float leftIndent, int depth) { if (null != bookmarkList) { for (int i = 0; i < bookmarkList.size(); i++) { HashMap<String, Object> bookmark = bookmarkList.get(i); String title = (String) bookmark.get("Title"); String pageNum = ((String) bookmark.get("Page")).split(" ")[0]; Paragraph paragraph = new Paragraph(title); paragraph.add(new Chunk(new DottedLineSeparator())); paragraph.add(Integer.toString((Integer.parseInt(pageNum)))); paragraph.setIndentationLeft(leftIndent * depth); paragraph.setSpacingBefore(0 == depth ? 9 : 0); ct.addElement(paragraph); fillColumnText(((List<HashMap<String, Object>>) bookmark.get("Kids")), ct, leftIndent, depth + 1); } } }
private void pageNumberFooter(PdfWriter writer, Rectangle rect) { Chunk c = new Chunk(String.format(LocaleStrings.getString("page"), writer.getPageNumber(), _maximumPageNumber)); c.setFont(new Font(FontFamily.HELVETICA, 10)); Phrase pagephrase = new Phrase(c); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, pagephrase, rect.getRight() - 60, rect.getBottom() - 30, 0); }
@SuppressWarnings("unused") private void headerText(PdfWriter writer, Rectangle rect) { float center = (rect.getLeft() + rect.getRight()) / 2; ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Header Text"), center, rect.getTop(), 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("01.01.1970"), center, rect.getTop() - 16, 0); }
public void apply(ColumnText ct,PdfPTable table,PdfPCell cell ) throws PdfRenderException{ table.addCell(cell); ct.addElement( table ); try { ct.go(); } catch (DocumentException e) { throw new PdfRenderException( e ); } }
public ColumnText createColumn(PdfContentByte cb, Block block){ ColumnText ct = new ColumnText( cb ); PdfDocument request = getPdfDocument(block); float[] mmPositions = getBoundsInMMIncludeCutmark(block); ct.setSimpleColumn( SizeFactory.millimetersToPostscriptPoints( mmPositions[0] ), SizeFactory.millimetersToPostscriptPoints( request.getSize()[1] - ( mmPositions[1] + mmPositions[3]) ), SizeFactory.millimetersToPostscriptPoints( mmPositions[0] + mmPositions[2] ), SizeFactory.millimetersToPostscriptPoints( request.getSize()[1] - mmPositions[1] ), 0, Element.ALIGN_LEFT ); return ct; }
public void onRender( PdfContentByte cb ) throws PdfRenderException{ float[] positions = new BlockFactory().getBoundsInPs(this); new BlockFactory().createRoundRectangle(cb, this); ColumnText ct = new BlockFactory().createColumn(cb,this); PdfPTable table = new TableFactory().createTable(positions[2]); PdfPCell cell = new CellFactory().createCell(this); new RenderParagraphs().render(cell, this); new TableFactory().apply(ct, table, cell); }
public void onStartPage(PdfWriter writer, Document document) { if (request.getTopLeft() != null) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(getPhrase(request.getTopLeft(), request.getTopLeftText(), document.getPageNumber()), font), 50, 800, 0); } if (request.getTopRight() != null) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase( getPhrase(request.getTopRight(), request.getTopRightText(), document.getPageNumber()), font), 550, 800, 0); } }
public void onEndPage(PdfWriter writer, Document document) { if (request.getBottomLeft() != null) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase( getPhrase(request.getBottomLeft(), request.getBottomLeftText(), document.getPageNumber()), font), 60, 30, 0); } if (request.getBottomRight() != null) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase( getPhrase(request.getBottomRight(), request.getBottomRightText(), document.getPageNumber()), font), 550, 30, 0); } }
public void onEndPage(PdfWriter writer, Document document) { Font font = FontFactory.getFont(Fonts.OPEN_SANS, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 8, Font.NORMAL, BaseColor.BLACK); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Localization.getString(Strings.REPORT_FOOTER_LEFT), font), 100, 25, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Localization.getString(Strings.REPORT_FOOTER_CENTER, document.getPageNumber()), font), 300, 25, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(DateTime.now().toString("dd.MM.YYYY"), font), 500, 25, 0); }
public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Caribbean Online Judge"), (rect.getLeft() + rect.getRight()) / 2, rect.getTop() + 10, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("-%d-", writer.getPageNumber())), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0); }
/** * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines"> * iTextSharp: Extra space between lines * </a> * <p> * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored. * The reason is that the op is working in text mode. Thus, he has to use * {@link ColumnText#setLeading(float, float)} instead, cf. * {@link #testLikeUser3208131Fixed()}. * </p> */ @Test public void testLikeUser3208131() throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131.pdf"))); document.open(); Font font = new Font(FontFamily.UNDEFINED, 4, Font.UNDEFINED, null); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); float gutter = 15; float colwidth = (document.getPageSize().getRight() - document.getPageSize().getLeft() - gutter) / 2; float[] left = { document.getPageSize().getLeft() + 133, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + 133, document.getPageSize().getBottom() }; float[] right = { document.getPageSize().getLeft() + colwidth, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + colwidth, document.getPageSize().getBottom() }; for (int i = 0; i < 3; i++) { Phrase Ps = new Phrase("Test " + i + "\n", font); Ps.setLeading(0.0f, 0.6f); ct.addText(Ps); ct.addText(Chunk.NEWLINE); } ct.setColumns(left, right); ct.go(); document.close(); }
/** * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines"> * iTextSharp: Extra space between lines * </a> * <p> * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored, * cf. {@link #testLikeUser3208131()}. The reason is that the op is working in * text mode. Thus, he has to use {@link ColumnText#setLeading(float, float)} * instead. * </p> */ @Test public void testLikeUser3208131Fixed() throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131-fixed.pdf"))); document.open(); Font font = new Font(FontFamily.UNDEFINED, 4, Font.UNDEFINED, null); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); float gutter = 15; float colwidth = (document.getPageSize().getRight() - document.getPageSize().getLeft() - gutter) / 2; float[] left = { document.getPageSize().getLeft() + 133, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + 133, document.getPageSize().getBottom() }; float[] right = { document.getPageSize().getLeft() + colwidth, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + colwidth, document.getPageSize().getBottom() }; ct.setLeading(0.0f, 0.3f); for (int i = 0; i < 3; i++) { Phrase Ps = new Phrase("Test " + i + "\n", font); ct.addText(Ps); ct.addText(Chunk.NEWLINE); } ct.setColumns(left, right); ct.go(); document.close(); }
/** * <a href="http://stackoverflow.com/questions/41949253/how-to-add-columntext-as-an-annotation-in-itext-pdf"> * How to add columnText as an annotation in itext pdf * </a> * <p> * This test demonstrates how to use a columntext in combination with an annotation. * </p> */ @Test public void testAddAnnotationLikeJasonY() throws IOException, DocumentException { String html ="<html><h1>Header</h1><p>A paragraph</p><p>Another Paragraph</p></html>"; String css = "h1 {color: red;}"; ElementList elementsList = XMLWorkerHelper.parseToElementList(html, css); try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "JasonY.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); Rectangle cropBox = reader.getCropBox(1); PdfAnnotation annotation = stamper.getWriter().createAnnotation(cropBox, PdfName.FREETEXT); PdfAppearance appearance = PdfAppearance.createAppearance(stamper.getWriter(), cropBox.getWidth(), cropBox.getHeight()); ColumnText ct = new ColumnText(appearance); ct.setSimpleColumn(new Rectangle(cropBox.getWidth(), cropBox.getHeight())); elementsList.forEach(element -> ct.addElement(element)); ct.go(); annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, appearance); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
private Float calculateTotalCellWidth(PdfPCell cell) { return cell.getBorderWidthLeft() + cell.getEffectivePaddingLeft() + ColumnText.getWidth(cell.getPhrase()) + cell.getEffectivePaddingRight() + cell.getBorderWidthRight(); }
/** * Adds the header and the footer. * * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(reportName), document.left(), document.top()+HEADER_HEIGHT, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(paragraphName), document.right(), document.top()+HEADER_HEIGHT, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(exportDate), document.left(), document.bottomMargin() - FOOTER_HEIGHT, 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(String.format("Page %d", pagenumber)), document.right(), document.bottomMargin() - FOOTER_HEIGHT, 0); }
/** * Adds the header and the footer. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0); }
@Override public void onEndPage(PdfWriter writer, Document document) { // TODO: 2. add page as template PdfContentByte canvas = writer.getDirectContent(); canvas.addTemplate(page, 0, 0); Phrase footerText = new Phrase("Page " + document.getPageNumber()); float footerXpos = (document.getPageSize().getLeft() + document.getPageSize().getRight()) / 2; float footerYpos = document.getPageSize().getBottom() + 36; ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, footerText, footerXpos, footerYpos, 0); }
/** * Fills out the total number of pages before the document is closed. */ public void onCloseDocument(PdfWriter writer, Document document) { totalPageNo = writer.getPageNumber() - 1; if (totalPageNoVbe != null) { Map<String, Object> style = buildCellStyleMap(totalPageNoVbe); fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY); int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue(); Font fnt = getFont(size); updateFont(style, fnt); ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(totalPageNo), fnt), 0, 1, 0); } }
@Override public void onEndPage(PdfWriter writer, Document document) { // 計算出文件中間位置 float center = (document.right() - document.left()) / 2; writer.getDefaultColorspace(); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_MIDDLE, new Phrase(Integer.toString(pageCount), mFont), center, 0 + 10, 0); }
public void generatePDF(File file) throws IOException, DocumentException { Image image = Image.getInstance(getClass().getClassLoader().getResource("blank.png")); image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight()); image.setAbsolutePosition(0, 0); if (logoFile != null) { logoImage = Image.getInstance(logoFile.toURI().toURL()); logoImage.scaleAbsolute((float) (logoImage.getWidth() * 0.35), (float) (logoImage.getHeight() * 0.35)); float logoWidth = logoImage.getWidth(); float logoHeight = logoImage.getHeight(); float ratioH = logoHeight / logoWidth; float ratioW = logoWidth / logoHeight; if (logoHeight >= logoWidth) { logoHeight = 150f; logoWidth = 150.0f * ratioW; logoImage.scaleAbsolute(logoWidth, logoHeight); } else { logoHeight = 150f * ratioH; logoWidth = 150.0f; logoImage.scaleAbsolute(logoWidth, logoHeight); } logoImage.setAbsolutePosition(130f - (0.5f * logoWidth), 725f - (0.5f * logoHeight)); } Document document = new Document(PageSize.A4, 0, 0, 0, 0); OutputStream outputStream = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, outputStream); BaseFont baseBold = BaseFont.createFont(getClass().getClassLoader().getResource("font/AbhayaLibre-Bold.ttf").toString(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); BaseFont baseRegular = BaseFont.createFont(getClass().getClassLoader().getResource("font/AbhayaLibre-Regular.ttf").toString(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); BaseFont baseExtraBold = BaseFont.createFont(getClass().getClassLoader().getResource("font/AbhayaLibre-ExtraBold.ttf").toString(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font fontBold = new Font(baseBold, 22); Font fontExtraBold = new Font(baseExtraBold, 40); Font fontRegular = new Font(baseRegular, 12); document.open(); PdfContentByte pdfContentByte = writer.getDirectContent(); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("PODPIS WYSTAWCY", fontRegular), 100, 100, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("PODPIS ODBIORCY ", fontRegular), 390, 100, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("Termin płatności: " + invoiceData.getString("paymentDate"), fontRegular), 35, 170, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("Słownie: " + invoiceData.getString("inWordsValue"), fontRegular), 35, 195, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("RAZEM", fontBold), 35, 245, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(invoiceData.getString("value") + " PLN", fontBold), 565, 245, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase(invoiceData.getString("service"), fontBold), 35, 380, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(invoiceData.getString("value") + " PLN", fontBold), 565, 380, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("Nazwa usługi", fontBold), 35, 400, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase("Wartość", fontBold), 565, 400, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase(senderData.getString("accountNumber"), fontRegular), 35, 435, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("Numer konta bankowego:", fontRegular), 35, 450, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("NIP: " + senderData.getString("NIP"), fontRegular), 35, 485, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase("NIP: " + receiverData.getString("NIP"), fontRegular), 565, 485, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase(senderData.getString("postalCode") + " " + senderData.getString("street"), fontRegular), 35, 510, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(receiverData.getString("postalCode") + " " + receiverData.getString("street"), fontRegular), 565, 510, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("ul. " + senderData.getString("street") + " " + senderData.getString("building") + (senderData.getString("apartment").isEmpty() ? "" : "/") + senderData.getString("apartment"), fontRegular), 35, 535, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase("ul. " + receiverData.getString("street") + " " + receiverData.getString("building") + (receiverData.getString("apartment").isEmpty() ? "" : "/") + receiverData.getString("apartment"), fontRegular), 565, 535, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase(senderData.getString("nameMore"), fontRegular), 35, 560, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(receiverData.getString("nameMore"), fontRegular), 565, 560, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase(senderData.getString("name"), fontRegular), 35, 585, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(receiverData.getString("name"), fontRegular), 565, 585, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("WYSTAWCA", fontRegular), 35, 605, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase("ODBIORCA", fontRegular), 565, 605, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("NR: " + invoiceData.getString("ID"), new Font(baseBold, 36)), 265, 690, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_LEFT, new Phrase("RACHUNEK", fontExtraBold), 265, 733, 0); ColumnText.showTextAligned(pdfContentByte, Element.ALIGN_RIGHT, new Phrase(invoiceData.getString("city") + ", " + invoiceData.getString("date"), fontRegular), 565, 795, 0); //pdfContentByte = writer.getDirectContent(); if (logoImage != null) { pdfContentByte.addImage(logoImage); } pdfContentByte = writer.getDirectContentUnder(); pdfContentByte.addImage(image); document.close(); outputStream.close(); }
private void sumSymboltoFooter(PdfWriter writer, Rectangle rect) { ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, _sumSymbol, rect.getLeft() - 10, rect.getBottom() - 30, 0); }
/** * <a href="https://stackoverflow.com/questions/45062602/itext-pdfappearence-issue"> * Text - PDFAppearence issue * </a> * <p> * This test shows how one can create a custom signature layer 2. * As the OP of the question at hand mainly wants to generate a * pure DESCRIPTION appearance that uses the whole area, we here * essentially copy the PdfSignatureAppearance.getAppearance code * for generating layer 2 in pure DESCRIPTION mode and apply it * to a plain pre-fetched layer 2. * </p> */ @Test public void signWithCustomLayer2() throws IOException, DocumentException, GeneralSecurityException { String digestAlgorithm = "SHA512"; CryptoStandard subfilter = CryptoStandard.CMS; try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf") ) { PdfReader reader = new PdfReader(resource); FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "test-customLayer2.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("reason"); appearance.setLocation("location"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // This essentially is the PdfSignatureAppearance.getAppearance code // for generating layer 2 in pure DESCRIPTION mode applied to a plain // pre-fetched layer 2. // vvvvv PdfTemplate layer2 = appearance.getLayer(2); String text = "We're using iText to put a text inside a signature placeholder in a PDF. " + "We use a code snippet similar to this to define the Signature Appearence.\n" + "Everything works fine, but the signature text does not fill all the signature " + "placeholder area as expected by us, but the area filled seems to have an height " + "that is approximately the 70% of the available space.\n" + "As a result, sometimes especially if the length of the signature text is quite " + "big, the signature text does not fit in the placeholder and the text is striped " + "away."; Font font = new Font(); float size = font.getSize(); final float MARGIN = 2; Rectangle dataRect = new Rectangle( MARGIN, MARGIN, appearance.getRect().getWidth() - MARGIN, appearance.getRect().getHeight() - MARGIN); if (size <= 0) { Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight()); size = ColumnText.fitText(font, text, sr, 12, appearance.getRunDirection()); } ColumnText ct = new ColumnText(layer2); ct.setRunDirection(appearance.getRunDirection()); ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT); ct.go(); // ^^^^^ ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter); } }
/** * <a href="http://stackoverflow.com/questions/29977927/table-header-in-pdf-getting-displayed-using-itextpdf5-1-1-but-not-in-itextpdf5-5"> * table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3 * </a> * <p> * Indeed, the code as presented by the OP does not show the header table. This makes sense, though: * </p> * <p> * The OP has cells with default padding (i.e. 2) and height 10, and he tries to insert text at height 7. * But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into the cell height 10. * Thus, the text does not fit and is not displayed. * </p> * <p> * You can fix this by either * <ul> * <li>using a smaller font, e.g. 6, or * <li>using a higher cell, e.g. 11, or * <li>using a smaller padding, e.g. 1, see below- * </p> */ @Test public void testSandeepSinghHeaderTable() throws DocumentException, IOException { byte[] strIntermediatePDFFile = createSampleDocument(); String header1 = "Header 1"; String header2 = "Header 2"; String header3 = "Header 3"; String header5 = "Header 5"; Document document = new Document(PageSize.A4.rotate(), 20, 20, 75, 20); PdfCopy copy = new PdfCopy(document, new FileOutputStream(new File(RESULT_FOLDER, "stampTableHeader.pdf"))); document.open(); PdfReader pdfReaderIntermediate = new PdfReader(strIntermediatePDFFile); int numberOfPages = pdfReaderIntermediate.getNumberOfPages(); Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL); System.out.println("###### No. of Pages: " + numberOfPages); for (int j = 0; j < numberOfPages; ) { PdfImportedPage page = copy.getImportedPage(pdfReaderIntermediate, ++j); PageStamp stamp = copy.createPageStamp(page); Phrase footer = new Phrase(String.format("%d of %d", j, numberOfPages), ffont); ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); if (j != 1) { PdfPTable headerTable = new PdfPTable(2); headerTable.setTotalWidth(700); headerTable.getDefaultCell().setFixedHeight(10); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); headerTable.getDefaultCell().setPadding(1); // Added! headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header1), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(new Phrase(String.format(header2), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header3), ffont)); headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.addCell(new Phrase(String.format(header5, j), ffont)); headerTable.completeRow(); headerTable.writeSelectedRows(0, 5, 60.5f, 550, stamp.getUnderContent()); } stamp.alterContents(); copy.addPage(page); } document.close(); }
private void generateProSheet(OutputStream output) { Paragraph spacingPara = new Paragraph(); spacingPara.setSpacingBefore(10); spacingPara.add(new Chunk(" ", bodyFont)); try { PdfWriter writer = PdfWriter.getInstance(document, output); document.setPageSize(PageSize.LETTER); // Set basic metadata document.addAuthor("Peter Brewer"); document.addSubject("Corina Provenience Sheet for " + o.getTitle()); /*HeaderFooter footer = new HeaderFooter(new Phrase(""), new Phrase("")); footer.setAlignment(Element.ALIGN_RIGHT); footer.setBorder(0); document.setFooter(footer);*/ /*HeaderFooter header = new HeaderFooter(new Phrase(o.getLabCode()+ " - "+o.getTitle(), bodyFont), false); header.setAlignment(Element.ALIGN_RIGHT); header.setBorder(0); document.setHeader(header);*/ document.open(); cb = writer.getDirectContent(); // Title Left ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(document.left(), document.top()-193, document.right(), document.top()-20, 20, Element.ALIGN_LEFT); ct.addText(getTitlePDF()); ct.go(); // Timestamp ColumnText ct3 = new ColumnText(cb); ct3.setSimpleColumn(document.left(), document.top()-223, 283, document.top()-60, 20, Element.ALIGN_LEFT); ct3.setLeading(0, 1.2f); ct3.addText(getTimestampPDF()); ct3.go(); // Pad text document.add(spacingPara); document.add(getObjectDescription()); document.add(getObjectComments()); document.add(spacingPara); getElementTable(); } catch (DocumentException de) { System.err.println(de.getMessage()); } // Close the document document.close(); }
public void generateBoxLabel(OutputStream output) { try { PdfWriter writer = PdfWriter.getInstance(document, output); document.setPageSize(PageSize.LETTER); document.open(); cb = writer.getDirectContent(); // Set basic metadata document.addAuthor("Peter Brewer"); document.addSubject("Box Label"); for(WSIBox b : this.boxlist) { // Title Left ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(document.left(), document.top(15)-210, 368, document.top(15), 20, Element.ALIGN_LEFT); ct.addText(getTitlePDF(b)); ct.go(); // Barcode ColumnText ct2 = new ColumnText(cb); ct2.setSimpleColumn(370, document.top(15)-100, document.right(0), document.top(0), 20, Element.ALIGN_RIGHT); ct2.addElement(getBarCode(b)); ct2.go(); // Timestamp ColumnText ct3 = new ColumnText(cb); ct3.setSimpleColumn(document.left(), document.top(15)-223, 350, document.top(15)-60, 20, Element.ALIGN_LEFT); ct3.setLeading(0, 1.2f); ct3.addText(getTimestampPDF(b)); ct3.go(); // Pad text document.add(new Paragraph(" ")); Paragraph p2 = new Paragraph(); p2.setSpacingBefore(70); p2.setSpacingAfter(10); p2.add(new Chunk(" ", bodyFontLarge)); document.add(new Paragraph(p2)); // Ring samples table addTable(b); document.add(getParagraphSpace()); document.add(getComments(b)); document.newPage(); } } catch (DocumentException de) { System.err.println(de.getMessage()); } // Close the document document.close(); }
public PDFLabelMaker(LabelPage margins, OutputStream output) throws IOException, DocumentException { this.margins = margins; float sides, page, h, w, labelGap; // calculate the number of labels wide this page is page = margins.getPageSize().getWidth(); labelGap = margins.getLabelHorizontalGap(); w = margins.getLabelWidth(); sides = margins.getPageLeftMargin() + margins.getPageRightMargin(); if(sides + w > page) throw new IllegalArgumentException("0 labels fit across"); for(int i = 1; sides + (((float)i) * w) + (((float)(i - 1)) * labelGap) <= page; i++) { nAcross = i; } // the number of labels 'tall' page = margins.getPageSize().getHeight(); labelGap = margins.getLabelVerticalGap(); h = margins.getLabelHeight(); sides = margins.getPageTopMargin() + margins.getPageBottomMargin(); if(sides + h > page) throw new IllegalArgumentException("0 labels fit down"); for(int i = 1; sides + (((float)i) * h) + (((float)(i - 1)) * labelGap) <= page; i++) { nDown = i; } System.out.println("LABELS: across: " + nAcross + ", down: " + nDown); document = new Document(margins.getPageSize()); PdfWriter writer = PdfWriter.getInstance(document, output); document.addAuthor("Tellervo Label Generator"); document.addCreationDate(); document.open(); contentb = writer.getDirectContent(); // first off, pdfs are weird and go from high y coordinates to low for pages (ie, highest y = top of page) // also, this sets the page margins new ColumnText(contentb).setSimpleColumn( margins.getPageLeftMargin(), // lower x margin margins.getPageBottomMargin(), // bottom y margin margins.getPageSize().getWidth() - (margins.getPageRightMargin() + margins.getPageLeftMargin()), // upper x margin margins.getPageSize().getHeight() - (margins.getPageTopMargin() + margins.getPageBottomMargin()), // upper y margin 0, // no leading Element.ALIGN_MIDDLE // align in the middle of the label ); int realCols = nAcross + nAcross - 1; // number of labels + number of intra-label gaps float colwidth[] = new float[realCols]; float totalWidth = 0; for(int i = 0; i < realCols; i++) { if((i & 1) == 1) { // odd, so it's a margin totalWidth += margins.getLabelHorizontalGap(); colwidth[i] = margins.getLabelHorizontalGap(); } else { // even, so it's an actual label totalWidth += margins.getLabelWidth(); colwidth[i] = margins.getLabelWidth(); } } table = new PdfPTable(realCols); table.setTotalWidth(totalWidth); table.setWidths(colwidth); table.setLockedWidth(true); table.getDefaultCell().setPadding(0); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_MIDDLE); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); }
public void cellLayout(final PdfPCell cell, final Rectangle position, final PdfContentByte[] canvases) { try { final BaseFont bf = font.getCalculatedBaseFont(false); float availableWidth = position.getWidth(); float contentWidth = bf.getWidthPoint(content, font.getSize()); final String newContent; if (contentWidth > availableWidth) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Need to truncate '" + content + "'"); } final int contentLength = content.length(); int leftChar = 0; availableWidth -= bf.getWidthPoint("...", font.getSize()); while (leftChar < contentLength) { availableWidth -= bf.getWidthPoint(content.charAt(leftChar), font.getSize()); if (availableWidth > 0) { leftChar++; } else { break; } } newContent = content.substring(0, leftChar) + "..."; } else { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Not truncating '" + content + "'"); } newContent = content; } final PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS]; final ColumnText ct = new ColumnText(canvas); ct.setSimpleColumn(position); ct.addElement(new Paragraph(newContent, font)); ct.go(); } catch (final DocumentException e) { throw new ExceptionConverter(e); } }
/** * Fills out the total number of pages before the document is closed. * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onCloseDocument(PdfWriter writer, Document document) { ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)),2,2, 0); }