i am trying to add a link to a pdf document currently its set up to eventually loop through and add multiple annotations to point to many different pages but as of right now i just need to get the annotation to wordk hardcoded on 1 file before i complete the loop.
from pypdf import PdfWriter, PdfReader
from pypdf.annotations import Link as pdf_link
from pypdf.generic import Fit,NumberObject
def add_links_to_pdf(pdf_path,page_link,link_locations):
# Read the PDF
reader = PdfReader(pdf_path)
writer = PdfWriter()
for page_num in range(len(reader.pages)):
page = reader.pages[page_num]
for link in link_locations:
if link[0] == page_num:
# Create the link annotation
link_annotation = pdf_link(
rect=(50, 550, 200, 650),
target_page_index=0,
fit=Fit(fit_type="/FitH", fit_args=(123,)),
)
writer.add_annotation(page_number=0,annotation=link_annotation)
# Add the annotation to the page
# Add the modified page to the writer
writer.add_page(page)
# Write the output to a new file
with open("E:Work FolderPDF Bookmark+CombinerTest2.pdf", "wb") as output_file:
writer.write(output_file)
link_data = [
(0, 100, 750, 50, 700) # (page_number, x1, width, top, height)
]
#
add_links_to_pdf("E:Work FolderPDF Bookmark+CombinerTest.pdf",2,link_data)
i tried this and i used a python debugger to step through it. currently the line below is causing the error.
writer.add_annotation(page_number=0,annotation=link_annotation)
the error message is below
Exception has occurred: IndexError
sequence index out of range
File "E:Work FolderPDF Bookmark+CombinerPDF_functions.py", line 119, in add_links_to_pdf
writer.add_annotation(page_number=0,annotation=link_annotation)
File "E:Work FolderPDF Bookmark+CombinerPDF_functions.py", line 134, in <module>
add_links_to_pdf("E:Work FolderPDF Bookmark+CombinerTest.pdf",2,link_data)
IndexError: sequence index out of range
Any help would be greatly appreciated, Thanks.
1