Extract pages from a PDF in C#
Copy some pages of a PDF into a new document, in the order you choose.
Short answer
Section titled “Short answer”Create an empty document with PdfDocument.Create, then import the pages you want with
Pages.Import. Page numbers in the sample start at 1. Fonts and images shared between the pages
are copied once.
#:package PdfNetStack@1.2.0using PdfNetStack;
PdfDocument source = PdfDocument.Open("manual.pdf");int[] keep = [1, 2, 5]; // page numbers, from 1, in the order you want them
PdfDocument extract = PdfDocument.Create();extract.Pages.Import(keep.Select(n => source.Pages[n - 1]));extract.Save("manual-extract.pdf");Console.WriteLine($"manual-extract.pdf: {extract.Pages.Count} pages");dotnet add package PdfNetStackAnnotations are copied fresh for every import. Links to pages imported in the same call are remapped, and links to pages left behind become empty.
Related
Section titled “Related”- Edit pages
- Command line:
pdfnetstack extract in.pdf out.pdf 1-3,7,9-takes ranges in any order, repeats allowed - API: PdfPageCollection