Reputation: 91
I have a Java application that has a JPanel with information that I want to output to PDF (using iText). The only twist is that I need to give this JPanel a different formatting on the PDF. Since the JPanel is showed on the GUI, I can't change it to the way I want to appear on the PDF, because this would change the JPanel being showed. So what I do is create a new JPanel with my PDF formatting, populate it with the information of the original one and then output this new one to PDF. No problem so far, except that I only can get this JPanel to be outputted to PDF if it's added to the Container. And obviously I don't want it to be, because I don't want this new JPanel to be showed. I even tried to set it not visible, but this way it also doesn't get outputted.
The new JPanel:
JPanel myFormattedPanel = new JPanel(); {
myFormattedPanel.setLayout(new GridLayout(2, 3, 0, 2));
myFormattedPanel.setBackground(Color.WHITE);
(...)
getContentPane().add(myFormattedPanel); //How to not need this??
Output to PDF:
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
float width = PageSize.A4.getWidth();
float height = PageSize.A4.getHeight() / 2;
PdfTemplate resultsPanelPdfTemplate = cb.createTemplate(width, height);
Graphics2D g2d2 = new PdfGraphics2D(resultsPanelPdfTemplate, width, height);
myFormattedPanel.paint(g2d2);
g2d2.dispose();
cb.addTemplate(resultsPanelPdfTemplate, 0, 0);
document.close();
So basically, what is the way to output a JPanel to PDF using iText, without having to add it to the Container, or at least, without having to make it visible?
Thanks very much in advance.
Cheers!
Upvotes: 2
Views: 3441
Reputation: 347214
setSize
to give the component space to paint its contents. You can use getPreferredSize
if you want to get the recommended sizeprintAll
instead of paint
. printAll
isn't double buffered and doesn't suffer from NullPointerException (which can occur under Windows from experience)Upvotes: 1