# Merge PDF files in C#

> Combine several PDF files into one in .NET with PdfDocument.Merge. Shared fonts and images are written once. MIT licensed, pure C#.

Available since 1.0.

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

## Short answer

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.

```csharp title="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");
```

```bash
dotnet add package PdfNetStack
```

## Variations

- 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.

## Related

- [Edit pages](https://www.jadev-corp.com/guides/edit-pages/): import, reorder, rotate and remove pages
- [Command line](https://www.jadev-corp.com/cli/): `pdfnetstack merge out.pdf a.pdf b.pdf c.pdf`
- API: [PdfDocument](https://www.jadev-corp.com/api/pdfnetstack/pdfdocument/), [PdfPageCollection](https://www.jadev-corp.com/api/pdfnetstack/pdfpagecollection/)

Source: https://www.jadev-corp.com/pdfnetstack/recipes/merge-pdf-files/
