Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you track the location of PDPageContentStream's text output?

Tags:

java

pdfbox

I am using Java to write output to a PDDocument, then appending that document to an existing one before serving it to the client.

Most of it is working well. I only have a small problem trying to handle content overflow while writing to that PDDocument. I want to keep track of where text is being inserted into the document so that when the "cursor" so to speak goes past a certain point, I'll create a new page, add it to the document, create a new content stream, and continue as normal.

Here is some code that shows what I'd like to do:

// big try block
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream content = new PDPageContentStream(doc, page);
int fontSize = 12;

content.beginText();
content.setFont(...);
content.moveTextPositionByAmount(margin, pageHeight-margin);
for ( each element in a collection of values ) {
    content.moveTextPositionByAmount(0, -fontSize); // only moves down in document

    // at this point, check if past the end of page, if so add a new page
    if (content.getTextYPosition(...) < margin) { // wishful thinking, doesn't exist
        content.endText();
        content.close();
        page = new PDPage();
        doc.addPage(page);
        content = new PDPageContentStream(doc, page);
        content.beginText();
        content.setFont(...);
        content.moveTextPositionByAmount(margin, pageHeight-(margin+fontSize));
    }
    content.drawString(...);
}
content.endText();
content.close();

The important bit is the content.getTextYPosition(). It doesn't actually exist, but I'm sure PDPageContentStream must be keeping track of a similar value. Is there any way to access this value?

Thanks.

like image 310
Junseok Lee Avatar asked Oct 03 '22 07:10

Junseok Lee


1 Answers

Create a heightCounter variable that tracks how far you've moved the text location. It's initial value can be your starting Y position.

        PDRectangle mediabox = page.findMediaBox();
        float margin = 72;
        float width = mediabox.getWidth() - 2 * margin;
        float startX = mediabox.getLowerLeftX() + margin;
        float startY = mediabox.getUpperRightY() - margin;
        float heightCounter = startY;

Every time you move the text position, subtract that from your heightCounter. When heightCounter is less than what you're moving the text position by, then create a new page.

like image 141
Catchwa Avatar answered Oct 11 '22 15:10

Catchwa