com.itextpdf.text.pdf.PdfTemplate Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfTemplate. 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: SwingExportUtil.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example #2
Source File: PlotUtils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #3
Source File: ChartExportUtil.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #4
Source File: RotateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@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();
    }
}
 
Example #5
Source File: JFreeChartTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #6
Source File: ChartExportUtil.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #7
Source File: SwingExportUtil.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes swing to pdf
 * 
 * @param panel
 * @param fileName
 * @throws DocumentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName)
    throws IOException, DocumentException {
  // print the panel to pdf
  int width = panel.getWidth();
  int height = panel.getHeight();
  logger.info(
      () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}",
          width, height, fileName.getAbsolutePath()));
  Document document = new Document(new Rectangle(width, height));
  PdfWriter writer = null;
  try {
    writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(width, height);
    Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 0, 0);
    document.close();
    writer.close();
  } finally {
    if (document.isOpen()) {
      document.close();
    }
  }
}
 
Example #8
Source File: ChartExportUtil.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #9
Source File: CreateLink.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <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();
}
 
Example #10
Source File: TestTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
@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();
}
 
Example #11
Source File: CreateSignature.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <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 #12
Source File: ReportFactory.java    From graylog-plugin-aggregates with GNU General Public License v3.0 2 votes vote down vote up
@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();
}