Java Code Examples for com.itextpdf.text.pdf.PdfWriter#getDirectContent()

The following examples show how to use com.itextpdf.text.pdf.PdfWriter#getDirectContent() . 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: AppearanceAndRotation.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException {
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight());

    cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight());
    cs.fill();

    cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);                        
    cs.beginText();
    cs.setLeading(12 + 1.75f);
    cs.moveText(.75f, rect.getHeight() - 12 + .75f);
    cs.showText(contents);
    cs.endText();

    return PdfAnnotation.createFreeText(writer, rect, contents, cs);
}
 
Example 2
Source File: UseColumnText.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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 3
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 4
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
static byte[] createRotatedImagePdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();

    BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 0, 500, -500, 0, 550, 50);

    document.close();

    return baos.toByteArray();
}
 
Example 5
Source File: UseMillimeters.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 6
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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 7
Source File: InterlineSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <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 8
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 9
Source File: PDFDocument.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void start() {
	try {
		this.document = new Document(new Rectangle(this.size.getWidth(), this.size.getHeight()) );
		PdfWriter writer = PdfWriter.getInstance(this.document, this.stream);
		this.document.open();
		this.cb = writer.getDirectContent();
	} catch(Throwable e){
		TGErrorManager.getInstance(this.context).handleError(e);
	}
}
 
Example 10
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createSimplePatternPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();
    Rectangle pageSuze = document.getPageSize();
    
    PdfPatternPainter painter = directContent.createPattern(200, 150);
    painter.setColorStroke(BaseColor.GREEN);
    painter.beginText();
    painter.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_STROKE);
    painter.setTextMatrix(AffineTransform.getTranslateInstance(0, 50));
    painter.setFontAndSize(BaseFont.createFont(), 100);
    painter.showText("Test");
    painter.endText();

    directContent.setColorFill(new PatternColor(painter));
    directContent.rectangle(pageSuze.getLeft(), pageSuze.getBottom(), pageSuze.getWidth(), pageSuze.getHeight());
    directContent.fill();

    document.close();

    return baos.toByteArray();
}
 
Example 11
Source File: SimpleRedactionTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
static byte[] createClippingTextPdf() throws DocumentException, IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();

    PdfContentByte directContent = writer.getDirectContent();
    directContent.beginText();
    directContent.setTextRenderingMode(PdfPatternPainter.TEXT_RENDER_MODE_CLIP);
    directContent.setTextMatrix(AffineTransform.getTranslateInstance(100, 400));
    directContent.setFontAndSize(BaseFont.createFont(), 100);
    directContent.showText("Test");
    directContent.endText();
    
    BufferedImage bim = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bim.createGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0, 0, 500, 500);
    g2d.dispose();

    Image image = Image.getInstance(bim, null);
    directContent.addImage(image, 500, 0, 0, 599, 50, 50);
    document.close();

    return baos.toByteArray();
}
 
Example 12
Source File: TestTransparency.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSimple() throws FileNotFoundException, DocumentException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "transparency.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();

    
    content.saveState();
    PdfGState state = new PdfGState();
    state.setFillOpacity(0.5f);
    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 13
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 14
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 15
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 16
Source File: AddRotatedImage.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39364197/how-to-rotate-around-the-image-center-by-itext">
 * How to rotate around the image center by itext?
 * </a>
 * <p>
 * This test draws an image at given coordinates without rotation and then again
 * as if that image was rotated around its center by some angle.
 * </p>
 */
@Test
public void testAddRotatedImage() throws IOException, DocumentException
{
    try (   FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "rotatedImage.pdf"))    )
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, stream);
        document.open();

        PdfContentByte contentByte = writer.getDirectContent();

        int x = 200;
        int y = 300;
        float rotate = (float) Math.PI / 3;

        try (InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/itext5/layer/Willi-1.jpg"))
        {
            Image image = Image.getInstance(IOUtils.toByteArray(imageStream));

            // Draw image at x,y without rotation
            contentByte.addImage(image, image.getWidth(), 0, 0, image.getHeight(), x, y);

            // Draw image as if the previous image was rotated around its center
            // Image starts out being 1x1 with origin in lower left
            // Move origin to center of image
            AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5);
            // Stretch it to its dimensions
            AffineTransform B = AffineTransform.getScaleInstance(image.getWidth(), image.getHeight());
            // Rotate it
            AffineTransform C = AffineTransform.getRotateInstance(rotate);
            // Move it to have the same center as above
            AffineTransform D = AffineTransform.getTranslateInstance(x + image.getWidth()/2, y + image.getHeight()/2);
            // Concatenate
            AffineTransform M = (AffineTransform) A.clone();
            M.preConcatenate(B);
            M.preConcatenate(C);
            M.preConcatenate(D);
            //Draw
            contentByte.addImage(image, M);
        }

        document.close();
    }
}
 
Example 17
Source File: MusicFontTest.java    From libreveris with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Printout of each MusicFont character
 */
@Test
public void textPrintout ()
        throws Exception
{
    File file = new File("data/temp/" + MusicFont.FONT_NAME + ".pdf");
    try (FileOutputStream fos = new FileOutputStream(file)) {
        Rectangle rect = new Rectangle(pageWidth, pageHeight);
        int x = xMargin; // Cell left side
        int y = yMargin; // Cell top side
        int line = 0;
        Document document = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphics(pageWidth, pageHeight);
        MusicFont musicFont = new MusicFont(64, 0);
        Font stringFont = g.getFont().deriveFont(24f);
        Font infoFont = stringFont.deriveFont(15f);
        String frm = "x:%4.1f y:%4.1f w:%4.1f h:%4.1f";

        for (int i = 0; i < 256; i++) {
            BasicSymbol symbol = new BasicSymbol(false, i);
            TextLayout layout = symbol.layout(musicFont);

            if (i > 0) {
                // Compute x,y for current cell
                x = xMargin + (cellWidth * (i % itemsPerLine));

                if (x == xMargin) {
                    line++;

                    if (line >= linesPerPage) {
                        // New page
                        g.dispose();
                        document.setPageSize(rect);
                        document.newPage();
                        cb = writer.getDirectContent();
                        g = cb.createGraphics(pageWidth, pageHeight);
                        x = xMargin;
                        y = yMargin;
                        line = 0;
                    } else {
                        y = yMargin + (line * cellHeight);
                    }
                }
            }

            // Draw axes
            g.setColor(Color.PINK);
            g.drawLine(
                    x + (cellWidth / 4),
                    y + (cellHeight / 2),
                    (x + cellWidth) - (cellWidth / 4),
                    y + (cellHeight / 2));
            g.drawLine(
                    x + (cellWidth / 2),
                    y + (cellHeight / 4),
                    x + (cellWidth / 2),
                    (y + cellHeight) - (cellHeight / 4));

            // Draw number
            g.setFont(stringFont);
            g.setColor(Color.RED);
            g.drawString(Integer.toString(i), x + 10, y + 30);

            // Draw info
            Rectangle2D r = layout.getBounds();
            String info = String.format(
                    frm,
                    r.getX(),
                    r.getY(),
                    r.getWidth(),
                    r.getHeight());
            g.setFont(infoFont);
            g.setColor(Color.GRAY);
            g.drawString(info, x + 5, (y + cellHeight) - 5);

            // Draw cell rectangle
            g.setColor(Color.BLUE);
            g.drawRect(x, y, cellWidth, cellHeight);

            // Draw symbol
            g.setColor(Color.BLACK);
            layout.draw(g, x + (cellWidth / 2), y + (cellHeight / 2));
        }

        // This is the end...
        g.dispose();
        document.close();
    }
}
 
Example 18
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 19
Source File: TableKeepTogether.java    From testarea-itext5 with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/39529281/itext-table-inside-columntext-dont-keeptogether">
 * iText Table inside ColumnText don't keeptogether
 * </a>
 * <p>
 * The first two pages use code of the OP which does not work as desired.
 * The last page shows how the desired effect can be achieved.
 * </p>
 */
@Test
public void testKeepTogetherTableInColumnText() throws IOException, DocumentException
{
    File file = new File(RESULT_FOLDER, "keepTogetherTableInColumnText.pdf");
    OutputStream os = new FileOutputStream(file);

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, os);

    document.open();

    PdfContentByte canvas = writer.getDirectContent();

    printPage1(document, canvas);

    document.newPage();

    printPage2(document, canvas);

    document.newPage();

    printPage3(document, canvas);

    document.close();
    os.close();
}
 
Example 20
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();
}