HTML to PDF Converter ASP.NET Core samples · .NET 10 and .NET 11

ExpertPdf Html To Pdf Converter for .NET - Pdf Split - C# / ASP.NET Sample

This sample shows how to use ExpertPdf Html To Pdf Converter 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 will create a new pdf document containing only pages 2 and 3 from the original pdf document.

C# code of this sample

Pages/PdfSplit.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ExpertPdf.HtmlToPdf.PdfDocument;

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

        public IActionResult OnPost()
        {
            // the initial file
            string file1 = Startup.ServerPath + @"\wwwroot\files\doc.pdf";

            // load the pdf document (do not close this document until the final Save)
            Document doc1 = new Document(file1);

            // create a new pdf document
            Document doc = new Document();

            // add 2 pages to the new document
            if (doc1.Pages.Count > 2)
            {
                doc.AddPage(doc1.Pages[1]);
                doc.AddPage(doc1.Pages[2]);
            }

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

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

        }
    }
}