public void createRoundRectangle(PdfContentByte cb, Block block ){ PdfDocument request = getPdfDocument(block); float[] positions = getBoundsInPs(block); float[] mmPositions = getBoundsInMMIncludeCutmark(block); PdfTemplate tp = cb.createTemplate(positions[2],positions[3]); tp.roundRectangle( 0, 0, positions[2], positions[3], SizeFactory.millimetersToPostscriptPoints( block.getRadius() ) ); // because pdf i calculated from bottom up cb.addTemplate( tp, positions[0], SizeFactory.millimetersToPostscriptPoints( request.getSize()[1] - ( mmPositions[1] + mmPositions[3])) ); }
public void print(String plot_pdf) { try { float width = jframe.getSize().width, height = jframe.getSize().height; Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf)); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(width, height); Graphics2D g2d = new PdfGraphics2D(template, width, height); jframe.paint(g2d); g2d.dispose(); canvas.addTemplate(template, 0, 0); document.close(); } catch (FileNotFoundException | DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Create the multipage PDF report from the internal list of JPanels. * @throws DocumentException */ public void createMultipagePDF() throws DocumentException { // Document defaults to A4, so specify the current dimensions Document doc= new Document(new Rectangle(pageWidth, pageHeight)); PdfWriter writer= PdfWriter.getInstance(doc, os); doc.open(); PdfContentByte cb= writer.getDirectContent(); // Iterate over tabs for (int i= 0; i != tabs.getTabCount(); ++i) { JPanel jp= (JPanel) tabs.getComponent(i); // Iterate over pages for (int currentPage= 0; currentPage < getNumPages(jp); ++currentPage) { doc.newPage(); // not needed for page 1, needed for >1 PdfTemplate template= cb.createTemplate(pageWidth, pageHeight); Graphics2D g2d= new PdfGraphics2D(template, pageWidth, pageHeight * (currentPage + 1)); jp.printAll(g2d); g2d.dispose(); cb.addTemplate(template, 0, 0); } } doc.close(); }
public static void writeToFile(File f, Component m) throws Exception { Graphics2D g2; Document document = new Document(new Rectangle( m.getBounds().x, m.getBounds().y, m.getBounds().width, m.getBounds().height )); PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(f)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(m.getSize().width, m.getSize().height); g2 = tp.createGraphicsShapes(m.getSize().width, m.getSize().height); m.paint(g2); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); }
private List<Element> renderGral(String raw) throws BadElementException, IOException { ChartDescriptor descriptor = new ChartDescriptorParser().parse(raw); PdfContentByte cb = writer.get().getDirectContent(); float width = (float) descriptor.getWidth(); float height = (float) descriptor.getHeight(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(template, width, height); GralRenderer renderer = new GralRenderer(); renderer.render(g2, descriptor); ArrayList<Element> elements = new ArrayList<Element>(1); elements.add(new ImgTemplate(template)); return elements; }
/** * Exports the specified JFreeChart to a PDF file using * <a href="http://itextpdf.com" target="_blank">iText</a>, bundled with * Fiji. The destination file is specified by the user in a save dialog * prompt. An error message is displayed if the file could not be saved. * Does nothing if {@code chart} is {@code null}. * * @param chart * the <a href="http://javadoc.imagej.net/JFreeChart/" target= * "_blank">JFreeChart </a> to export. * @param bounds * the Rectangle delimiting the boundaries within which the chart * should be drawn. * @see #exportChartAsPDF(JFreeChart, Rectangle) * @see #exportChartAsSVG(JFreeChart, Rectangle) * @see #exportChartAsSVG(JFreeChart, Rectangle, File) */ public static void exportChartAsPDF(final JFreeChart chart, final Rectangle bounds, final File f) throws FileNotFoundException, DocumentException { final int margin = 0; // page margins // Initialize writer final Document document = new Document(new com.itextpdf.text.Rectangle(bounds.width, bounds.height), margin, margin, margin, margin); final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f)); document.open(); final PdfContentByte cb = writer.getDirectContent(); final PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height); // Draw the chart. Release resources upon completion final Graphics2D g2 = tp.createGraphics(bounds.width, bounds.height, new DefaultFontMapper()); chart.draw(g2, bounds); g2.dispose(); // Write to file cb.addTemplate(tp, 0, 0); document.close(); }
public static void exportChartAsPDF( JFreeChart chart, Rectangle bounds, File file) throws IOException, DocumentException { System.out.println(file.getPath()); PdfWriter writer = null; com.itextpdf.text.Document document = new com.itextpdf.text.Document(); document.addCreator("CanReg5"); document.addCreationDate(); writer = PdfWriter.getInstance(document, new FileOutputStream( file)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(bounds.width, bounds.height); Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, bounds.width, bounds.height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); document.close(); }
public PdfPCellEvent createEvent(final Block block ){ return new PdfPCellEvent(){ public void cellLayout(PdfPCell cell, Rectangle rect,PdfContentByte[] canvas) { float radiusInPs = SizeFactory.millimetersToPostscriptPoints( block.getRadius() ); PdfContentByte cb = canvas[PdfPTable.LINECANVAS]; PdfTemplate template = cb.createTemplate( rect.getWidth() , rect.getHeight()); template.roundRectangle(0, 0, rect.getWidth() ,rect.getHeight() , radiusInPs); template.clip(); template.newPath(); if( block.getBaseColor() != null ){ template.setColorFill(block.getBaseColor()); } Border border = block.getBorder(); if( border != null ){ template.setLineWidth( SizeFactory.millimetersToPostscriptPoints( border.getThickness()) ); template.setColorStroke( border.getBaseColor()); } template.roundRectangle(0, 0, rect.getWidth() ,rect.getHeight() ,radiusInPs); if( block.getBaseColor() != null || border != null ){ if( block.getBaseColor() != null && border != null ){ template.fillStroke(); }else if( block.getBaseColor() != null ){ template.fill(); }else{ template.stroke(); } } cb.addTemplate( template, rect.getLeft(), rect.getBottom()); } }; }
/** * Exports the 3d graph as a pdf * * @param file The pdf file to which the data should be written * @param panel The chart panel that has to be exported */ public static void exportToPDF(File file, Chart3DPanel panel){ PdfWriter out = null; Document document = new com.itextpdf.text.Document(PageSize.A4.rotate()); int width = 800, height = 500; try{ out = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = out.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); @SuppressWarnings("deprecation") Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height); panel.getChart().draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch(Exception e){ // in case any error occurs tell the user what the error is (sometimes useful if there is a problem of writing rights) JOptionPane.showMessageDialog(GUIPrism.getGUI(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return; } document.close(); }
/** * Stores the logo in PDF format * @param width * @param height * @param fileName */ public void saveAsPDF(int width, int height, String fileName) { if (chart == null) { makeSequenceLogo(); } PdfWriter writer = null; Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
/** * Stores the logo in PDF format * @param width * @param height * @param fileName */ public void saveRAWAsPDF(int width, int height, String fileName) { ChartPanel logo = getRawLogoPanel(); PdfWriter writer = null; Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); logo.getChart().draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
/** * Save chart as a pdf file. * * @param chart * chart that should be saved * @param fileName * file name under which the file should be saved */ public static void writeChartToPDF(final JFreeChart chart, final String fileName) { PdfWriter writer = null; com.itextpdf.text.Document document = new com.itextpdf.text.Document( PageSize.A4); final int width = (int) PageSize.A4.getWidth(); final int height = (int) PageSize.A4.getHeight(); try { writer = PdfWriter.getInstance(document, new FileOutputStream( fileName + ".pdf")); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
/** * Save the chart as pdf. * * @param chart * chart that should be saved * @param fileName * file name under which chart should be saved */ public static void writeChartToPDF(final JFreeChart chart, final String fileName) { PdfWriter writer = null; com.itextpdf.text.Document document = new com.itextpdf.text.Document( PageSize.A4); final int width = (int) PageSize.A4.getWidth(); final int height = (int) PageSize.A4.getHeight(); try { writer = PdfWriter.getInstance(document, new FileOutputStream( fileName + ".pdf")); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
public static final void save(File file, Component c, int width, int height) { if (file == null) { logger.log(Level.WARNING, "no file selected"); return; } if (c == null) { logger.log(Level.WARNING, "no component provided"); return; } try { Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath())); document.addAuthor("UJMP v" + UJMP.UJMPVERSION); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper()); if (c instanceof CanRenderGraph) { ((CanRenderGraph) c).renderGraph(g2); } else { c.paint(g2); } g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); writer.close(); } catch (Exception e) { logger.log(Level.WARNING, "could not save PDF file", e); } }
/** * This method saves a chart as a PDF with given dimensions * * @param chart * @param width * @param height * @param fileName is a full path */ public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception { PdfWriter writer = null; Document document = new Document(new Rectangle(width, height)); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); throw e; } finally { document.close(); } }
@Test public void testOwnAppearances() throws IOException, DocumentException { try ( InputStream resourceStream = getClass().getResourceAsStream("/mkl/testarea/itext5/merge/testA4.pdf"); OutputStream outputStream = new FileOutputStream(new File(RESULT_FOLDER, "testA4-annotate-app.pdf")) ) { PdfReader reader = new PdfReader(resourceStream); PdfStamper stamper = new PdfStamper(reader, outputStream); BaseColor baseColorRed = new BaseColor(255,0,0); BaseColor baseColorGreen = new BaseColor(0,255,0); Rectangle linkLocation = new Rectangle( 100, 700, 100 + 200, 700 + 25 ); PdfName highlight = PdfAnnotation.HIGHLIGHT_INVERT; PdfAnnotation linkGreen = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "green" ); PdfTemplate appearance = PdfTemplate.createTemplate(stamper.getWriter(), linkLocation.getWidth(), linkLocation.getHeight()); appearance.setColorFill(baseColorGreen); appearance.rectangle(0, 0, linkLocation.getWidth(), linkLocation.getHeight()); appearance.fill(); double angleDegrees = 35; double angleRadians = Math.PI*angleDegrees/180; AffineTransform at = AffineTransform.getRotateInstance(angleRadians); appearance.setMatrix((float)at.getScaleX(), (float)at.getShearY(),(float) at.getShearX(), (float)at.getScaleY(),(float) at.getTranslateX(), (float)at.getTranslateY()); linkGreen.setAppearance(PdfName.N, appearance); linkGreen.setColor(baseColorGreen); stamper.addAnnotation(linkGreen, 1); PdfAnnotation linkRed = PdfAnnotation.createLink( stamper.getWriter(), linkLocation, highlight, "red" ); linkRed.setColor(baseColorRed); stamper.addAnnotation(linkRed, 1); stamper.close(); } }
private static Image cropImage(PdfWriter pdfWriter, Image image, CropRectangle cropRectangle) throws DocumentException { float width = image.getScaledWidth(); float height = image.getScaledHeight(); PdfTemplate template = pdfWriter.getDirectContent().createTemplate( width - cropRectangle.leftReduction - cropRectangle.rightReduction, height - cropRectangle.topReduction - cropRectangle.bottomReduction); template.addImage(image, width, 0, 0, height, -cropRectangle.leftReduction, -cropRectangle.bottomReduction); return Image.getInstance(template); }
public static void writeChartToPDFClipped(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(); document.setPageSize(new com.itextpdf.text.Rectangle(width, height)); if (document.isOpen()) { document.newPage(); } else { document.open(); } PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
@Override public void emit(SourceCode sourceCode, ITextContext context) { String lang = sourceCode.lang(); String code = sourceCode.content(); try { String trimmed = Strings.unindentBlock(code); log.debug("Initializing text grid"); TeXFormula formula = new TeXFormula(trimmed); TeXIcon teXIcon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 14f); teXIcon.setInsets(new Insets(1, 1, 1, 1)); teXIcon.setForeground(foreground); PdfWriter pdfWriter = context.getPdfWriter(); PdfContentByte cb = pdfWriter.getDirectContent(); float width = (float) teXIcon.getIconWidth(); float height = (float) teXIcon.getIconHeight(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(template, width, height, new JLaTeXmathFontMapper()); log.debug("Rendering formula"); teXIcon.paintIcon(null, g2, 0, 0); g2.dispose(); log.debug("Rendering diagram done"); ImgTemplate imgTemplate = new ImgTemplate(template); scaleToFit(imgTemplate, context.getDocumentArtBox()); context.append(imgTemplate); } catch (Exception e) { throw new WrappedRuntimeException(e); } }
/** * Creates a pdf showing the given {@link PlotterTemplate} via {@link PdfTemplate} usage. * @param template * @param document * @param cb * @throws DocumentException */ private void createPdfViaTemplate(PlotterTemplate template, Document document,PdfContentByte cb) throws DocumentException { PdfTemplate tp = cb.createTemplate(500, PageSize.A4.getHeight()/2); Graphics2D g2 = tp.createGraphics(500, PageSize.A4.getHeight()/2); AffineTransform at = new AffineTransform(); double factor = 500d / template.getPlotEngine().getChartPanel().getWidth(); at.scale(factor, factor); g2.transform(at); template.getPlotEngine().getChartPanel().print(g2); g2.dispose(); document.add(new Paragraph(componentName)); document.add(Image.getInstance(tp)); }
/** * Prints the given {@link Layout} into the given PDF output stream. */ public static void print(Layout layout, OutputStream out) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, out); } catch (Exception e) { handle(warning(Voc.ErrorWhilePrinting)); } document.open(); PdfContentByte cb = writer.getDirectContent(); It<Page> pages = it(layout.getPages()); for (Page page : pages) { //create PDF page Size2f pageSize = page.getFormat().getSize(); float width = Units.mmToPx(pageSize.width, 1); float height = Units.mmToPx(pageSize.height, 1); document.newPage(); PdfTemplate tp = cb.createTemplate(width, height); //fill PDF page Graphics2D g2d = new PdfGraphics2D(cb, width, height); log(remark("Printing page " + pages.getIndex() + "...")); LayoutRenderer.paintToCanvas(layout, pages.getIndex(), new AwtCanvas(g2d, pageSize, CanvasFormat.Vector, CanvasDecoration.None, CanvasIntegrity.Perfect)); //finish page g2d.dispose(); cb.addTemplate(tp, 0, 0); } document.close(); }
/** * Save chart as PDF file. Requires iText library. * * @param chart JFreeChart to save. * @param fileName Name of file to save chart in. * @param width Width of chart graphic. * @param height Height of chart graphic. * @throws Exception if failed. * @see <a href="http://www.lowagie.com/iText">iText</a> */ @SuppressWarnings("deprecation") public static void writeAsPDF(File fileToSave, int width, int height) throws Exception { if (chart != null) { BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath())); // convert chart to PDF with iText: Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("JFreeChart"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D, null); g2.dispose(); cb.addTemplate(tp, 0, 0); } finally { document.close(); } } finally { if (out != null) out.close(); } } }
/** * <a href="http://stackoverflow.com/questions/34734669/define-background-color-and-transparency-of-link-annotation-in-pdf"> * Define background color and transparency of link annotation in PDF * </a> * <p> * This test creates a link annotation with custom appearance. Adobe Reader chooses * to ignore it but other viewers use it. Interestingly Adobe Acrobat export-as-image * does use the custom appearance... * </p> */ @Test public void testCreateLinkWithAppearance() throws IOException, DocumentException { Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "custom-link.appearance.pdf"))); writer.setCompressionLevel(0); doc.open(); BaseFont baseFont = BaseFont.createFont(); int fontSize = 15; doc.add(new Paragraph("Hello", new Font(baseFont, fontSize))); PdfContentByte content = writer.getDirectContent(); String text = "Test"; content.setFontAndSize(baseFont, fontSize); content.beginText(); content.moveText(100, 500); content.showText(text); content.endText(); Rectangle linkLocation = new Rectangle(95, 495 + baseFont.getDescentPoint(text, fontSize), 105 + baseFont.getWidthPoint(text, fontSize), 505 + baseFont.getAscentPoint(text, fontSize)); PdfAnnotation linkGreen = PdfAnnotation.createLink(writer, linkLocation, PdfName.HIGHLIGHT, "green" ); PdfTemplate appearance = PdfTemplate.createTemplate(writer, linkLocation.getWidth(), linkLocation.getHeight()); PdfGState state = new PdfGState(); //state.FillOpacity = .3f; // IMPROVEMENT: Use blend mode Darken instead of transparency; you may also want to try Multiply. state.setBlendMode(new PdfName("Darken")); appearance.setGState(state); appearance.setColorFill(BaseColor.GREEN); appearance.rectangle(0, 0, linkLocation.getWidth(), linkLocation.getHeight()); appearance.fill(); linkGreen.setAppearance(PdfName.N, appearance); writer.addAnnotation(linkGreen); doc.open(); doc.close(); }
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(); }
@Test public void testComplex() throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "transparencyComplex.pdf"))); writer.setCompressionLevel(0); document.open(); PdfContentByte content = writer.getDirectContent(); content.setRGBColorStroke(0, 255, 0); for (int y = 0; y <= 400; y+= 10) { content.moveTo(0, y); content.lineTo(500, y); } for (int x = 0; x <= 500; x+= 10) { content.moveTo(x, 0); content.lineTo(x, 400); } content.stroke(); PdfTemplate template = content.createTemplate(500, 400); PdfTransparencyGroup group = new PdfTransparencyGroup(); group.put(PdfName.CS, PdfName.DEVICEGRAY); group.setIsolated(false); group.setKnockout(false); template.setGroup(group); PdfShading radial = PdfShading.simpleRadial(writer, 262, 186, 10, 262, 186, 190, BaseColor.WHITE, BaseColor.BLACK, true, true); template.paintShading(radial); PdfDictionary mask = new PdfDictionary(); mask.put(PdfName.TYPE, PdfName.MASK); mask.put(PdfName.S, new PdfName("Luminosity")); mask.put(new PdfName("G"), template.getIndirectReference()); content.saveState(); PdfGState state = new PdfGState(); state.put(PdfName.SMASK, mask); content.setGState(state); content.setRGBColorFill(255, 0, 0); content.moveTo(162, 86); content.lineTo(162, 286); content.lineTo(362, 286); content.lineTo(362, 86); content.closePath(); //content.fillStroke(); content.fill(); content.restoreState(); document.close(); }
/** * <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); } }
/** * Exports the given chart to a pdf format file * @param file the file that has to be saved in pdf format * @param chart the chart that needs to be exported into pdf */ public static void exportToPDF(File file, JFreeChart chart){ PdfWriter out = null; com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4.rotate()); int width = 800, height = 500; try{ out = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = out.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); @SuppressWarnings("deprecation") Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch(Exception e){ JOptionPane.showMessageDialog(GUIPrism.getGUI(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); return; } document.close(); }
@SuppressWarnings("deprecation") public static void writeChartsToPDF(List<JFreeChart> charts, int width, int height, OutputStream outputStream, String hostname, Date date) { PdfWriter writer = null; Document document = new Document(); try { writer = PdfWriter.getInstance(document, outputStream); writer.setPageEmpty(false); document.open(); document.setPageSize(PageSize.A4); document.add(new Paragraph("Aggregates Report generated by " + hostname + " on " + date.toString())); document.newPage(); writer.newPage(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template; Graphics2D graphics2d; int position = 0; Rectangle2D rectangle2d; for (JFreeChart chart : charts){ LOG.debug("Writing chart to PDF"); if (writer.getVerticalPosition(true)-height+(height*position) < 0){ position = 0; document.newPage(); writer.newPage(); } template = contentByte.createTemplate(width, height); graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 38, writer.getVerticalPosition(true)-height+(height*position)); position--; } } catch (Exception e) { e.printStackTrace(); } document.close(); }