liveBook · Manning

PyMuPDF

As explained in Learn AI-Assisted Python Programming, Second Edition

PyMuPDF is a library for accessing and processing PDF documents and their text, graphics, and images.

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

```python
import fitz
 
# Merge the two PDF files
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()
```

Browse the complete two-file merge listing, including document creation, page insertion, saving, and closing. section 9.4.2

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains installation, import naming, document creation, page insertion, saving, and closing without covering library internals.
Examples
Uses two input PDFs, fitz.Document, insert_pdf(), merged.pdf, and a directory-based cover-adding function.
What it assumes
Assumes basic Python file handling and PDF paths while showing the required package installation and import name.
What you can do after
Apply PyMuPDF via Python to merge PDF files into a saved output document.
How it connects
Connects PDF merging with Python modules, PDF documents, pages, and file output.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.