How to create a PDF with multiple pages from a Graphics object with Java and itext

后端 未结 2 1361
小蘑菇
小蘑菇 2021-01-18 01:43

I have an abstract class with an abstract method draw(Graphics2D g2), and the methods print(), showPreview(), printPDF(). For each document in my Java program, I implement

2条回答
  •  后悔当初
    2021-01-18 02:38

        document.open();
    
        // the same contentByte is returned, it's just flushed & reset during
        // new page events.
        PdfContentByte cb = writer.getDirectContent();
    
        for (int _pageNumber = 0; _pageNumber < _numberofPages; ++_numberOfPages) {
          /*******************/
          //harmless in first pass, *necessary* in others
          document.newPage(); 
          /*******************/
    
          g2 = cb.createGraphics(_pageWidth, _height);
          g2.translate(0, (_numberOfPages - _pageNumber) * _pageHeight);
          draw(g2);
          g2.dispose();
        }
    
        document.close();
    

    So you're rendering your entire interface N times, and only showing a page-sized slice of it in different locations. That's called "striping" in print-world IIRC. Clever, but it could be more efficient in PDF.

    Render your entire interface into one huge PdfTemplate (with g2d), once. Then draw that template into all your pages such that the portion you want is visible inside the current page's margins ("media box").

    PdfContentByte cb = writer.getDirectContent();
    float entireHeight = _numberOfPages * _pageHeight;
    PdfTemplate hugeTempl = cb.createTemplate( 0, -entireHeight, pageWidth, _pageHeight );
    g2 = hugeTempl.createGraphics(0, -entireHeight, _pageWidth, _pageHeight ); 
    draw(g2);
    g2.dispose();
    
    for (int curPg = 0; curPg < _numberOfPages; ++curPg) {
      cb.addTemplateSimple( hugeTempl, 0, -_pageHeight * curPg );
    
      document.newPage();
    }
    

    PDF's coordinate space sets 0,0 in the lower left corner, and those values increase as you go up and to the right. PdfGraphis2D does a fair amount of magic to hide that difference from you, but we still have to deal with it a bit here... thus the negative coordinates in the bounding box and drawing locations.

    This is all "back of the napkin" coding, and it's entirely possible I've made a mistake or two in there... but that's the idea.

提交回复
热议问题