private void createGridColumnHeader(PdfPTable table, Collection<ColumnHeader> topHeaders, int maxHeaderLevel) throws Exception { for (int i = 1; i < 50; i++) { List<ColumnHeader> result = new ArrayList<ColumnHeader>(); generateGridHeadersByLevel(topHeaders, i, result); for (ColumnHeader header : result) { PdfPCell cell = new PdfPCell(createParagraph(header)); if (header.getBgColor() != null) { int[] colors = header.getBgColor(); cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2])); } cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(header.getAlign()); cell.setColspan(header.getColspan()); if (header.getColumnHeaders().size() == 0) { int rowspan = maxHeaderLevel - (header.getLevel() - 1); if (rowspan > 0) { cell.setRowspan(rowspan); } } table.addCell(cell); } } }
private void createGridTableDatas(PdfPTable table, Collection<ReportData> datas) { for (ReportData data : datas) { PdfPCell cell = new PdfPCell(createParagraph(data.getTextChunk())); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); int level = this.calculateIndentationCount(data.getTextChunk().getText()); if (data.getBgColor() != null) { int[] colors = data.getBgColor(); cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2])); } if (level == 0) { cell.setHorizontalAlignment(data.getAlign()); } else { cell.setIndent(20 * level); } table.addCell(cell); } }
public void validate(PdfRequest request, QRCode qr) throws PdfRequestNotValidException { PdfDocument document = request.getDocument(); DocumentErrorFactory errorFactory = new DocumentErrorFactory().withPageIndex(pageIndex).withBlockIndex(blockIndex); if( qr.getText() == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString( "You must specify text for qr") ); } if( qr.getColorRef() == null ){ qr.setBaseColor( new ColorFactory().getBlack() ); }else{ BaseColor color = new ColorFactory().getBaseColorByRef(document, qr.getColorRef() ); if( color == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString( "Could not find color ref for qr") ); } qr.setBaseColor(color); } }
public BaseColor createBaseColor( Color color ) throws CreateColorException{ if( color.getColor().length < 4 && color.getColor().length > 5 ){ throw new CreateColorException( "Incorrect length of color. Should be [cyan,magenta,yellow,black] or [cyan,magenta,yellow,black,tint]"); } if( color.getRef() == null ){ throw new CreateColorException( "You must specify a reference" ); } for( float c : color.getColor() ){ if( c > 1 || c < 0 ){ throw new CreateColorException( "[cyan,magenta,yellow,black] or [cyan,magenta,yellow,black,tint] must be between 0 and 1" ); } } float[] colors = color.getColor(); CMYKColor baseColor = new CMYKColor( colors[0],colors[1],colors[2],colors[3] ); if( color.getColor().length == 4 ){ return baseColor; } return new SpotColor(new PdfSpotColor(color.getRef(), baseColor),colors[4]); }
/** * This method checks whether two colors are approximately equal. As the * sample document only uses CMYK colors, only this comparison has been * implemented yet. */ boolean approximates(BaseColor colorA, BaseColor colorB) { if (colorA == null || colorB == null) return colorA == colorB; if (colorA instanceof CMYKColor && colorB instanceof CMYKColor) { CMYKColor cmykA = (CMYKColor) colorA; CMYKColor cmykB = (CMYKColor) colorB; float c = Math.abs(cmykA.getCyan() - cmykB.getCyan()); float m = Math.abs(cmykA.getMagenta() - cmykB.getMagenta()); float y = Math.abs(cmykA.getYellow() - cmykB.getYellow()); float k = Math.abs(cmykA.getBlack() - cmykB.getBlack()); return c+m+y+k < 0.01; } // TODO: Implement comparison for other color types return false; }
/** * The OP's original code transformed into Java */ void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setColorFill(new BaseColor(255,200,200)); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
/** * The OP's code transformed into Java changed with the work-around. */ void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.setColorFill(new BaseColor(255,200,200)); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.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. 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/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(); } }
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfWriter writer = canvases[0].getPdfWriter(); float x = position.getLeft(); float y = position.getBottom(); Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5); RadioCheckField checkbox = new RadioCheckField( writer, rect, name, "Yes"); checkbox.setCheckType(RadioCheckField.TYPE_CROSS); checkbox.setChecked(check); // change: set border color checkbox.setBorderColor(BaseColor.BLACK); try { pdfStamper.addAnnotation(checkbox.getCheckField(), page); } catch (Exception e) { throw new ExceptionConverter(e); } }
@Test public void testOPCode() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 ); PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT; PdfAnnotation linkRed = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" ); PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" ); BaseColor baseColorRed = new BaseColor(255,0,0); BaseColor baseColorGreen = new BaseColor(0,255,0); linkRed.setColor(baseColorRed); linkGreen.setColor(baseColorGreen); double angleDegrees = 10; double angleRadians = Math.PI*angleDegrees/180; stamper.addAnnotation(linkRed, 1); linkGreen.applyCTM(AffineTransform.getRotateInstance(angleRadians)); stamper.addAnnotation(linkGreen, 1); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation without appearance on a page without rotation. Everything looks ok. * </p> * @see #testCreateEllipseAppearance() * @see #testCreateEllipseOnRotated() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipse() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-ellipse.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); stamper.addAnnotation(annotation, 1); stamper.close(); reader.close(); } }
/** * <a href="http://stackoverflow.com/questions/43205385/trying-to-draw-an-ellipse-annotation-and-the-border-on-the-edges-goes-thin-and-t"> * Trying to draw an ellipse annotation and the border on the edges goes thin and thik when i try to roatate pdf itext5 * </a> * <p> * This test creates an ellipse annotation without appearance on a page with rotation. * The ellipse form looks ok but it is moved to the right of the actual appearance rectangle when viewed in Adobe Reader. * This is caused by iText creating a non-standard rectangle, the lower left not being the lower left etc. * </p> * @see #testCreateEllipse() * @see #testCreateEllipseAppearance() * @see #testCreateEllipseAppearanceOnRotated() * @see #testCreateCorrectEllipseAppearanceOnRotated() */ @Test public void testCreateEllipseOnRotated() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-rotated-ellipse.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); reader.getPageN(1).put(PdfName.ROTATE, new PdfNumber(90)); PdfStamper stamper = new PdfStamper(reader, outputStream); Rectangle rect = new Rectangle(202 + 6f, 300, 200 + 100, 300 + 150); PdfAnnotation annotation = PdfAnnotation.createSquareCircle(stamper.getWriter(), rect, null, false); annotation.setFlags(PdfAnnotation.FLAGS_PRINT); annotation.setColor(BaseColor.RED); annotation.setBorderStyle(new PdfBorderDictionary(3.5f, PdfBorderDictionary.STYLE_SOLID)); stamper.addAnnotation(annotation, 1); stamper.close(); reader.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(); }
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor color) { float posX = Utilities.millimetersToPoints(x); float posY = Utilities.millimetersToPoints(y); float widthX = Utilities.millimetersToPoints(width + x); float heightY = Utilities.millimetersToPoints(height + y); Rectangle rectangle = new Rectangle(posX, posY, widthX, heightY); PdfContentByte canvas = writer.getDirectContent(); rectangle.setBorder(Rectangle.BOX); rectangle.setBorderWidth(1); rectangle.setBorderColor(color); canvas.rectangle(rectangle); }
/** * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer"> * Filling a PDF with iTextsharp and then hiding the base layer * </a> * <p> * This test shows how to cover all content using a white rectangle. * </p> */ @Test public void testHideContenUnderRectangle() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { Rectangle pageSize = pdfReader.getPageSize(page); PdfContentByte canvas = pdfStamper.getOverContent(page); canvas.setColorFill(BaseColor.WHITE); canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight()); canvas.fill(); } pdfStamper.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/31730278/extract-text-from-pdf-between-two-dividers-with-itextsharp"> * Extract text from PDF between two dividers with ITextSharp * </a> * <br> * <a href="http://www.tjsc.jus.br/institucional/diario/a2015/20150211600.PDF"> * 20150211600.PDF * </a> * <p> * This test applies the {@link DividerAndColorAwareTextExtractionStrategy} to the OP's sample * document, page 346, to demonstrate its use. * </p> */ @Test public void test20150211600_346() throws IOException, DocumentException { InputStream resourceStream = getClass().getResourceAsStream("20150211600.PDF"); BaseColor headerColor = new CMYKColor(0.58f, 0.17f, 0, 0.56f); try { PdfReader reader = new PdfReader(resourceStream); String content = extractAndStore(reader, new File(RESULT_FOLDER, "20150211600.%s.%s.txt").toString(), 346, 346, headerColor); System.out.println("\nText 20150211600.PDF\n************************"); System.out.println(content); System.out.println("************************"); } finally { if (resourceStream != null) resourceStream.close(); } }
String extractAndStore(PdfReader reader, String format, int from, int to, BaseColor headerColor) throws IOException { StringBuilder builder = new StringBuilder(); for (int page = from; page <= to; page++) { PdfReaderContentParser parser = new PdfReaderContentParser(reader); DividerAwareTextExtrationStrategy strategy = parser.processContent(page, new DividerAndColorAwareTextExtractionStrategy(810, 30, 20, 575, headerColor)); List<Section> sections = strategy.getSections(); int i = 0; for (Section section : sections) { String sectionText = strategy.getResultantText(section); Files.write(Paths.get(String.format(format, page, i)), sectionText.getBytes("UTF8")); builder.append("--\n") .append(sectionText) .append('\n'); i++; } builder.append("\n\n"); } return builder.toString(); }
/** * <a href="http://stackoverflow.com/questions/38605538/itextpdf-redaction-partly-redacted-text-string-is-fully-removed"> * itextpdf Redaction :Partly redacted text string is fully removed * </a> * <br/> * <a href="https://drive.google.com/file/d/0B42NqA5UnXMVMDc4MnE5VmU5YVk/view"> * Document.pdf * </a> * <p> * This indeed is a case which shows that glyphs are completely removed even if their * bounding box merely minutely intersects the redaction area. While not desired by * the OP, this is how <code>PdfCleanUp</code> works. * </p> * * @see #testRedactStrictForMayankPandey() * @see #testRedactStrictForMayankPandeyLarge() */ @Test public void testRedactLikeMayankPandey() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("Document.pdf"); OutputStream result = new FileOutputStream(new File(OUTPUTDIR, "Document-redacted.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfCleanUpProcessor cleaner= null; PdfStamper stamper = new PdfStamper(reader, result); stamper.setRotateContents(false); List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>(); Rectangle rectangle = new Rectangle(380, 640, 430, 665); cleanUpLocations.add(new PdfCleanUpLocation(1, rectangle, BaseColor.BLACK)); cleaner = new PdfCleanUpProcessor(cleanUpLocations, stamper); cleaner.cleanUp(); stamper.close(); reader.close(); } }
/** * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onStartPage(PdfWriter writer, Document document) { if (writer.getPageNumber() < 3) { PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.setColorFill(BaseColor.PINK); cb.beginText(); cb.setFontAndSize(helv, 48); cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); cb.endText(); cb.restoreState(); } }
@Override public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas) { BaseColor color = colorProviders.apply(percent); if (color != null) { PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS]; cb.saveState(); cb.setColorFill(color); cb.rectangle( rect.getLeft() + margin.marginLeft, rect.getBottom() + margin.marginBottom, rect.getWidth() * percent - (margin.marginLeft + margin.marginRight), rect.getHeight() - (margin.marginTop + margin.marginBottom)); cb.fill(); cb.restoreState(); } }
public Styles initDefaults() { FontDescriptor defaultFont = fontDescriptor(defaultFontName(), defaultFontSize(), Font.NORMAL, BaseColor.BLACK); registeredColors.put(DEFAULT_COLOR, BaseColor.BLACK); registeredFonts.put(DEFAULT_FONT, defaultFont); registeredFonts.put(CODE_FONT, fontDescriptor(verbatimBaseFont(), defaultFontSize(), Font.NORMAL, BaseColor.BLACK)); registeredFonts.put(INLINE_CODE_FONT, fontDescriptor(verbatimBaseFont(), defaultFontSize(), Font.NORMAL, BaseColor.BLACK)); registeredColors.put(INLINE_CODE_BACKGROUND, Colors.VERY2_LIGHT_GRAY); registeredFonts.put(H1_FONT, fontDescriptor(defaultFontName(), 18.0f, Font.BOLD, BaseColor.BLACK)); registeredFonts.put(H2_FONT, fontDescriptor(defaultFontName(), 16.0f, Font.BOLD, BaseColor.DARK_GRAY)); registeredFonts.put(H3_FONT, fontDescriptor(defaultFontName(), 14.0f, Font.BOLD, BaseColor.DARK_GRAY)); registeredFonts.put(H4_FONT, fontDescriptor(defaultFontName(), 14.0f, Font.ITALIC, BaseColor.DARK_GRAY)); registeredColors.put(TABLE_ALTERNATE_BACKGROUND, Colors.VERY2_LIGHT_GRAY); registeredFonts.put(TABLE_HEADER_FONT, fontDescriptor(defaultFontName(), 14.0f, Font.ITALIC, BaseColor.WHITE)); registeredColors.put(TABLE_HEADER_BACKGROUD, BaseColor.BLACK); registeredFonts.put(TABLE_BODY_FONT, defaultFont); registeredColors.put(TABLE_BODY_CELL_BORDER_COLOR, Colors.LIGHT_GRAY); registeredColors.put(BLOCKQUOTE_COLOR, Colors.LIGHT_GRAY); return this; }
public void drawFooter(PdfContentByte canvas, PageInfos pageInfos) { if (pageInfos.getRawPageNumber() == 1 && !footerOnFirstPage) return; if (drawLine) { BaseColor lineColor = styles.getColorOrDefault(HEADER_LINE_COLOR); canvas.saveState(); canvas.setColorStroke(lineColor); canvas.setLineWidth(1.2f); canvas.moveTo(rect.getLeft(), rect.getBottom() - 6); canvas.lineTo(rect.getRight(), rect.getBottom() - 6); canvas.stroke(); canvas.restoreState(); } float bottom = rect.getBottom() - 20; Phrase footer = footerText(pageInfos); if (footer != null) { showTextAligned(canvas, Element.ALIGN_LEFT, footer, rect.getLeft(), bottom, 0); } Font footerFont = styles.getFontOrDefault(FOOTER_FONT); Phrase page = new Phrase(pageInfos.getFormattedPageNumber(), footerFont); showTextAligned(canvas, Element.ALIGN_RIGHT, page, rect.getRight(), bottom, 0); }
/** * Adds the footer style row for the field to the PDF table. * * @param table * the table. * @param font * the font to use. * @param name * the field name. * @param value * the field value. */ private static void addFooter(PdfPTable table, Font font, String name, Integer value) { PdfPCell emptyCell = new PdfPCell(); emptyCell.setBorder(ReportServiceHelper.PDF_NO_BORDER); table.addCell(emptyCell); PdfPCell footerNameCell = new PdfPCell(); footerNameCell.setBorderColorTop(BaseColor.BLACK); footerNameCell .setHorizontalAlignment(ReportServiceHelper.PDF_ALIGN_LEFT); footerNameCell.addElement(new com.itextpdf.text.Phrase(name, font)); footerNameCell.setBorder(ReportServiceHelper.PDF_BORDER_TOP); table.addCell(footerNameCell); PdfPCell footerValueCell = new PdfPCell(); footerValueCell.setBorderColorTop(BaseColor.BLACK); if (value != null) { com.itextpdf.text.Paragraph p = new com.itextpdf.text.Paragraph( value.toString(), font); p.setAlignment(ReportServiceHelper.PDF_ALIGN_RIGHT); footerValueCell.addElement(p); } footerValueCell.setBorder(ReportServiceHelper.PDF_BORDER_TOP); table.addCell(footerValueCell); }
public GeneratePDF() { try { bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.CP1250, BaseFont.EMBEDDED); catFont = new Font(bf, 18, Font.BOLD); redFont = new Font(bf, 14, Font.BOLD, BaseColor.RED); subFont = new Font(bf, 16, Font.BOLD); smallBold = new Font(bf, 12, Font.BOLD); } catch (DocumentException | IOException e) { e.printStackTrace(); } }
public GeneratePDFZeb() { try { bf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.CP1250, BaseFont.EMBEDDED); catFont = new Font(bf, 18, Font.BOLD); redFont = new Font(bf, 14, Font.BOLD, BaseColor.RED); subFont = new Font(bf, 16, Font.BOLD); smallBold = new Font(bf, 12, Font.BOLD); } catch (DocumentException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void emitMethodSummary(final PdfPTable summaryTable, MethodEntry methodEntry) { log.debug("Emitting summary for method {}", methodEntry.signature()); methodEntry.patterns().forEach(new Consumer<String>() { @Override public void accept(String pattern) { Phrase phrase = new Phrase(pattern, FontFactory.getFont("Arial", 10, BLACK)); PdfPCell patternCell = new PdfPCell(phrase); patternCell.setColspan(SUMMARY_NB_COLS - 2); patternCell.setBorder(Rectangle.BOTTOM); patternCell.setBorderColor(BaseColor.LIGHT_GRAY); summaryTable.addCell(emptyCell(2)); summaryTable.addCell(patternCell); } }); }
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 addTitle() throws DocumentException { Paragraph title = new Paragraph(); title.setAlignment(1); title.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD, BaseColor.RED)); title.add(new Phrase("Java Assignment")); document.add(title); addEmptyLine(title, 2); Paragraph name = new Paragraph(); name.setAlignment(0); name.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, BaseColor.GRAY)); name.add(new Phrase(" Name : " + FileUtil.name + "\n")); name.add(new Phrase(" Enrollno : " + FileUtil.rollno + "\n\n")); document.add(name); addEmptyLine(title, 2); }
/** * 將排序過的圖片轉成PDF * * @param pageSize * pdf的文件大小:A4 or B3 etc... * @param sourceFolderPath * 圖片所在的資料夾路徑 * @param pathList * 排序過的圖片列表 * @param targetPdfPath * 要儲存的的PDF路徑 * @return * @throws Exception */ public static boolean comicFolderToPDF(Rectangle pageSize, String sourceFolderPath, ArrayList<String> pathList, String targetPdfPath) throws Exception { boolean result = false; Document document = new Document(pageSize); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetPdfPath)); writer.setPageEvent(new HeaderFooter(14)); document.open(); for (String filename : pathList) { String filePath = sourceFolderPath + File.separator + filename; document.newPage(); Image img = Image.getInstance(filePath); img.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight()); img.setBorderColor(BaseColor.WHITE); document.add(img); } result = true; document.close(); return result; }
public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) { BaseFont bf = null; try { bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); } catch (Exception e) { e.printStackTrace(); } Font font = new Font(bf, size, style, color); font.setColor(color); return font; }
private void writeQuestions(Paragraph paragraph, Document document, boolean showCorrectAnswer, ArrayList<Question> qlist) throws DocumentException, IOException { for (int i = 0; i < qlist.size(); i++) { Question question = qlist.get(i); paragraph.clear(); // addQuestionNumber(paragraph, i, qlist.size()); addQuestionText(paragraph, question, i); addAnswerTexts(paragraph, showCorrectAnswer, question); fixFonts(paragraph); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); table.setKeepTogether(true); PdfPCell cell = new PdfPCell(); cell.addElement(paragraph); cell.setBorderColor(BaseColor.WHITE); cell.setBorder(PdfPCell.NO_BORDER); table.addCell(cell); document.add(table); } }
private PdfContentByte bulidCellBorder(PdfContentByte[] canvases,Border border){ PdfContentByte cb=canvases[PdfPTable.LINECANVAS]; cb.saveState(); BigDecimal w=new BigDecimal(border.getWidth()); cb.setLineWidth(w.divide(new BigDecimal(2),10,RoundingMode.HALF_UP).floatValue()); if(border.getStyle().equals(BorderStyle.dashed)){ cb.setLineDash(new float[]{2f,3f,1f},2); } String borderColor[]=border.getColor().split(","); cb.setColorStroke(new BaseColor(Integer.valueOf(borderColor[0]),Integer.valueOf(borderColor[1]),Integer.valueOf(borderColor[2]))); return cb; }
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(); }
/** * Adds a header to every page * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { PdfPTable table = new PdfPTable(3); try { table.setWidths(new int[]{40,5,10}); table.setTotalWidth(100); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); Font font=new Font(chineseFont,8); font.setColor(new BaseColor(55,55,55)); Paragraph paragraph=new Paragraph("第 "+writer.getPageNumber()+" 页 共",font); paragraph.setAlignment(Element.ALIGN_RIGHT); table.addCell(paragraph); Image img=Image.getInstance(total); img.scaleAbsolute(28, 28); PdfPCell cell = new PdfPCell(img); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); PdfPCell c = new PdfPCell(new Paragraph("页",font)); c.setHorizontalAlignment(Element.ALIGN_LEFT); c.setBorder(Rectangle.NO_BORDER); table.addCell(c); float center=(document.getPageSize().getWidth())/2-120/2; table.writeSelectedRows(0, -1,center,30, writer.getDirectContent()); } catch(DocumentException de) { throw new ExceptionConverter(de); } }
protected Font createFont(TextChunk textChunk) { Font font = new Font(chineseFont); if (textChunk.getFontColor() != null) { int[] colors = textChunk.getFontColor(); font.setColor(new BaseColor(colors[0], colors[1], colors[2])); } if (textChunk.getFontSize() > 0) { font.setSize(textChunk.getFontSize()); } font.setStyle(textChunk.getFontStyle()); return font; }
public void validateParagraph(PdfRequest request, Paragraph paragraph,DocumentErrorFactory errorFactory ) throws PdfRequestNotValidException{ PdfDocument document = request.getDocument(); if( paragraph.getLeading() <= 0 ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Font leading is 0 or less") ); } if( paragraph.getColorRef() == null ){ paragraph.setBaseColor( new ColorFactory().getBlack() ); }else{ BaseColor color = new ColorFactory().getBaseColorByRef(document, paragraph.getColorRef() ); if( color == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Could not find color ref for paragraph")); } paragraph.setBaseColor(color); } if( paragraph.getFontRef() != null ){ BaseFont font = new FontFactory().getBaseFontByRef(document,paragraph.getFontRef() ); if( font == null ){ throw new PdfRequestNotValidException(errorFactory.appendErrorString("Could not find font ref for paragraph")); } paragraph.setBaseFont(font); } if( paragraph.getHorizontalAlign() != null ){ HorizontalAlign align = HorizontalAlign.getByName(paragraph.getHorizontalAlign()); if( align == null ){ throw new PdfRequestNotValidException( errorFactory.appendErrorString("Horizontal align must be any of [left,center,right]" )); } } }