Issue
I am trying to write some content in pdf using Apache PDFBox. I have to create a table and write some content into every column.
Let's say my table has 5 columns and I am writing content into the second column and content exceeds the length of the page. I closed the previous contentstream and created new contentstream, adding a new page to contentstream. But for the next column, I have to jump back to the previous page.
How would I do that? Can anyone help with this?
Solution
I closed the previous contentstream and created new contentstream, adding a new page to contentstream.
If you want to jump back and forth between pages, that approach probably is not appropriate. Have you considered keeping both pages open to freely go back and forth as long as you draw the table?
If you really need to close the current content stream before opening the next one, though, you can add multiple streams to a single page, use AppendMode.APPEND
.
In a comment you continued asking:
Can you give an example of adding multiple streams to a single page? It will be easy to understand if it is according to my question.
This is a simple example for going back and forth between two pages and adding content in a new content stream each time:
try (PDDocument document = new PDDocument()) {
PDRectangle mediaBox = PDRectangle.LETTER;
document.addPage(new PDPage(mediaBox));
document.addPage(new PDPage(mediaBox));
PDFont font = PDType1Font.HELVETICA;
for (int column = 1; column < 6; column++) {
try (PDPageContentStream canvas = new PDPageContentStream(document, document.getPage(0), AppendMode.APPEND, true)) {
canvas.beginText();
canvas.setFont(font, 12);
canvas.newLineAtOffset(column * (mediaBox.getWidth() / 7), mediaBox.getHeight() / 7);
canvas.showText("Column " + column + " A");
canvas.endText();
}
try (PDPageContentStream canvas = new PDPageContentStream(document, document.getPage(1), AppendMode.APPEND, true)) {
canvas.beginText();
canvas.setFont(font, 12);
canvas.newLineAtOffset(column * (mediaBox.getWidth() / 7), 6 * mediaBox.getHeight() / 7);
canvas.showText("Column " + column + " B");
canvas.endText();
}
}
document.save(new File("BackAndForthBetweenPages.pdf"));
}
(BackAndForthBetweenPages test testForSagarKumar
)
Here we add content to the first two pages of a document in 5 columns, column-by-column.
The result:
Answered By - mkl
Answer Checked By - Timothy Miller (JavaFixing Admin)