如何在iText中定位PDFGraphis2D对象?

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

我通过使用PdfTemplatePdfTemplate创建了一个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)