I'm using PDFbox for downloading PDF. I want to add some new page in the middle.
PDPage page = new PDPage();
pdoc.addPage(page);
This code inserts the new page at end of the PDF. How can I insert a page at another position?
You can add your page before another page with:
PDPageTree pages = document.getDocumentCatalog().getPages();
pages.insertBefore(page, pages.get(0)); //0 - index of the page before that you wish to add your new page
or after another page with:
PDPageTree pages = document.getDocumentCatalog().getPages();
pages.insertAfter(page, pages.get(0)); //0 index of the page after that you wish to add your new page
Tested with PDFBox v2.0.21
When a PDF is created with PDF-Box the result of
doc.getDocumentCatalog().getPages().getKids();
is a flat list. It contains all pages in a sequence.
PDPageNode
|- Page1
|- Page2
|- Page3
If the PDF was not created with PDF-Box this might not be true, instead the PDPageNode for all Pages can be layed out in a tree structure
PDPageNode
|-Page1
|-PDPageNode
| |- Page2
| |- Page3
|- Page4
In this case the sample code mentioned in the other answer will not work. Instead you can use the following
public void addPage(PDDocument doc, final int index, final PDRectangle size) {
// Use the normal method if the page comes after all other pages
if (index >= doc.getNumberOfPages())
doc.addPage(new PDPage(size));
else {
final PDPage page = new PDPage(size);
// Find the existing page that is currently at the index
// the new page will be
final PDPage nextPage = (PDPage) doc.getDocumentCatalog().getAllPages().get(index);
// Get the node the current page is stored in
PDPageNode pageNode = nextPage.getParent();
// Set the appropriate node as the new pages parent
page.setParent(pageNode);
// Insert the new page in the node at the index of the current page is stored
// this shifts all pages in the node forward
pageNode.getKids().add(pageNode.getKids().indexOf(nextPage), page);
// Update the current node and all parent nodes
while (pageNode != null) {
pageNode.updateCount();
pageNode = pageNode.getParent();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With