Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing multiple JTables as one job -- Book object only prints 1st table

For a number of reasons, I'm trying to combine the output of multiple JTables into a single print job. After tearing my hair out trying to build PDFs, and combing the Java API, I settled on the Book class. My printing code currently looks like this.

try {       
    PrinterJob printer = PrinterJob.getPrinterJob();

    //Set 1/2 " margins and orientation
    PageFormat pf = printer.defaultPage();
    pf.setOrientation(PageFormat.LANDSCAPE);
    Paper paper = new Paper();
    double margin = 36; // half inch
    paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2);
    pf.setPaper(paper);

    Book printJob = new Book();

    // Note for next line: getAllTables() returns an ArrayList of JTables
    for (JTable t : getAllTables() )  
        printJob.append(t.getPrintable(PrintMode.FIT_WIDTH, null, null), pf,2);

    printer.setPageable(printJob);

    System.out.println(printJob.getNumberOfPages());

    if (printer.printDialog())
        printer.print();
    } catch (PrinterException e) {
        e.printStackTrace();
}

Primary Problem: Only the output from the "first" table is printing. I've made sure the for loop iterates correctly, and debugging statements have shown that every table is being added to the Book. Changing order of tables has no effect. Changing the print mode to PrintMode.NORMAL, does appear result in pieces of the other tables being printed. However, I run into a slew horizontal pagination problems, as the table width frequently exceeds page width (and it still doesn't explain why PrintMode.FIT_WIDTH isn't working)

A secondary question: How can I detect the correct number of pages in each printable? Most of my tables are two pages long, so for the moment, I'm just adding 2 pages each time I append. I read "somewhere" that using Book.UNKNOWN_NUMBER_OF_PAGES as the page number will fix this problem, but that only leads to an IndexOutOfBounds exception in the API's code. I've considered calling print myself until I get NO_PAGE_EXISTS, but I'd need a Graphics object with the proper page dimensions (and I have no idea how to get that).

Lastly: If the Book approach is hopeless, how else can I combine the output of multiple JTables (ie. multiple printables) into a single job? I looked into exporting the table as a PDF, but JTable's built-in pagination is so nice, I'd rather not have to do it myself. My last resort is to just give up and use iText's built in table function to construct a copy of the table.

Edit 3: Per my comment below, I got this working by generating a printable, determining the # of pages, and then generating a new one. I also modified Durendal's wrapper to spare us the hassle of iterating over each page. The code from the wrapper is

    class PrintableWrapper implements Printable
    {
        private Printable delegate;
        private int offset;

        public PrintableWrapper(Printable delegate, int offset) {
            this.offset = offset;
            this.delegate = delegate;
        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            return delegate.print(graphics, pageFormat, pageIndex-offset);
        }
    }   

I put Durendal's code for determining number of pages in its own function

    public int getNumberOfPages(Printable delegate, PageFormat pageFormat) throws PrinterException 
    {
        Graphics g = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics();
        int numPages = 0;
        while (true) {
            int result = delegate.print(g, pageFormat, numPages);
            if (result == Printable.PAGE_EXISTS) {
                ++numPages;
            } else {
                break;
            }
        }

        return numPages;
    }

After I create the book object, my printing code looks like this

            int totalPages = 0;
            for (DragNDropTable t : getAllTables() )
            {
                int pages = getNumberOfPages(t.getPrintable(PrintMode.FIT_WIDTH, null, null), pf);
                Printable p = t.getPrintable(PrintMode.FIT_WIDTH, null, null);
                printJob.append(new PrintableWrapper(p,totalPages), pf, pages);
                totalPages += pages;
            }
            printer.setPageable(printJob);

            if (printer.printDialog())
                printer.print();

And it works like a charm!

Edit 2: (you can skip this) I tried Durendal's answer. While I'm printing enough pages, multipage printables are printing the last page multiple times (once for every page in the printable). This is the same problem I discussed in my 1st edit (below), and I have no idea why this is happening, and my debugging statements are saying that it's printing all of the pages correctly, but the last page of a multipage printable is printed in place of each page. Code is attached. Insight is appreciated (and repayed with virtual cookies)

try {       
    PrinterJob printer = PrinterJob.getPrinterJob();

    //Set 1/2 " margins and orientation
    PageFormat pf = printer.defaultPage();
    pf.setOrientation(PageFormat.LANDSCAPE);
    Paper paper = new Paper();
    double margin = 36; // half inch
    paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2);
    pf.setPaper(paper);

    Book printJob = new Book();

    // Note for next line: getAllTables() returns an ArrayList of JTables
    for (JTable t : getAllTables() )  
    {
        Printable p = t.getPrintable(PrintMode.FIT_WIDTH, null, null);
        int pages = getNumberOfPages(p, pf);

        for (int i=0; i < pages; i++)
            printJob.append(new PageWrapper(p,i), pf);
    }

    printer.setPageable(printJob);

    System.out.println(printJob.getNumberOfPages());

    if (printer.printDialog())
        printer.print();
    } catch (PrinterException e) {
        e.printStackTrace();
}

public int getNumberOfPages(PageFormat pageFormat) throws PrinterException 
{
    Graphics g = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics();
    int numPages = 0;
    while (true) {
        int result = delegate.print(g, pageFormat, numPages);
        if (result == Printable.PAGE_EXISTS) 
            ++numPages;
        else
            break;
    }

    return numPages;
}

I'm using the unmodified PageWrapper that Durendal gave below.

Edit 1: (You can skip this) Dovetailing off of Durendal's answer, I tried to make a wrapper that spares us the chore of iterating over the pages ourselves. Unfortunately, it doesn't seem to work correctly on multipage printables, printing the same page multiple times in the document. I post it, simply because someone may get it to work, and it's slightly more convenient to use.

class PrintableWrapper implements Printable
    {
        private Printable delegate;
        private int offset;

        public PrintableWrapper(Printable delegate, int offset) {
            this.offset = offset;
            this.delegate = delegate;
        }

        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            return delegate.print(graphics, pageFormat, pageIndex-offset);
        }


        public int getNumberOfPages(PageFormat pageFormat) throws PrinterException 
        {
            Graphics g = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics();
            int numPages = 0;
            while (true) {
                int result = delegate.print(g, pageFormat, numPages);
                if (result == Printable.PAGE_EXISTS) 
                    ++numPages;
                else
                    break;
            }

            return numPages;
        }
    }

My printing code now looks like this (after I set the page format)

Book printJob = new Book();
int totalPages = 0;

for (DragNDropTable t : getAllTables() )
{
    Printable p = t.getPrintable(PrintMode.FIT_WIDTH, null, null);
    PrintableWrapper pw = new PrintableWrapper(p, totalPages);
    totalPages += pw.getNumberOfPages(pf);
    printJob.append(pw, pf,pw.getNumberOfPages(pf));
}

printer.setPageable(printJob);

if (printer.printDialog())
{
    printer.print();

}
like image 668
T. K. Avatar asked Oct 21 '22 17:10

T. K.


1 Answers

I had the very same Problem recently. The Book class by itself is useless, because if you add Printables to it, when the Book is printed it will pass the pageIndex from the Book to the Printable at pageIndex.

That is in most cases not what you want.

Create a simple Printable Wrapper that can remember a pageIndex to be used for the Printable delegate and add those to the Book:

class PageWrapper implements Printable {
    private Printable delegate;
    private int localPageIndex;

    public PageWrapper(Printable delegate, int pageIndex) {
        this.localPageIndex = pageIndex;
        this.delegate = delegate;
    }

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        return delegate.print(graphics, pageFormat, localPageIndex);
    }
}

Now you need to iterate trough each page of each Printable/Pageable and add a wrapper instance (that knows the pageIndex into its delegate) to the Book. That solves the problem that Book passes the wrong pageIndex to the printables added to it (its easier for Pageables than Printables).

You can detect the number of Pages in a Printable by printing it ;) Yes, I'm serious:

Graphics g = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics();
int numPages = 0;
while (true) {
    int result = printable.print(g, pageFormat, numPages);
    if (result == Printable.PAGE_EXISTS) {
        ++numPages;
    } else {
        break;
    }
}

Its important you obtain your PageFormat instance from the actual PrinterJob you want to print to, because the number of pages depends on the page format (paper size).

like image 118
Durandal Avatar answered Oct 27 '22 20:10

Durandal