How to insert a new PDF page to an existing PDF at a specified index

Spire.PDF offers a method of PdfDocument.MergeFiles(); to enable developers to merge PDF files easily and conveniently. This article will show you how to insert a new page from the first PDF into the second PDF file at a specified index by using the method of Pages.Insert(); offered by Spire.PDF.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.PDF.dll in the bin folder as the reference of Visual Studio.

Here comes to the steps of how to insert the page from the first PDF (sample.pdf) into the second PDF (test.pdf) at a specified index:

Step 1: Create the first PDF document and load file.

PdfDocument doc1 = new PdfDocument();
doc1.LoadFromFile("sample.pdf");

Step 2: Create the second PDF document and load file.

PdfDocument doc2 = new PdfDocument();
doc2.LoadFromFile("test.pdf");

Step 3: Get the first page and its size from the first PDF document.

PdfPageBase page = doc1.Pages[0];
SizeF size = page.Size;

Step 4: Inserts a new blank page with the specified size at the specified index into the second PDF.

PdfPageBase newPage = doc2.Pages.Insert(1, size);

Step 5: Copy the contents on the page into the second PDF.

newPage.Canvas.DrawTemplate(page.CreateTemplate(), new PointF(0, 0));

Step 6: Save the document to file.

doc2.SaveToFile("result.pdf");

Effective screenshot of insert a new PDF page to an existing PDF at a specified index:

How to insert a new PDF page to an existing PDF at a specified index

Full codes:

static void Main(string[] args)
{
    PdfDocument doc1 = new PdfDocument();
    doc1.LoadFromFile("sample.pdf");
    PdfDocument doc2 = new PdfDocument();
    doc2.LoadFromFile("test.pdf");

    PdfPageBase page = doc1.Pages[0];
    SizeF size = page.Size;

    PdfPageBase newPage = doc2.Pages.Insert(1, size);
    newPage.Canvas.DrawTemplate(page.CreateTemplate(), new PointF(0, 0));

    doc2.SaveToFile("result.pdf");

}