Hello,
My application allows the user to print the screen content which is made of several Swing controls (images, texts, etc.) - the printed panel it self is long (several pages) and the width about 600pixels.
Since I know exactly each page layout (I put the exact number of images and components) on each page (the total number of images is dynamic), I can calculate exactly how many pages I will need for the print.
I've implemented the Printable interface as follows:
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK); //set default foreground color to black
RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
Dimension d = this.getSize(); //get size of document
double panelWidth = d.width; //width in pixels
double panelHeight = d.height; //height in pixels
double pageHeight = pf.getImageableHeight(); //height of printer page
double pageWidth = pf.getImageableWidth(); //width of printer page
double scale = pageHeight / panelHeight;
int totalNumPages = (int) Math.ceil(scale * panelWidth / pageWidth);
if (pageIndex >= totalNumPages) {
return Printable.NO_SUCH_PAGE;
}
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.translate(0f, -pageIndex * pageHeight);
g2.scale(scale, scale);
this.paint(g2);
return Printable.PAGE_EXISTS;
}
It seems that everything works fine. Since I don't have a printer, I've tested it using a PDF printer and on several clients printer - and the results were good.
However, on one of my user's printer - it seems that something in not working with the calculation, since it breaks the page in the middle of the images.
Is there a more elegant way to do these calculations ? Can I add instead a "page break" notification somewhere ?
Thanks