如何在iText中定位PDFGraphis2D对象?

4
我正在创建一份PDF文档,并希望在其中添加一个JPanel。使用PdfContentByte和PdfGraphics2D,我能够将其添加到文档中,但是:
1. 如何将其定位到左边距而不是左边缘? 2. 如何防止它显示在其他元素上方? 3. 换句话说:如何将其放入段落中?
代码片段:
// multiple Paragraphs
// ...
JPanel myPanel = ...

PdfContentByte canvas = writer.getDirectContent();
int origWidth = myPanel.getWidth();
int origHeight = myPanel.getHeight();
float width = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
double scale = width / origWidth;
Graphics2D g2 = new PdfGraphics2D(canvas, origWidth, origHeight);
g2.scale(scale, scale);
myPanel.paint(g2);
g2.dispose();

// even more Paragraphs
//...

你可能想要创建一个单独的模板,使用它的Graphics2D,并将模板定位到您想要的位置。 - mkl
1个回答

4

我通过使用PdfTemplate并从中创建一个Image,使其工作。

PdfContentByte canvas = writer.getDirectContent();
int origWidth = myPanel.getWidth();
int origHeight = myPanel.getHeight();
PdfTemplate template = canvas.createTemplate(origWidth, origHeight);
Graphics2D g2 = new PdfGraphics2D(template, origWidth, origHeight);
myPanel.paint(g2);
g2.dispose();
Image image = Image.getInstance(template);
float width = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
image.scaleToFit(width, 1000);
document.add(image)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接