PyMuPDF is a Python library for working with PDF files, including merging documents and handling text, graphics, and images. Install it as PyMuPDF but import it as fitz. section 9.4.1 section 9.4.2
A basic PDF-merging workflow:
- Create a fitz.Document object for the output PDF. section 9.4.2
- Open each input PDF with fitz.open and add its pages with insert_pdf(). section 9.4.2
- Save the merged document and close it after processing. section 9.4.2
Merging two PDF files
import fitz pdf_files = ['file1.pdf', 'file2.pdf'] pdf_writer = fitz.Document() for pdf_file in pdf_files: pdf_reader = fitz.open(pdf_file) for page in pdf_reader: pdf_writer.insert_pdf(page) pdf_writer.save('merged.pdf') pdf_writer.close() section 9.4.2
```pythonimport fitz# Merge the two PDF filespdf_files = ['file1.pdf', 'file2.pdf']pdf_writer = fitz.Document()for pdf_file in pdf_files:pdf_reader = fitz.open(pdf_file)for page in pdf_reader:pdf_writer.insert_pdf(page)pdf_writer.save('merged.pdf')pdf_writer.close()```
Browse the complete two-file merge listing, including document creation, page insertion, saving, and closing. section 9.4.2
