4

I'm creating a PDF and somewhere in there I want to add a JPanel.

Using PdfContentByte and PdfGraphics2D I am able to add it to the document but:

  • How do I position it so it's at the left margin instead of the left page edge?
  • How do I prevent it from showing up over other elements?
  • In other words: how can I put it in a Paragraph?

Code fragment:

// 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
//...
Koohoolinn
  • 1,427
  • 6
  • 20
  • 29
  • You might want to create a separate template, use its Graphics2D, and position the template where you want it to be. – mkl Sep 26 '13 at 13:31

1 Answers1

4

I got it working by using a PdfTemplate and creating an Image from that.

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)
Koohoolinn
  • 1,427
  • 6
  • 20
  • 29