PyPDF2 is a Python library for reading existing PDF files, creating output PDFs, and combining pages. A practical use is adding matching cover pages to report files. section 9.4.1 section 9.4.2
A typical PDF-merging task separates into three parts:
- Input: open report and cover files in binary mode, then create PdfFileReader objects. section 9.4.1
- Process: read pages with getPage and add them to a PdfFileWriter in the required order. section 9.4.1 section 9.4.2
- Output: write the assembled PDF with write and close the input and output files. section 9.4.1
- Compatibility: PyPDF2 must be installed with its exact capitalization; older examples using PdfFileReader fail under PyPDF2 3.0.0. section 9.4.2
Add covers to reports
Define add_covers(report_dir, cover_dir, final_dir), match reports such as 1.pdf with cover1.pdf, prepend each cover page, and save finalized files in the output directory. Test carefully: opening a destination with 'wb' can overwrite an existing file, while missing imports or incompatible APIs can stop the program. section 9.4.2
```pythonimport PyPDF2# Open the PDF files to be mergedpdf1 = open('file1.pdf', 'rb')pdf2 = open('file2.pdf', 'rb')# Create a PDF reader object for each filereader1 = PyPDF2.PdfFileReader(pdf1)reader2 = PyPDF2.PdfFileReader(pdf2)# Create a PDF writer objectwriter = PyPDF2.PdfFileWriter()# Loop through the pages of each PDF and add them to the writer objectfor i in range(reader1.getNumPages()):page = reader1.getPage(i)writer.addPage(page)for i in range(reader2.getNumPages()):page = reader2.getPage(i)writer.addPage(page)# Write the merged PDF to a fileoutput = open('merged.pdf', 'wb')writer.write(output)# Close the input and output filespdf1.close()pdf2.close()output.close()```
Use the complete listing to inspect the reader, writer, page loop, output write, and file-closing workflow for merging two PDFs. section 9.4.1
