Create mutli page document dynamically with PDFBox

I am trying to create a PDF report from a Java ResultSet. If the report was only one page, I would not have a problem here. The problem is that the report can be from one to ten pages. Right now I have this to create a one-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 needed. Is there an object-oriented answer that looks in my face and I just don't see it?

+7
java pdf pdfbox
source share
2 answers

As I expected, the answer looked right in my 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 @mkl for the answer.

+10
source share

Create a multi-page PDF using PDFBox:

(a) Create a new page, a new content stream, Go to the beginning on the left, start writing. When writing each word, check if a space gap is required for the width of the media box. If crosses, go to the next line on the left and start writing. Continue writing to the last line of the page.

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

(c) Repeat steps (a) and (b) until the last record / line / line is recorded.

  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(); 

Hint: Use font options such as size / height and remaining height of the media window to determine the last line of the page.

+7
source share

All Articles