SelectPdf for .NET 10 - Pdf Split - C# / .NET 10 Sample

This sample shows how to use SelectPdf Library for .NET to split a pdf document into several pdf documents or extract only certain pages from the original document and create a new pdf document only with them.

Here is our initial test pdf document:
Test file

Click on the "Create PDF" button below to see the result. This sample uses a PdfSplitManager to extract pages 2 and 3 from the original pdf document into a new pdf document.

Sample code · C#
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PdfSplitModel : PageModel
    {
        public void OnGet()
        {

        }

        public IActionResult OnPost()
        {
            // the initial file
            string file1 = Path.Combine(Startup.ServerPath, "wwwroot", "files", "doc.pdf");

            // load the pdf document into a split manager
            PdfSplitManager splitter = new PdfSplitManager();
            byte[] pdf;
            try
            {
                splitter.Load(file1);

                // extract pages 2 and 3 into a new pdf document
                PdfDocument doc = splitter.ExtractPages("2-3");
                try
                {
                    // save pdf document
                    pdf = doc.Save();
                }
                finally
                {
                    // close pdf document
                    doc.Close();
                }
            }
            finally
            {
                // release the initial document
                splitter.Close();
            }

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}