How to merge multiple PDFs using Python

Here's a step-by-step example of how to merge multiple PDFs using PyMuPDF (fitz) in Python:




Install the fitz library:

Copy code
pip install PyMuPDF

Import the fitz library in your Python script:
python

Copy code
import fitz

Create a new fitz PDF object to store the merged PDF:
python

Copy code
merger = fitz.open()

Loop through the list of PDFs you want to merge:
sql

Copy code
pdf_list = ['file1.pdf', 'file2.pdf', 'file3.pdf']
for pdf in pdf_list:
    # Open each PDF
    doc = fitz.open(pdf)
    # Insert the contents of each PDF into the merger
    merger.insert_pdf(doc)
    # Close the PDF
    doc.close()
Save the merged PDF to a file:
python
Copy code
merger.save("output.pdf")



The complete code would look like this:
python


Copy code
import fitz

def merge_pdfs(pdf_list, output):
    # Create a PDF object to write the merged PDF to
    merger = fitz.open()

    # Loop through all PDFs in the list
    for pdf in pdf_list:
        # Open the PDF
        doc = fitz.open(pdf)
        # Read the PDF into the merger
        merger.insert_pdf(doc)
        # Close the PDF
        doc.close()

    # Write the merged PDF to the output file
    merger.save(output)

# Example usage
pdf_list = ['file1.pdf', 'file2.pdf', 'file3.pdf']
merge_pdfs(pdf_list, 'output.pdf')



This code will take a list of PDF filenames as input, merge them into a single PDF, and write the result to the specified output file.

Comments

Popular posts from this blog

Convert PDF Files to PPT Files in Python.

Compress PDF using python step by step

Shark Tank India: Focusing on the Innovative Technology Startups

Contact Form

Name

Email *

Message *