Guide
How to merge PDFs in C#
Load the destination PDF, append pages from one or more source streams with
AppendPdfAsync(...), and save the result.
The main thing to get right is page order and stream handling. The pages are appended in the order you call the method, and the final save follows the same stream rules as the rest of the API.
The shortest working example
Start with the PDF you want to keep as the base document, append the other file, then save.
using ZingPDF;
using var baseStream = File.OpenRead("base.pdf");
using var appendStream = File.OpenRead("appendix.pdf");
using var pdf = Pdf.Load(baseStream);
await pdf.AppendPdfAsync(appendStream);
await pdf.SaveAsync(File.Create("merged.pdf"));
That produces a new file containing the original pages from base.pdf followed by the pages
from appendix.pdf.
Merging more than two PDFs
If you need to combine several PDFs, keep the destination document open and append each source in sequence.
using ZingPDF;
using var output = File.Create("combined.pdf");
using var pdf = Pdf.Load(File.OpenRead("part-1.pdf"));
foreach (var path in new[] { "part-2.pdf", "part-3.pdf", "part-4.pdf" })
{
using var stream = File.OpenRead(path);
await pdf.AppendPdfAsync(stream);
}
await pdf.SaveAsync(output);
The order in that loop is the order of the final document. If your input list comes from a database, queue, or API, sort it before you append.
Page order and destination choice
AppendPdfAsync(...) appends pages onto the current document. It does not insert them into the
middle of the page tree.
That means the simplest rule is to load the document whose metadata and starting pages you want to keep, then append everything else to it.
If you need to merge files and then add a final document-level mark, do the merge first and call
AddWatermarkAsync(...) afterward.
Stream requirements
The source streams you load or append need to be readable as PDFs, and the output stream for
SaveAsync(...) still needs to be writable and seekable.
- The base document stream passed to
Pdf.Load(...)must be seekable. - Each appended PDF stream should be opened as its own readable stream.
- The output stream passed to
SaveAsync(...)must be writable and seekable. - If you save to a different stream, it must be empty.
Combine the merge with another document update
After the merge, a common next step is adding a document-wide watermark before saving the output.