com.itextpdf.text.Phrase Java Examples
The following examples show how to use
com.itextpdf.text.Phrase.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PDFSampleMain.java From tutorials with MIT License | 7 votes |
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException { Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI()); Image img = Image.getInstance(path.toAbsolutePath().toString()); img.scalePercent(10); PdfPCell imageCell = new PdfPCell(img); table.addCell(imageCell); PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2")); horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(horizontalAlignCell); PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3")); verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell(verticalAlignCell); }
Example #2
Source File: StampUnicodeText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #3
Source File: ImportPageWithoutFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * This method creates a PDF with a single styled paragraph. */ static byte[] createSimpleTextPdf() throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); Paragraph paragraph = new Paragraph(); paragraph.add(new Phrase("Beware: ", new Font(FontFamily.HELVETICA, 12, Font.BOLDITALIC))); paragraph.add(new Phrase("The implementation of ", new Font(FontFamily.HELVETICA, 12, Font.ITALIC))); paragraph.add(new Phrase("MarginFinder", new Font(FontFamily.COURIER, 12, Font.ITALIC))); paragraph.add(new Phrase(" is far from optimal. It is not even correct as it includes all curve control points which is too much. Furthermore it ignores stuff like line width or wedge types. It actually merely is a proof-of-concept.", new Font(FontFamily.HELVETICA, 12, Font.ITALIC))); document.add(paragraph); document.close(); return baos.toByteArray(); }
Example #4
Source File: UseRowspan.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans"> * Changing rowspans * </a> * <p> * Helper method of the OP. * </p> * @see #testUseRowspanLikeUser7968180() * @see #testUseRowspanLikeUser7968180Fixed() * @see #createPdf(String) * @see #createPdfFixed(String) */ private static void addCellToTableCzech(PdfPTable table, int horizontalAlignment, int verticalAlignment, String value, int colspan, int rowspan, String fontType, float fontSize) { BaseFont base = null; try { base = BaseFont.createFont(fontType, BaseFont.CP1250, BaseFont.EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font font = new Font(base, fontSize); PdfPCell cell = new PdfPCell(new Phrase(value, font)); cell.setColspan(colspan); cell.setRowspan(rowspan); cell.setHorizontalAlignment(horizontalAlignment); cell.setVerticalAlignment(verticalAlignment); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); }
Example #5
Source File: DoubleSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #6
Source File: InterlineSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); }
Example #7
Source File: InterlineSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); }
Example #8
Source File: UseColumnText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); }
Example #9
Source File: StampUnicodeText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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> * <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, cf. * {@link #testAddUnicodeStampEg_01()}. This test creates a new PDF with the same * font and chunk as stamped by the OP. Adobe Reader has no problem with it either. * </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 testCreateUnicodePdf() throws DocumentException, IOException { Document document = new Document(); try ( OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "unicodePdf.pdf")) ) { PdfWriter.getInstance(document, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); document.open(); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); document.add(p); document.close(); } }
Example #10
Source File: StampUnicodeText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <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(); } }
Example #11
Source File: JFreeChartTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) { PdfWriter writer = null; Document document = new Document(); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte pdfContentByte = writer.getDirectContent(); PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(50, 50); Graphics2D graphics2d = new PdfGraphics2D(pdfTemplateChartHolder, 50, 50); Rectangle2D chartRegion = new Rectangle2D.Double(0, 0, 50, 50); chart.draw(graphics2d, chartRegion); graphics2d.dispose(); Image chartImage = Image.getInstance(pdfTemplateChartHolder); document.add(chartImage); PdfPTable table = new PdfPTable(5); // the cell object // we add a cell with colspan 3 PdfPCell cellX = new PdfPCell(new Phrase("A")); cellX.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cellX.setRowspan(6); table.addCell(cellX); PdfPCell cellA = new PdfPCell(new Phrase("A")); cellA.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cellA.setColspan(4); table.addCell(cellA); PdfPCell cellB = new PdfPCell(new Phrase("B")); table.addCell(cellB); PdfPCell cellC = new PdfPCell(new Phrase("C")); table.addCell(cellC); PdfPCell cellD = new PdfPCell(new Phrase("D")); table.addCell(cellD); PdfPCell cellE = new PdfPCell(new Phrase("E")); table.addCell(cellE); PdfPCell cellF = new PdfPCell(new Phrase("F")); table.addCell(cellF); PdfPCell cellG = new PdfPCell(new Phrase("G")); table.addCell(cellG); PdfPCell cellH = new PdfPCell(new Phrase("H")); table.addCell(cellH); PdfPCell cellI = new PdfPCell(new Phrase("I")); table.addCell(cellI); PdfPCell cellJ = new PdfPCell(new Phrase("J")); cellJ.setColspan(2); cellJ.setRowspan(3); //instead of // cellJ.setImage(chartImage); //the OP now uses Chunk chunk = new Chunk(chartImage, 20, -50); cellJ.addElement(chunk); //presumably with different contents of the other cells at hand table.addCell(cellJ); PdfPCell cellK = new PdfPCell(new Phrase("K")); cellK.setColspan(2); table.addCell(cellK); PdfPCell cellL = new PdfPCell(new Phrase("L")); cellL.setColspan(2); table.addCell(cellL); PdfPCell cellM = new PdfPCell(new Phrase("M")); cellM.setColspan(2); table.addCell(cellM); document.add(table); } catch (Exception e) { e.printStackTrace(); } document.close(); }
Example #12
Source File: TableKeepTogether.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
private void printPage3(Document document, PdfContentByte canvas) throws DocumentException { int cols = 3; int rows = 15; PdfPTable table = new PdfPTable(cols); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { table.addCell(new Phrase("Cell " + row + ", " + col)); } } table.setSpacingBefore(5); Rectangle docBounds = document.getPageSize(); Rectangle upper = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20)); upper.setBackgroundColor(new BaseColor(23, 142, 255, 20)); Rectangle lower = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600); lower.setBackgroundColor(new BaseColor(255, 142, 23, 20)); Rectangle[] rectangles = new Rectangle[] { upper, lower }; for (Rectangle bounds : rectangles) { bounds.setBorder(Rectangle.BOX); bounds.setBorderColor(BaseColor.BLACK); bounds.setBorderWidth(1); canvas.rectangle(bounds); } rectangles = drawKeepTogether(new Paragraph("This table should keep together!"), canvas, rectangles); rectangles = drawKeepTogether(table, canvas, rectangles); }
Example #13
Source File: WatermarkPdfTests.java From kbase-doc with Apache License 2.0 | 5 votes |
/** * pdf 用文字加水印,存在问题,如何支持中文 * @author eko.zhan at 2018年9月2日 下午1:44:40 * @throws FileNotFoundException * @throws IOException * @throws DocumentException */ @Test public void testVisioAsPdfWithText() throws FileNotFoundException, IOException, DocumentException{ File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx"); File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf"); if (!outputFile.exists()) { convert(inputFile, outputFile); } File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf"); //转换成 pdf 后利用 itext 加水印 PdfReader reader = new PdfReader(new FileInputStream(outputFile)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile)); int pageNo = reader.getNumberOfPages(); Font f = new Font(FontFamily.HELVETICA, 28); Phrase p = new Phrase("Xiaoi Robot", f); for (int i=1;i<=pageNo;i++) { PdfContentByte over = stamper.getOverContent(i); over.saveState(); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.5f); over.setGState(gs1); ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0); over.restoreState(); } stamper.close(); reader.close(); }
Example #14
Source File: PDFSampleMain.java From tutorials with MIT License | 5 votes |
private static void addTableHeader(PdfPTable table) { Stream.of("column header 1", "column header 2", "column header 3") .forEach(columnTitle -> { PdfPCell header = new PdfPCell(); header.setBackgroundColor(BaseColor.LIGHT_GRAY); header.setBorderWidth(2); header.setPhrase(new Phrase(columnTitle)); table.addCell(header); }); }
Example #15
Source File: PdfExportDialogFragment.java From geopaparazzi with GNU General Public License v3.0 | 5 votes |
private void addKeyValueToTableRow(PdfPTable table, String key, String value) { PdfPCell keyCell = new PdfPCell(new Paragraph(key)); keyCell.setHorizontalAlignment(Element.ALIGN_CENTER); keyCell.setVerticalAlignment(Element.ALIGN_MIDDLE); keyCell.setPadding(10); table.addCell(keyCell); PdfPCell valueCell = new PdfPCell(new Phrase(value)); valueCell.setHorizontalAlignment(Element.ALIGN_CENTER); valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE); valueCell.setPadding(10); table.addCell(valueCell); }
Example #16
Source File: CreateLink.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/34408764/create-local-link-in-rotated-pdfpcell-in-itextsharp"> * Create local link in rotated PdfPCell in iTextSharp * </a> * <p> * This is the equivalent Java code for the C# code in the question. Indeed, this code * also gives rise to the broken result. The cause is simple: Normally iText does not * touch the current transformation matrix. So the chunk link creation code assumes the * current user coordinate system to be the same as used for positioning annotations. * But in case of rotated cells iText does change the transformation matrix and * consequently the chunk link creation code positions the annotation at the wrong * location. * </p> */ @Test public void testCreateLocalLinkInRotatedCell() throws IOException, DocumentException { Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "local-link.pdf"))); doc.open(); PdfPTable linkTable = new PdfPTable(2); PdfPCell linkCell = new PdfPCell(); linkCell.setHorizontalAlignment(Element.ALIGN_CENTER); linkCell.setRotation(90); linkCell.setFixedHeight(70); Anchor linkAnchor = new Anchor("Click here"); linkAnchor.setReference("#target"); Paragraph linkPara = new Paragraph(); linkPara.add(linkAnchor); linkCell.addElement(linkPara); linkTable.addCell(linkCell); PdfPCell linkCell2 = new PdfPCell(); Anchor linkAnchor2 = new Anchor("Click here 2"); linkAnchor2.setReference("#target"); Paragraph linkPara2 = new Paragraph(); linkPara2.add(linkAnchor2); linkCell2.addElement(linkPara2); linkTable.addCell(linkCell2); linkTable.addCell(new PdfPCell(new Phrase("cell 3"))); linkTable.addCell(new PdfPCell(new Phrase("cell 4"))); doc.add(linkTable); doc.newPage(); Anchor destAnchor = new Anchor("top"); destAnchor.setName("target"); PdfPTable destTable = new PdfPTable(1); PdfPCell destCell = new PdfPCell(); Paragraph destPara = new Paragraph(); destPara.add(destAnchor); destCell.addElement(destPara); destTable.addCell(destCell); destTable.addCell(new PdfPCell(new Phrase("cell 2"))); destTable.addCell(new PdfPCell(new Phrase("cell 3"))); destTable.addCell(new PdfPCell(new Phrase("cell 4"))); doc.add(destTable); doc.close(); }
Example #17
Source File: CreateSignature.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <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); } }
Example #18
Source File: FindFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
public static PdfPTable getFooterTable(int x, int y) { java.util.Date date = new java.util.Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); String month = sdf.format(date); System.out.println("Month : " + month); PdfPTable table = new PdfPTable(1); table.setTotalWidth(120); table.setLockedWidth(true); table.getDefaultCell().setFixedHeight(20); table.getDefaultCell().setBorder(Rectangle.TOP); table.getDefaultCell().setBorder(Rectangle.LEFT); table.getDefaultCell().setBorder(Rectangle.RIGHT); table.getDefaultCell().setBorderColorTop(BaseColor.BLUE); table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE); table.getDefaultCell().setBorderColorRight(BaseColor.BLUE); table.getDefaultCell().setBorderWidthTop(1f); table.getDefaultCell().setBorderWidthLeft(1f); table.getDefaultCell().setBorderWidthRight(1f); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); Font font1 = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.BLUE); table.addCell(new Phrase("CONTROLLED COPY", font1)); table.getDefaultCell().setFixedHeight(20); table.getDefaultCell().setBorder(Rectangle.LEFT); table.getDefaultCell().setBorder(Rectangle.RIGHT); table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE); table.getDefaultCell().setBorderColorRight(BaseColor.BLUE); table.getDefaultCell().setBorderWidthLeft(1f); table.getDefaultCell().setBorderWidthRight(1f); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); Font font = new Font(FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.RED); table.addCell(new Phrase(month, font)); table.getDefaultCell().setFixedHeight(20); table.getDefaultCell().setBorder(Rectangle.LEFT); table.getDefaultCell().setBorder(Rectangle.RIGHT); table.getDefaultCell().setBorder(Rectangle.BOTTOM); table.getDefaultCell().setBorderColorLeft(BaseColor.BLUE); table.getDefaultCell().setBorderColorRight(BaseColor.BLUE); table.getDefaultCell().setBorderColorBottom(BaseColor.BLUE); table.getDefaultCell().setBorderWidthLeft(1f); table.getDefaultCell().setBorderWidthRight(1f); table.getDefaultCell().setBorderWidthBottom(1f); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(new Phrase("BLR DESIGN DEPT.", font1)); return table; }
Example #19
Source File: StampHeader.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <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(); }
Example #20
Source File: WatermarkPdfTests.java From kbase-doc with Apache License 2.0 | 4 votes |
/** * pdf 用图片加水印 * @author eko.zhan at 2018年9月2日 下午1:44:58 * @throws FileNotFoundException * @throws IOException * @throws DocumentException */ @Test public void testVisioAsPdfWithImg() throws FileNotFoundException, IOException, DocumentException{ File inputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx.vsdx"); File outputFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice.pdf"); if (!outputFile.exists()) { convert(inputFile, outputFile); } File destFile = new File("E:/ConvertTester/TestFiles/I_am_a_vsdx_libreoffice_watermark.pdf"); final String IMG = "D:\\Xiaoi\\logo\\logo.png"; //转换成 pdf 后利用 itext 加水印 PdfReader reader = new PdfReader(new FileInputStream(outputFile)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile)); int pageNo = reader.getNumberOfPages(); // text watermark Font f = new Font(FontFamily.HELVETICA, 30); Phrase p = new Phrase("Xiaoi Robot Image", f); // image watermark Image img = Image.getInstance(IMG); float w = img.getScaledWidth(); float h = img.getScaledHeight(); // transparency PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0.5f); // properties PdfContentByte over; Rectangle pagesize; float x, y; // loop over every page for (int i = 1; i <= pageNo; i++) { pagesize = reader.getPageSizeWithRotation(i); x = (pagesize.getLeft() + pagesize.getRight()) / 2; y = (pagesize.getTop() + pagesize.getBottom()) / 2; over = stamper.getOverContent(i); over.saveState(); over.setGState(gs1); if (i % 2 == 1) ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0); else over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2)); over.restoreState(); } stamper.close(); reader.close(); }
Example #21
Source File: HRPDFBuilderImpl.java From Spring-MVC-Blueprints with MIT License | 4 votes |
@SuppressWarnings("unchecked") @Override protected void buildPdfDocument(Map<String, Object> model, Document doc, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { // get data model which is passed by the Spring container List<HrmsLogin> users = (List<HrmsLogin>) model.get("allUsers"); doc.add(new Paragraph("Master List of Users")); PdfPTable table = new PdfPTable(4); table.setWidthPercentage(100.0f); table.setWidths(new float[] {3.0f, 2.0f, 2.0f, 2.0f}); table.setSpacingBefore(10); // define font for table header row Font font = FontFactory.getFont(FontFactory.HELVETICA); font.setColor(BaseColor.WHITE); // define table header cell PdfPCell cell = new PdfPCell(); cell.setBackgroundColor(BaseColor.BLUE); cell.setPadding(5); // write table header cell.setPhrase(new Phrase("Employee ID", font)); table.addCell(cell); cell.setPhrase(new Phrase("Username", font)); table.addCell(cell); cell.setPhrase(new Phrase("Password", font)); table.addCell(cell); cell.setPhrase(new Phrase("Role", font)); table.addCell(cell); // write table row data for (HrmsLogin user : users) { table.addCell(user.getHrmsEmployeeDetails().getEmpId()+""); table.addCell(user.getUsername()); table.addCell(user.getPassword()); table.addCell(user.getRole()); } doc.add(table); }
Example #22
Source File: PdfReportPageNumber.java From bdf3 with Apache License 2.0 | 2 votes |
/** * 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); }