如何在iTextPDF中对齐图形? [英] How do I align a graphic in iTextPDF?

查看:787
本文介绍了如何在iTextPDF中对齐图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Java App。我使用jFreeChart创建了一个饼图,并将其添加到使用iText库创建的PDF文件中,但我无法找到一种方法来对齐PDF中的图形并使其居中。这是我用来添加图表的代码:

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);


推荐答案

您正在坐标<$ c处添加模板$ c>(0,0)。通常,这是页面的左下角。

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

有多种方法可以确保您的图表出现在其他位置。例如:您可以执行Math并在不同的坐标处添加模板。如果您正在使用A4页面,您会发现图形的大小(600乘600用户单位)并不真正适合页面(595乘842个用户单位)。

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).

我更喜欢将模板包装在 Image 对象中,如下所示:

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.

现在我可以使用大量的方法。例如:您可以缩放它以适合页面,您可以引入水平对齐,您甚至可以将图像作为单元格添加到 PdfPTable ,在这种情况下它将是默认情况下,自动缩放以适合 PdfPCell

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.

进一步阅读:

  • 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

这篇关于如何在iTextPDF中对齐图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆