Merge Two or More PDFs
The code above enables you to combine multiple PDF documents created from different HTML contents into a single PDF file.
Two HTML contents have been rendered into separate PDF documents. The PdfDocument.mergePdf
method is utilized to merge the two PDF documents, pdfdoc_a
and pdfdoc_b
, into a single PDF document named "merged."
The merging process is not limited to freshly rendered PDFs; it can also be applied to existing PDF documents using this method.
# Import required libraries
from pypdf import PdfMerger
# Paths to the PDF documents that need to be merged
pdf_path_a = "path/to/pdfdoc_a.pdf"
pdf_path_b = "path/to/pdfdoc_b.pdf"
# Initialize a PdfMerger object
merger = PdfMerger()
# Append the first PDF document to the merger object
merger.append(pdf_path_a)
# Append the second PDF document to the merger object
merger.append(pdf_path_b)
# Write out the merged PDF to a new file
with open("merged.pdf", "wb") as output_pdf:
merger.write(output_pdf)
# Close the merger to free up resources
merger.close()
# Import required libraries
from pypdf import PdfMerger
# Paths to the PDF documents that need to be merged
pdf_path_a = "path/to/pdfdoc_a.pdf"
pdf_path_b = "path/to/pdfdoc_b.pdf"
# Initialize a PdfMerger object
merger = PdfMerger()
# Append the first PDF document to the merger object
merger.append(pdf_path_a)
# Append the second PDF document to the merger object
merger.append(pdf_path_b)
# Write out the merged PDF to a new file
with open("merged.pdf", "wb") as output_pdf:
merger.write(output_pdf)
# Close the merger to free up resources
merger.close()
Explanation
- Library Import: We import
PdfMerger
from thepypdf
library, which is responsible for merging the PDFs. - File Paths: Define the file paths for the PDFs to be merged. Modify
pdf_path_a
andpdf_path_b
to the actual file paths of the PDFs you wish to merge. - PdfMerger Object: We create an instance of
PdfMerger
to which we can append the individual PDFs. - Appending PDFs: Use the
append
method ofPdfMerger
to add each PDF into the merger sequence. - Writing the Merged PDF: Open (or create) the file where the merged content will be saved using a context manager
with open(...)
. This ensures the file is properly closed after writing. - Closing the Merger: Calls
merger.close()
to clean up resources used byPdfMerger
.
This code is useful for combining PDFs generated from different sources or pre-existing files, facilitating easy document management.