SelectPdf for .NET - Pdf Split - C# / ASP.NET MVC 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 will create a new pdf document containing only pages 2 and 3 from the original pdf document.


Sample Code C#



using System.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class PdfSplitController : Controller
    {
        // GET: PdfSplit
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // the initial file
            string file1 = Server.MapPath("~/files/doc.pdf");

            // load the pdf document
            PdfDocument doc1 = new PdfDocument(file1);

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

            // 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 = "Document.pdf";
            return fileResult;
        }
    }
}