Merge Selected Pages from Multiple PDF Files into One in C#/VB.NET

Using Spire.PDF, you can not only merge multiple PDF files into a single file, but also select specific pages from the source files and combine them in one PDF document. The following code snippets demonstrate the same.

Step 1: Get the PDF file paths and store in a string array.

string[] files = { "Sample1.pdf", "Sample2.pdf", "Sample3.pdf" };

Step 2: Load each PDF document to an object of PdfDocument and store all these objects in PdfDocument array.

         PdfDocument[] docs = new PdfDocument[files.Length];

        for (int i = 0; i < files.Length; i++)
        {
            docs[i] = new PdfDocument(files[i]);
        }

Step 3: Create an instance of PdfDocument class.

PdfDocument doc = new PdfDocument();

Step 4: Call InsertPage(PdfDocument doc, int pageIndex) method and InertPageRange(PdfDocument doc, int startIndex, int endIndex) method to insert selected pages to the new PDF document.

       doc.InsertPage(docs[0], 0);
       doc.InsertPage(docs[1], 1);
       doc.InsertPageRange(docs[2], 2, 5);

Step 5: Save and launch the file.

       doc.SaveToFile("Result.pdf");
       Process.Start("Result.pdf");

Screen Shot of Effect:

Merge Selected Pages from Multiple PDF Files into One in C#, VB.NET

The six pages in the result file are extracted from three sample PDF files.

Full Code:

[C#]
using Spire.Pdf;
using System.Diagnostics;

namespace MergeSelectedPages
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = { "Sample1.pdf", "Sample2.pdf", "Sample3.pdf" };
            PdfDocument[] docs = new PdfDocument[files.Length];

            //open pdf documents
            for (int i = 0; i < files.Length; i++)
            {
                docs[i] = new PdfDocument(files[i]);
            }

            //create a new pdf document and insert selected pages
            PdfDocument doc = new PdfDocument();
            doc.InsertPage(docs[0], 0);
            doc.InsertPage(docs[1], 1);
            doc.InsertPageRange(docs[2], 2, 5);


            doc.SaveToFile("Result.pdf");
            Process.Start("Result.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports System.Diagnostics

Namespace MergeSelectedPages
	Class Program
		Private Shared Sub Main(args As String())
			Dim files As String() = {"Sample1.pdf", "Sample2.pdf", "Sample3.pdf"}
Dim docs As PdfDocument() = New PdfDocument(files.Length - 1) {}

'open pdf documents
For i As Integer = 0 To files.Length - 1
	docs(i) = New PdfDocument(files(i))
Next

'create a new pdf document and insert selected pages
Dim doc As New PdfDocument()
doc.InsertPage(docs(0), 0)
doc.InsertPage(docs(1), 1)
doc.InsertPageRange(docs(2), 2, 5)

doc.SaveToFile("Result.pdf")
Process.Start("Result.pdf")
		End Sub
	End Class
End Namespace