如何在iText中定位PDFGraphis2D对象?

时间:2013-09-26 09:40:47

标签: java itext

我正在创建一个PDF,我想在那里添加一个JPanel。

使用PdfContentBytePdfGraphics2D我可以将其添加到文档中,但是:

  • 如何定位它,使其位于左边距而不是左页边缘?
  • 如何防止它出现在其他元素上?
  • 换句话说:我怎么能把它放在段落中?

代码片段:

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

1 个答案:

答案 0 :(得分: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)