split pdf pages using pdfsharp in csharp in csharp

To split PDF pages using PdfSharp in C# you can use the PdfDocument class from the library. First, create an instance of PdfDocument class and load the PDF document you want to split. Then loop through the pages you want to extract and add them to a new PdfDocument instance. Finally, save the extracted pages as a new PDF document.

Here is an example code snippet that demonstrates how to split PDF pages using PdfSharp in C#:

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

public static void SplitPdf(string inputFilePath, int startPage, int endPage, string outputFilePath)
{
    // Load the input PDF document
    using (PdfDocument inputDocument = PdfReader.Open(inputFilePath, PdfDocumentOpenMode.Import))
    {
        // Create a new PDF document that will contain the extracted pages
        PdfDocument outputDocument = new PdfDocument();

        // Loop through the pages of the input PDF document
        for (int pageNumber = startPage; pageNumber <= endPage; pageNumber++)
        {
            // Get the page from the input document
            PdfPage page = inputDocument.Pages[pageNumber - 1];

            // Add the page to the output document
            outputDocument.AddPage(page);
        }

        // Save the extracted pages as a new PDF document
        outputDocument.Save(outputFilePath);
    }
}
898 chars
26 lines

To use this method, you can call it with the input PDF file path, the start and end page numbers you want to extract, and the output file path for the resulting PDF document:

main.cs
string inputFilePath = "input.pdf";
int startPage = 1;
int endPage = 3;
string outputFilePath = "output.pdf";

SplitPdf(inputFilePath, startPage, endPage, outputFilePath);
172 chars
7 lines

This will extract pages 1 to 3 from the input PDF document and save them as a new PDF document at the specified output file path.

gistlibby LogSnag