Extracting hyperlinks from PDF

Viewed 13

I'm trying to make some changes (replacing and adding pages) in PDF file, i use PDFsam Basic program to cut PDF pages, and then i replace them with corrected ones. The problem is, when i merge PDF file after some changes back together - the hyperlinks (links to page) does not work properly. It works only in sectors that were not cut. E.g - File has 60 pages, i want to replace page number 20 so i cut it after page 19 and 21. The program outputs 3 files:

  • File1 (contains pages from 1-19)
  • File2 (contains page 20 - the one i want to replace)
  • File3 (contains pages left - from 21-60)

After I replace a page and merge those 3 files back to 1 file, the links to pages works only in sectors they've been cut, so for example:

  • I can click on hyperlink that moves me from page 5 to page 12 or from page 23 to page 49 and those links works just fine. But I cannot move for example from page 5 to page 49 etc. There are no such hyperlinks. Ofcourse there are no hyperlinks on page that was replaced (number 20) aswell.

I don't have Adobe Acrobat Pro to add those links to pages. Is there any way i can extract those links to pages from PDF file using python? Then replace pages, merge file back together and after that input those hyperlinks back to that PDF in the same spots?

I've been looking on PyPDF2 and pikepdf library, and got some code:

import PyPDF2
PDFFile = open("PRE09-EDIA-9410-001-A-REV04.pdf",'rb')

PDF = PyPDF2.PdfFileReader(PDFFile)
pages = PDF.getNumPages()
key = '/Annots'
uri = '/URI'
ank = '/A'

for page in range(pages):
    print("Current Page: {}".format(page))
    pageSliced = PDF.getPage(page)
    pageObject = pageSliced.getObject()
    if key in pageObject.keys():
        ann = pageObject[key]
        for a in ann:
            u = a.getObject()
            if uri in u[ank].keys():
                print(u[ank][uri])

Maybe someone has so ideas how to do it the simplest way? Thanks!

0 Answers
Related