Код: Выделить всё
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 Folder\PDF Bookmark+Combiner\Test2.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 Folder\PDF Bookmark+Combiner\Test.pdf",2,link_data)
Код: Выделить всё
writer.add_annotation(page_number=0,annotation=link_annotation)
Код: Выделить всё
Exception has occurred: IndexError
sequence index out of range
File "E:\Work Folder\PDF Bookmark+Combiner\PDF_functions.py", line 119, in add_links_to_pdf
writer.add_annotation(page_number=0,annotation=link_annotation)
File "E:\Work Folder\PDF Bookmark+Combiner\PDF_functions.py", line 134, in
add_links_to_pdf("E:\Work Folder\PDF Bookmark+Combiner\Test.pdf",2,link_data)
IndexError: sequence index out of range
Подробнее здесь: https://stackoverflow.com/questions/790 ... tion-issue