简体   繁体   中英

Create mutli-page document dynamically using PDFBox

I am attempting to create a PDF report from a Java ResultSet. If the report was only one page, I would have no problem here. The issue comes from the fact that the report could be anywhere from one to ten pages long. Right now, I have this to create a single-page document:

PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document,page);

So my question is, how do I create pages dynamically as they are needed. Is there an object-oriented answer staring me in the face and I just cannot see it?

As I expected, the answer was staring me right in the face, I just needed someone to point it out for me.

PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document,page);

//generate data for first page

content.close();

//if number of results exceeds what can fit on the first page
page = new PDPage(PDPage.PAGE_SIZE_LETTER);
document.addPage(page);
content = new PDPageContentStream(document,page);

//generate data for second page

content.close();

Thanks to @mkl for the answer.

(a) Create new page, new content stream, Move to Top Left, start writing. While writing each word check whether space required is not crossing mediabox width. If crosses, move to next line leftmost and start writing. Continue writing till the last line of the page.

(b) Close the contentStream and add the current page to the document when the writing operation reaches the last line of the current page,

(c) Repeat steps (a) and (b) till the last record/row/line is written.

        PDDocument document = new PDDocument();
        PDFont font = PDType1Font.HELVETICA;

//For Each Page:
        PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.setFont(font, 12);
        contentStream.beginText();
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString("PDF BOX TEXT CONTENT");
        contentStream.endText();
        contentStream.close();
        document.addPage(page);

//After All Content is written:
        document.save(pdfFile);
        document.close();

Use Font parameters like size/height and remaining media box height to determine the last line of the page. 使用大小/高度等字体参数和剩余媒体框高度来确定页面的最后一行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM