Add and remove pages in an existing PDF

PDF Read Write Graphics Container

This sample shows how to insert and delete pages of an existing PDF document. Since PDF pages can't be edited in place, it reopens the source file with PdfReader and rebuilds it page by page with PdfWriter: copying each page's content with GetContent and Graphics.DrawContainer, skipping the page to remove, and adding a brand-new page where one should be inserted.

Сode Snippet

System.Action<Graphics, float, float, RgbColor, string> drawLabeledPage = (gr, width, height, color, label) =>
{
    gr.FillRectangle(new SolidBrush(color), 0, 0, width, height);

    var font = gr.CreateFont("Arial", 28f);
    var text = new PlainText(label, font, new SolidBrush(RgbColor.White), width / 2f, (height / 2f) - 20f, TextAlignment.Center);
    gr.DrawText(text);
};

const string originalPath = "Original.pdf";
const string editedPath = "EditedDocument.pdf";
const float dpi = 150f;
var pageWidth = UnitConverter.ConvertUnitsToPixels(dpi, 5f, Unit.Inch);
var pageHeight = UnitConverter.ConvertUnitsToPixels(dpi, 3f, Unit.Inch);

// Build a simple 4-page starting document to edit afterwards.
var pageColors = new[] { RgbColor.SteelBlue, RgbColor.DarkOrange, RgbColor.ForestGreen, RgbColor.Firebrick };
using (var writer = new PdfWriter(originalPath))
using (var gr = writer.GetGraphics())
{
    for (var i = 0; i < pageColors.Length; i++)
    {
        writer.AddPage(pageWidth, pageHeight, dpi, dpi);
        drawLabeledPage(gr, pageWidth, pageHeight, pageColors[i], string.Format("Page {0}", i + 1));
    }
}

// PDF pages can't be edited in place, so the document is rebuilt page by page instead:
// the page to remove is simply never copied, and the new page is written in its place.
const int pageIndexToRemove = 1; // Zero-based; this is "Page 2".

using (var reader = new PdfReader(originalPath))
using (var writer = new PdfWriter(editedPath))
using (var gr = writer.GetGraphics())
{
    for (var i = 0; i < reader.Frames.Count; i++)
    {
        if (i != pageIndexToRemove)
        {
            using (var pageContent = reader.Frames[i].GetContent())
            {
                writer.AddPage(pageContent.Width, pageContent.Height, pageContent.DpiX, pageContent.DpiY);
                gr.DrawContainer(pageContent, 0, 0);
            }
        }

        if (i == 0)
        {
            // Insert a brand-new page right after the first one.
            writer.AddPage(pageWidth, pageHeight, dpi, dpi);
            drawLabeledPage(gr, pageWidth, pageHeight, RgbColor.Gold, "Inserted page");
        }
    }
}

Output

Original.pdf

Download

EditedDocument.pdf

Download

For AI-assisted development: Download Graphics Mill Code Samples XML Catalog