Printing multiple components

2019-08-22 03:35发布

问题:

I am trying to send a JTable and a JPanel to the printer in a single print job like this :

            PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
            attr.add(OrientationRequested.LANDSCAPE);

            MessageFormat header = new MessageFormat("Page {0}");
            Printable p1 = table.getPrintable(JTable.PrintMode.FIT_WIDTH, header, null);

            PageFormat pf = new PageFormat();                

            Printable p2 = new ComponentPrinter().returnIt(jPanel1);

            Book book = new Book();
            book.append(p1, pf);
            book.append(p2, pf);

            PrinterJob pj = PrinterJob.getPrinterJob();

            pj.setPageable(book);

            if (pj.printDialog(attr)){
                try {
                    pj.print(attr);
                } catch (PrinterException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

My problem is, this only prints the first Printable added to the Book ; in this case, the JTable. If I swap the order and add the panel first, then it only prints the panel. Can someone point out the error ?

回答1:

The answer lies here.

The Book passes wrong pageIndex to the added Printables. For more information and a solution click on the link.