How to merge multiple PDFs into one?¶
The pypdf library manipulates PDF documents on the page level, e.g. merging two or more PDFs.
Install it with:
pip install pypdf
The following code merges all PDF files from the input path into a single one:
import os
from pypdf import PdfMerger
from pathlib import Path
input_path = Path("input")
merger = PdfMerger()
for fn in os.listdir(input_path):
if fn.endswith('.pdf'):
merger.append(open(input_path / fn, "rb"))
output = open("result.pdf", "wb")
merger.write(output)
How to merge multiple images into a PDF¶
With pypdf you can also merge images into a PDF:
from PyPDF2 import PdfMerger
from PIL import Image
files = [
"image1.jpg,
"image2.jpg,
"image3.jpg,
]
output_pdf = "merged_output.pdf"
merger = PdfMerger()
images = [Image.open(img).convert('RGB') for img in files]
images[0].save(output_pdf, save_all=True, append_images=images)