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 { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// Open or render the first PDF document
// Either from HTML, file path, or URL — here assuming file paths:
const pdfA = await PdfDocument.open("path/to/pdfdoc_a.pdf");
const pdfB = await PdfDocument.open("path/to/pdfdoc_b.pdf");
// Merge multiple PdfDocument instances into one
const merged = await PdfDocument.mergePdf([pdfA, pdfB]);
// Save the merged PDF to a new file
await merged.saveAs("merged.pdf");
})();
import { PdfDocument } from "@ironsoftware/ironpdf";
(async () => {
// Open or render the first PDF document
// Either from HTML, file path, or URL — here assuming file paths:
const pdfA = await PdfDocument.open("path/to/pdfdoc_a.pdf");
const pdfB = await PdfDocument.open("path/to/pdfdoc_b.pdf");
// Merge multiple PdfDocument instances into one
const merged = await PdfDocument.mergePdf([pdfA, pdfB]);
// Save the merged PDF to a new file
await merged.saveAs("merged.pdf");
})();
Explanation
- Import: uses
PdfDocument
from the@ironsoftware/ironpdf
package - Opening PDFs:
PdfDocument.open(...)
loads existing PDF files (rather than rendering HTML) — appropriate when merging pre‑existing PDFs. - Merging PDFs:
PdfDocument.mergePdf([pdfA, pdfB])
combines the two documents into a single instance - Saving the result:
merged.saveAs("merged.pdf")
writes out the merged PDF, equivalent to Python’smerger.write(...)
This code is useful for combining PDFs generated from different sources or pre-existing files, facilitating easy document management.