D.Anush
D.Anush

Reputation: 195

How iText 7 create single pdf file with multiple pages while iteration in Java?

I have a loop which will fetch data from DB and want to print them to a PDF file using iText 7. My question is suppose DB have 10 records, I want to create a single PDF doc with 10 pages.

Here is my code, This code will only create a doc with 1 page and save it to a location.

list.forEach(item -> {

  String fileLocation = "path/records.pdf";
  WriterProperties wp = new WriterProperties();
  PdfWriter writer = new PdfWriter(fileLocation, wp);
  PdfDocument pdfDoc = new PdfDocument(writer);
  Document doc = new Document(pdfDoc);

  // Add data to doc
  // close the doc
  //close the writer
}
)

With this approach I try to add document.add(new AreaBreak(AreaBreakType.NEXT_PAGE)); but this will not do the trick.

Apart from that I have seen some approaches using ByteArrayOutputStream but I could not find a good solution.

Can anyone help me o this?

Upvotes: 2

Views: 3798

Answers (1)

swapyonubuntu
swapyonubuntu

Reputation: 2110

I feel you need to initialize your PdfDocument outside the loop so single doc is created.

Adding page breaks will not help, You can create new pages with

PdfDocument pdfDoc = new PdfDocument(writer);
// Adding an empty page 
pdfDoc.addNewPage();

Ref: https://www.tutorialspoint.com/itext/itext_creating_pdf_document.htm

Also it would be worth checking addPage and addNewPage https://api.itextpdf.com/iText7/java/7.0.0/com/itextpdf/kernel/pdf/PdfDocument.html#addPage-com.itextpdf.kernel.pdf.PdfPage-

Upvotes: 5

Related Questions