Skip to content

Merge PDF files in C#

Since 1.0View as Markdown

Combine several PDFs into one document, pages in the order you give.

Open each file with PdfDocument.Open, pass them to PdfDocument.Merge, and save the result. Saving runs the lossless optimizer, so fonts and images the files share are written once.

recipe-merge-pdf-files.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
string[] files = ["a.pdf", "b.pdf", "c.pdf"];
PdfDocument merged = PdfDocument.Merge(files.Select(file => PdfDocument.Open(file)));
merged.Save("merged.pdf"); // shared fonts and images are written once
Console.WriteLine($"merged.pdf: {merged.Pages.Count} pages");
Terminal window
dotnet add package PdfNetStack
  • To insert pages at a given place instead, use doc.Pages.Import(other.Pages, index).
  • Annotations travel with their pages. Links to pages imported in the same call are remapped.
  • Encrypted inputs open with PdfDocument.Open(path, password). Pages can be copied out of them only when their permissions allow copying.