How do I align a graphic in iTextPDF?

2019-06-22 13:27发布

问题:

I am developing a Java App. I created a pie chart using jFreeChart and added it to a PDF file created with the iText library, but I cannot find a way to align and center the graphic inside the PDF. This is the code I'm using to add the chart:

PdfContentByte contentByte = writer.getDirectContent();

PdfTemplate template = contentByte.createTemplate(600, 600);
Graphics2D graphics2d = template.createGraphics(600, 600, new DefaultFontMapper());
Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 300, 300);

resultsPieChart.draw(graphics2d, rectangle2d);

graphics2d.dispose();
contentByte.addTemplate(template, 0, 0);

回答1:

You are adding the template at the coordinates (0, 0). Usually, this is the lower-left corner of the page.

There are different ways to make sure that your chart appears at another position. For instance: you could do the Math and add the template at a different coordinate. If you're working with an A4 page, you'll discover that the size of your graphic (600 by 600 user units) doesn't really fit the page (595 by 842 user units).

I prefer wrapping the template inside an Image object like this:

Image chart = Image.getInstance(template);

This doesn't rasterize your template: if it consists of vector data, the image will be a vector image.

Now I can use plenty of convience methods. For instance: you can scale it to fit a page, you can introduce a horizontal alignment, you can even add the image as a cell to a PdfPTable in which case it will be scaled to fit a PdfPCell automatically by default.

Further reading:

  • How to position a PDFGraphis2D object in iText?
  • Add rectangle into pdfpcell itextsharp
  • How to add text to an image?
  • Create an Image or PdfTemplate from a PDF file