问题
Id like to export my jcomponent (custom paintcomponent method which draws a lot of texts and lines, small images (kind of a small word application)) to PDF
my component is "bill"
the method i use for this (which works, but some methods are deprecated) is:
com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(0,0,bill.getWidth(),bill.getHeight());
Document document = new Document(r);
try {
PdfWriter writer;
writer = PdfWriter.getInstance(document, new FileOutputStream(f));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(bill.getWidth(), bill.getHeight());
Graphics2D g2d = tp.createGraphics(bill.getWidth(), bill.getHeight(), new DefaultFontMapper());
bill.addNotify();
bill.validate();
bill.paint(g2d);
g2d.dispose();
cb.addTemplate(tp, 0, 0);
}
catch(Exception e) {
e.printStackTrace();
}
document.close();
It works quite well, but there are two big problems: the method tp.createGraphics is deprecated (so there might be a better solution) and If the swing Component is very big, it is printed on just one single page in PDF.
So what i need is a "page-splitter" to help me creating A4 sized pages to be print-friendly. Of course without a buffer overflow when the jcomponent is very big...
Can anyone help?
回答1:
The "official Java" way to do this would be for your JComponent to implement Pageable and/or Printable, so that it knows how to draw portions of itself onto a page (represented by a Graphics). Typically, in the Printable.print(Graphics graphics, PageFormat pageFormat, int pageIndex)
method, you would translate the graphics by some constant Y factor times the pageIndex, accounting for headers, spacers, etc...
That way it can print out to paper too.
The PDF code is very close to what you have, you just do it once per page. You can find code on my blog here, which is based upon earlier work by Gert-Jan Schouten here
来源:https://stackoverflow.com/questions/10516633/export-jcomponent-to-pdf-with-itext