how do i change hyperlinks inside pdf using python?

Viewed 3010

How do I change the hyperlinks in pdf using python? I am currently using a pyPDF2 to open up and loop through the pages. How do I actually scan for hyperlinks and then proceed to change the hyperlinks?

2 Answers

I managed to get it working with PyPDF2.

If you just want to remove all annotations for a page, you just have to do:

if '/Annots' in page: del page['/Annots']

Else, here is how you change each link:

import PyPDF2

new_link = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # great video by the way

pdf_reader = PyPDF2.PdfFileReader("input.pdf")
pdf_writer = PyPDF2.PdfFileWriter()

for i in range(pdf_reader.getNumPages()):
    page = pdf_reader.getPage(i)
    
    if '/Annots' not in page: continue
    for annot in page['/Annots']:
        annot_obj = annot.getObject()
        if '/A' not in annot_obj: continue  # not a link
        # you have to wrap the key and value with a TextStringObject:
        key   = PyPDF2.generic.TextStringObject("/URI")
        value = PyPDF2.generic.TextStringObject(new_link)
        annot_obj['/A'][key] = value
    
    pdf_writer.addPage(page)

with open('output.pdf', 'wb') as f:
    pdf_writer.write(f)

An equivalent one-liner for a given page index i and annotation index j would be:

pdf_reader.getPage(i)['/Annots'][j].getObject()['/A'][PyPDF2.generic.TextStringObject("/URI")] = PyPDF2.generic.TextStringObject(new_link)
Related