【问题标题】:How to position a PDFGraphis2D object in iText?如何在 iText 中定位 PDFGraphis2D 对象?
【发布时间】:2013-09-27 16:18:19
【问题描述】:

我正在创建一个 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
//...

【问题讨论】:

  • 您可能想要创建一个单独的模板,使用它的 Graphics2D,并将模板放置在您想要的位置。

标签: java itext


【解决方案1】:

我通过使用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)

【讨论】:

    猜你喜欢
    • 2010-12-10
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2018-04-15
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多