Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert new page in middle of pdf using pdfbox

Tags:

java

pdf

pdfbox

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?

like image 853
user2914640 Avatar asked Oct 21 '25 12:10

user2914640


2 Answers

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

like image 54
littlejoe Avatar answered Oct 24 '25 03:10

littlejoe


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();
        }
    }
}
like image 30
user3240383 Avatar answered Oct 24 '25 01:10

user3240383



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!