File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Printing multiple pages! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Printing multiple pages!" Watch "Printing multiple pages!" New topic

Printing multiple pages!

Payam Fard
Ranch Hand

Joined: Jan 31, 2003
Posts: 75
Hi all,
I have downloaded Marty Hall's PrintUtilities class ad follows. I am trying to print a JTree with all its expanded nodes (which could very well go beyond one page).
I am calling PrintUtilities.print(tree). I only get one page out, even though the following code is checking to see if there are more than one page and return PAGE_EXISTS. Could someone point out how I can fix this problem? Also, another problem is that sometimes, depending on how many nodes are expanded or extracted, half of a node gets printed on the first page. How would I know whether the last node would completely fit into a page or not?
Thank you very much,

public class PrintUtilities implements Printable {
private Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();

public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;

public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printJob.printDialog())
try {
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {

if (pageIndex > 0) {
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on.
* So this turns if off globally.
* @see enableDoubleBuffering
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
/** Re-enables double buffering globally. */

public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
Raja Kannappan
Ranch Hand

Joined: May 08, 2002
Posts: 83
This is because in print() method, you are checking if pageIndex > 0 and if is greater than 0, you are returning NO_SUCH_PAGE. That is why it is printing only one page. If you do something like pageIndex > maximumPages it will print all the pages till maximumPages.

I agree. Here's the link:
subject: Printing multiple pages!
jQuery in Action, 3rd edition