DEV Community

Jeremy K.
Jeremy K.

Posted on

Delete PDF Pages in C#

In modern digital workflows, PDF files often contain unwanted pages due to export errors, duplicate content, or formatting issues. Manually deleting pages is slow and risks corrupting the file structure.

C# developers need a reliable, automated solution. Free Spire.PDF for .NET offers a free API to delete, merge, split, and manipulate PDF pages – without installing Adobe Acrobat.


Installation

Use NuGet Package Manager Console:

Install-Package FreeSpire.PDF
Enter fullscreen mode Exit fullscreen mode

Or search FreeSpire.PDF in Manage NuGet PackagesBrowse → Install.

Load the PDF Document

using Spire.Pdf;

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("input.pdf");
Enter fullscreen mode Exit fullscreen mode

Delete a Single Page

Pages are zero-indexed. To delete page 3:

pdf.Pages.RemoveAt(2);  // Removes the 3rd page
Enter fullscreen mode Exit fullscreen mode

Delete Multiple Pages (Safe Reverse Order)

When deleting multiple pages, always delete from the highest to the lowest index to avoid shifting errors.

int[] pagesToDelete = new int[] { 1, 3 }; // Pages 1 and 3 (1-based)

Array.Sort(pagesToDelete);
Array.Reverse(pagesToDelete);

foreach (int pageNum in pagesToDelete)
{
    if (pageNum >= 1 && pageNum <= pdf.Pages.Count)
    {
        pdf.Pages.RemoveAt(pageNum - 1); // Convert to zero-based
    }
}
Enter fullscreen mode Exit fullscreen mode

Save the Modified PDF

pdf.SaveToFile("output.pdf");
pdf.Close();
Enter fullscreen mode Exit fullscreen mode

Advanced PDF Deletion Scenarios

Scenario Description
Batch delete Use LINQ to delete all pages with specific text or pattern.
Conditional delete Find pages containing sensitive data (e.g., SSN, credit card) using PdfTextFinder.
Office integration Remove blank or redundant pages after Word/Excel to PDF conversion.

Best Practices for C# PDF Page Removal

  • ✅ Always validate page numbers before deletion.
  • ✅ Delete multiple pages in reverse order.
  • ✅ Use try-catch blocks to handle corrupted files or invalid paths.
  • ✅ Call pdf.Close() to release resources.

Conclusion

The Free Spire.PDF library provides a straightforward API for deleting PDF pages in C#:

  • Load the PDF with PdfDocument.LoadFromFile.
  • Use Pages.RemoveAt(index) to delete pages (zero‑based indexing).
  • For multiple deletions, sort indices descending.
  • Save the document with SaveToFile.

Frequently Asked Questions (FAQ)

Can I delete PDF pages without Adobe Acrobat?

Yes, Free Spire.PDF for .NET works completely independently.

Is Free Spire.PDF really free?

Yes, for personal and commercial use, but with a 10-page limit.

How to delete the last page of a PDF?

Use pdf.Pages.RemoveAt(pdf.Pages.Count - 1);

Top comments (0)