Skip to main content

Command Palette

Search for a command to run...

How to Delete PDF Pages in C# | Free .NET PDF API

Published
2 min read

I. Why Automate PDF Page Deletion?

In digital workplace scenarios, PDF files often contain extra pages due to export errors, redundant content, or format compatibility issues. Manual deletion is not only inefficient but also risks corrupting the file structure. For C# developers, robust automated processing solutions are essential—and Free Spire.PDF for .NET delivers exactly that: a free API supporting page deletion, merging, splitting, and more, with no need to install Adobe Acrobat.


II. Step-by-Step Guide

1. Install the Free Library

Install via NuGet Console: In 「Tools」→「NuGet Package Manager」→「Package Manager Console」, enter the command:

Install-Package FreeSpire.PDF

2. Load PDF Document

Use the PdfDocument class to load the target PDF file, ensuring the path is valid:

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("input.pdf");

3. Locate and Delete Specific Pages

Operate the page collection through PdfPageBaseCollection:

// Delete the 3rd page (index starts from 0)
pdf.Pages.RemoveAt(2);

4. Delete Multiple Pages

If you need to delete multiple pages:

// Define the page numbers to delete (example: delete the 2nd and 4th pages)
int[] pagesToDelete = new int[] { 1, 3 };
// Note: When deleting multiple pages, you need to **delete in reverse order** (to avoid deletion errors caused by page number shifting)
Array.Sort(pagesToDelete);
Array.Reverse(pagesToDelete);
foreach (int pageNum in pagesToDelete)
{
   // Check if the page number is valid (1 ≤ page number ≤ total number of pages)
   if (pageNum >= 1 && pageNum <= pdf.Pages.Count)
   {
      pdf.Pages.RemoveAt(pageNum);
    }

5. Save the Modified Document

Call the SaveToFile method to output the result, which supports overwriting the original file or saving as a new file:

pdf.SaveToFile("output.pdf");

III. Practical Tips & Considerations

3.1 Error Handling

Add exception capture handling:

try
{
    // Deletion operation code
}
catch (ArgumentException ex)
{
    Console.WriteLine($"Invalid page number: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Operation failed: {ex.Message}");
}

3.2 Advanced Application Scenarios

  • Batch deletion: Use LINQ to filter pages with specific content
  • Conditional deletion: Locate pages containing sensitive information through PdfTextFinder
  • Integration with Office documents: Delete redundant pages after converting Word to PDF

With Free Spire.PDF for .NET, developers can quickly implement the function of deleting specific pages in PDF. The core steps are "load file → specify page numbers → delete → save"

More from this blog