[ 
https://issues.apache.org/jira/browse/PDFBOX-2400?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=14955126#comment-14955126
 ] 

Tilman Hausherr commented on PDFBOX-2400:
-----------------------------------------

My attempt at this:
{code}
    /**
     * Insert a page before another page within a page tree.
     *
     * @param nextPage the page that is to be after the new page.
     * @param newPage the page to be inserted.
     * @throws IllegalArgumentException if one attempts to insert a page that 
isn't part of a page
     * tree.
     */
    public void insertBefore(PDPage nextPage, PDPage newPage)
    {
        COSDictionary nextPageDict = nextPage.getCOSObject();
        COSDictionary parentDict = (COSDictionary) 
nextPageDict.getDictionaryObject(COSName.PARENT);
        COSArray kids = (COSArray) parentDict.getDictionaryObject(COSName.KIDS);
        boolean found = false;
        for (int i = 0; i < kids.size(); ++i)
        {
            COSDictionary pageDict = (COSDictionary) kids.getObject(i);
            if (pageDict.equals(nextPage.getCOSObject()))
            {
                kids.add(i, newPage.getCOSObject());
                newPage.getCOSObject().setItem(COSName.PARENT, parentDict);
                found = true;
                break;
            }
        }
        if (!found)
        {
            throw new IllegalArgumentException("attempted to insert before 
orphan page");
        }

        // now increase every parent
        do
        {
            int cnt = parentDict.getInt(COSName.COUNT);
            parentDict.setInt(COSName.COUNT, cnt + 1);
            parentDict = (COSDictionary) 
parentDict.getDictionaryObject(COSName.PARENT);
        }
        while (parentDict != null);
    }
{code}
to test:
{code}
        PDPage newPage = new PDPage();
        PDPage nextPage = doc.getPage(23);

        insertBefore(nextPage, newPage);
{code}



> Add insertPage() method
> -----------------------
>
>                 Key: PDFBOX-2400
>                 URL: https://issues.apache.org/jira/browse/PDFBOX-2400
>             Project: PDFBox
>          Issue Type: New Feature
>          Components: PDModel
>    Affects Versions: 1.8.7, 2.0.0
>            Reporter: Patrick Tucker
>            Priority: Minor
>             Fix For: 2.1.0
>
>
> It would be nice if PDDocument had an insertPage function similar to addPage, 
> but takes a number to indicate where to add the new page in the current set 
> of pages.



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to