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

前端 未结 1 587
自闭症患者
自闭症患者 2020-12-11 07:04

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

相关标签:
1条回答
  • 2020-12-11 07:42

    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).

    0 讨论(0)
提交回复
热议问题