DEV Community

Gia
Gia

Posted on

How to Delete PDF Pages in C#

Compared to other document formats, the PDF document format is more stable and generally difficult to edit or change. However, in our daily work, dealing with PDF documents is essential. For example, by removing duplicate or unnecessary pages from a PDF document, you can simplify the content of the document and provide a better viewing experience for readers. It can save you a lot of effort and time, especially for large documents. This article will share how to delete specified pages in a PDF file through a C# program.

Tool:

  • Visual Studio 2022
  • Free Spire.PDF for .NET This is a free version of Spire.PDF for Java, supports editing and converting PDF on .NET platforms freely. You can also download the commercial version from this link and trial it for 30 days.

Installation:

  • Download and install Free Spire.PDF for .NET.
  • Create a new C# project and open it.
  • Right-click " References " in the " Solution Explorer ".
  • And then select " Add Reference " > " Browse ".
  • Find the DLL file in the BIN folder under the installation path and click " OK " to add it as a reference.

Sample Code:

using Spire.Pdf;

namespace RemovePage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument document = new PdfDocument();

            //Load a sample PDF document
            document.LoadFromFile(@"sample.pdf");

            //Remove the second page
            document.Pages.RemoveAt(1);

            //Save the result document
            document.SaveToFile("RemovePages.pdf");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

First, create a PdfDocument object and load β€œ sample.pdf ”. And then get the desired page by PdfDocument.Pages property and delete it by using PdfPageCollection.RemoveAt(int index) method. Finally, save the document to another file.

Image description

Top comments (0)