Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to overwrite specific page of PDF with another page of another PDF with Python's PyPDF2

I want to overwrite the first page of a PDF with another page of another PDF using the PyPDF2 library in Python.

For more detail, I have two separate PDFs (let’s call them overwritten.pdf and other.pdf) and I want to replace the first (it doesn’t have to be the first) page of overwritten.pdf with a specific page of other.pdf so the first page of overwritten.pdf is that specific page of other.pdf.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I don’t know if you can literally "replace a page" with PyPDF2. I would use the merge function. Example from the PyPDF2 web site:

from PyPDF2 import PdfMerger

merger = PdfMerger()

input1 = open("document1.pdf", "rb")
input2 = open("document2.pdf", "rb")
input3 = open("document3.pdf", "rb")

# add the first 3 pages of input1 document to output
merger.append(fileobj=input1, pages=(0, 3))

# insert the first page of input2 into the output beginning after the second page
merger.merge(position=2, fileobj=input2, pages=(0, 1))

# append entire input3 document to the end of the output document
merger.append(input3)

# Write to an output PDF document
output = open("document-output.pdf", "wb")
merger.write(output)

# Close File Descriptors
merger.close()
output.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading