Search code examples
javapdfpdfbox

Writing multiple lines and pages in PDFBox - Get PDPageContentStream Y-Axis


I'm testing PDFBox and I've a doubt writing a new document..

The following code writes 75 lines in a pdf file. The height of the file isn't enough. So I'd need to know when the contentStream reaches the end of page in order to create a new one and continue writing lines.

Any way to solve my question?

Thank you so much!

    File pdfFile = new File("hello.pdf");
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    contentStream.setFont( PDType1Font.TIMES_ROMAN, 12);
    float initPosY = page.getMediaBox().getHeight()-50;
    contentStream.beginText();
    contentStream.newLineAtOffset(25, initPosY);
    contentStream.setLeading(30.5f);
    for(int i=1; i<75;i++){
        contentStream.showText("Line: "+i);
        contentStream.newLine();
   }
    contentStream.endText();
    contentStream.close();
    doc.addPage(page);
    doc.save(pdfFile);
    doc.close();

Solution

  • Substract the leading value (30.5f) from initPosY in your loop after calling newLine(). When it is < 0, or below a useful value (e.g. 50 which is your top margin), then you should start a new page.