Search code examples
pythonpdfoutlinepikepdf

Copying the outlines from PDF1 to PDF2 using the pikepdf module


I wrote some code that reorders the pages of PDF1 and saves them to PDF2:

import pikepdf

def Main():
    with pikepdf.open("pdf1.pdf") as sourcePDF:
        sourcePages = sourcePDF.pages
        targetPDF = pikepdf.Pdf.new()
        targetPages = targetPDF.pages
        # Reorder the pages basing on the previously provided list
        for idx in [1, 7, 2, 3, 4, 5, 6, 0]:
            targetPages.append(sourcePages[idx])
        targetPDF.save("pdf2.pdf")
        
if __name__ == "__main__":
    Main()

Is there any way to copy the outlines (bookmarks etc.) too, by assigning them to the desired pages?

So far, I tried something like this:

with sourcePDF.open_outline() as sourceOutline:
    with targetPDF.open_outline() as targetOutline:
        for outline in sourceOutline.root:
            targetOutline.root.append(sourcePDF.copy_foreign(outline))

But I cannot figure out how to use the copy_foreign method properly.


Solution

  • As Jorj McKie said, I used PyMuPDF instead of PyPDF2. My final code looks like this:

    doc = fitz.open("pdf1.pdf")
    doc.select([1, 7, 2, 3, 4, 5, 6, 0])
    doc.save("pdf2.pdf")