split pages using pdfsharp in csharp

To split pages using PdfSharp in C#, you can follow these steps:

  1. Install PdfSharp package from NuGet.
  2. Load the existing PDF from file using PdfSharp.Pdf.IO.PdfReader.Open() method.
  3. Loop through each page of the PDF and create a new PDF document for each page using PdfSharp.Pdf.PdfDocument() constructor.
  4. Add the page from the original PDF to the new PDF using PdfSharp.Pdf.PdfDocument.AddPage() method.
  5. Save the new PDF document to file using PdfSharp.Pdf.PdfDocument.Save() method.

Here's a sample code that splits a PDF file into multiple files, each containing only one page:

main.cs
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

string sourcePath = @"C:\input.pdf";
string outputPath = @"C:\output{0}.pdf";

// Load the existing PDF document
PdfDocument inputDocument = PdfReader.Open(sourcePath, PdfDocumentOpenMode.Import);

// Split the PDF into separate pages
for (int i = 0; i < inputDocument.PageCount; i++)
{
    // Create a new PDF document
    PdfDocument outputDocument = new PdfDocument();

    // Add the current page from the input document to the output document
    outputDocument.AddPage(inputDocument.Pages[i]);

    // Save the output document to file
    outputDocument.Save(String.Format(outputPath, i + 1));

    // Close the output document
    outputDocument.Close();
}

// Close the input document
inputDocument.Close();
760 chars
28 lines

Note that in this example, the output file name is generated using a placeholder "{0}" which is replaced with the page number. You can customize the output file name as per your requirement.

related categories

gistlibby LogSnag