Splitting a PDF from .NET (C# Code Provided)

by Anil S Tue, May 22 2012, 1:47 PM (US Eastern Time)

We get a decent amount of people who ask us about dynamically splitting a PDF.  Splitting a PDF document using DynamicPDF Merger for .Net is a very simple task. With the few lines of code the document can be split efficiently at the desired page. Use of PdfDocument object allows for efficient reuse of imported PDF document data. If the same PDF needs to be reused in multiple parts of the application, load the PDF into a PdfDocument object and use it where ever needed. Also the PdfDocument object is designed to be thread safe.
 
Let’s take a look at an example where we want to take a PDF file (pdfToSplit.pdf) and split it into two files (pdfA.pdf and pdfB.pdf).  The first PDF split (pdfA.pdf) will contain the first 50 pages of the file while the second PDF (pdfB.pdf) will contain all remaining pages.  Notice that we do not need to know how many pages the original PDF contained by utilizing the PdfDocument’s Pages.Count method.

            //Create a PdfDocument object to load the PDF.
            PdfDocument pdfToSplit = new PdfDocument("pdfToSplit.pdf");

            //Page number to split the document at. 
            int pageNumToSplit = 50;

            //Add first 50 pages and call the Draw method to save the PDF. 
            MergeDocument firstPdf = new MergeDocument(pdfToSplit, 1, pageNumToSplit);
            firstPdf.Draw("pdfA.pdf");

            //Add the remaining pages to a second document and save the PDF. 
            MergeDocument secondPDF = new MergeDocument(pdfToSplit, pageNumToSplit + 1, pdfToSplit.Pages.Count - pageNumToSplit);
            secondPDF.Draw("pdfB.pdf");

More...

Tags: , , , ,