DEV Community

Gia
Gia

Posted on • Edited on

How to Split a PDF Files into Multiple Files

In daily work or study, it's common to split a multi-page PDF document into several smaller files. For instance, dividing a large PDF document into separate files based on chapters can make it easier to manage and read. Users can choose their preferred page range, name, and save each generated PDF file as required. This process can be accomplished using professional PDF editing software or through programming. In this article, I will introduce how to split a PDF file in C# program.

Step 1 Create a Project

Create a new project in Visual Studio

Step 2 Import the DLL File into Project

  • Download and install Free Spire.PDF for .NET.
  • Open the new project.
  • Right-click "References" in the "Solution Explorer".
  • Select "Add Reference" > "Browse".
  • Find the dll file in the BIN folder under the installation path, and click "OK".

Step 3 Write code

Write code in your program
or you can also copy the following code and paste it to program

using Spire.Pdf;
using System;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the input file path and output directory
            String inputFile = "sample.pdf";
            String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            //Create a PdfDocument objects and load sample file
            PdfDocument sourceDoc = new PdfDocument(inputFile);

            //Create two additional PdfDocument objects
            PdfDocument newDoc_1 = new PdfDocument();
            PdfDocument newDoc_2 = new PdfDocument();

            //Insert the first page of source file to the first document
            newDoc_1.InsertPage(sourceDoc, 0);

            //Insert the rest pages of source file to the second document
            newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);

            //Save the two documents 
            newDoc_1.SaveToFile(outputDirectory + "output1.pdf");
            newDoc_2.SaveToFile(outputDirectory + "output2.pdf");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Using the above code, you can split a multi-page PDF file into multiple individual files effortlessly. Additionally, Free Spire.PDF for .NET supports a variety of other document operations and conversions, such as merging PDFs and converting PDFs to images.

Top comments (2)

Collapse
 
avinashdalvi_ profile image
Avinash Dalvi

Nice article 👏🏻. Welcome to dev.to. One recommendation can step 2 explained in bullet points.

Collapse
 
gia-- profile image
Gia

Thanks for your advice!!