I'm trying to attach a file to a PDF file, but I'm running into some issues. I'm not sure if I'm doing something wrong or if there's a bug in PyPDF2. I'm using Python 3.10.2 for this and I downloaded the newest package for PyPDF2 through pip.
These are 3 versions of code that I tried using, but each has its own issues.
- This code copies the PDF properly, but the attachment fails silently. I can confirm the failure because the file size didn't grow.
pdfFile = open("input.pdf", "rb")
reader = PdfReader(pdfFile)
writer = PdfWriter()
writer.clone_document_from_reader(reader) # this line is different
pdfFile.close()
with open("image.png", "rb") as file:
writer.add_attachment("image", file.read())
with open("output.pdf", "wb") as file:
writer.write(file)
- This code is slightly different than the one before, but also fails to attach the file.
pdfFile = open("input.pdf", "rb")
reader = PdfReader(pdfFile)
writer = PdfWriter()
writer.clone_reader_document_root(reader) # this line is different
writer.append_pages_from_reader(reader) # this line is different
pdfFile.close()
with open("image.png", "rb") as file:
writer.add_attachment("image", file.read())
with open("output.pdf", "wb") as file:
writer.write(file)
- This code actually does attach the file, but upon opening the file in Adobe Acrobat, I get the error: "The was an error opening this document. The root object is missing or invalid." I don't see any API calls for creating a root object manually in PyPDF2.
pdfFile = open("input.pdf", "rb")
reader = PdfReader(pdfFile)
writer = PdfWriter()
writer.append_pages_from_reader(reader) # this line is different
pdfFile.close()
with open("image.png", "rb") as file:
writer.add_attachment("image", file.read())
with open("output.pdf", "wb") as file:
writer.write(file)
Funny enough, I don't get the error if I run the 3rd version of the code without attaching the file. Then it just works like the first 2 versions.