Merge Multiple PDFs in C# with Spire.PDF
In practical project development, we often encounter requirements to merge multiple PDF files into a single document or extract specific pages from multiple PDFs to form a new PDF. This article will show you how to use the Spire.PDF for .NET library to implement two functions:
- Merge multiple complete PDF documents
- Merge specified pages from multiple PDFs
1. Install Spire.PDF
Before getting started, you need to install Spire.PDF for .NET. You can install it via NuGet:
Install-Package Spire.PDF
Or search for Spire.PDF in Visual Studio's "Manage NuGet Packages" and install it.
2. Merge Multiple PDF Documents (Basic Scenario)
This is suitable for concatenating multiple PDF files in sequence into one document.
using Spire.Pdf;
namespace MergePDFs
{
class Program
{
static void Main(string[] args)
{
// PDF documents to be merged
string[] files = new string[] {"Example1.pdf", "Example2.pdf", "Example3.pdf"};
// Merge PDF documents
PdfDocumentBase pdf = PdfDocument.MergeFiles(files);
// Save
pdf.Save("MergedPDF.pdf", FileFormat.PDF);
}
}
}
✅ Advantages: Simple code, stable execution, suitable for batch processing.
⚠️ Note: Ensure file paths exist and are readable.
3. Merge Specified Pages (Advanced Scenario)
In practical work, you often need to merge specific pages from different PDFs (e.g., page 2 of a contract + page 3 of an approval form).
using Spire.Pdf;
namespace MergePDFs
{
class Program
{
static void Main(string[] args)
{
// PDF documents to be merged
string[] files = new string[] {"Example1.pdf", "Example2.pdf"};
// Load each PDF document
PdfDocument[] pdfs = new PdfDocument[files.Length];
for (int i = 0; i < files.Length; i++)
{
pdfs[i] = new PdfDocument(files[i]);
}
// Create a new PdfDocument object
PdfDocument newPDF = new PdfDocument();
// Merge pages 2 and 3 from the first document and page 1 from the second document
newPDF.InsertPageRange(pdfs[0], 1, 2);
newPDF.InsertPage(pdfs[1], 0);
// Save the new PDF file
newPDF.SaveToFile("ExtractedPDFPages.pdf");
}
}
}
📌 Applicable scenarios: Cross-document content integration, report page reorganization.
4. Notes
- Page Indexing: Spire.PDF uses 0-based page indexing, unlike some software that starts from 1.
- Large File Handling: When merging many or large PDFs, use using statements to ensure proper resource release.
- Supported Formats: Spire.PDF supports PDF 1.0 ~ PDF 1.7 formats, as well as some PDF/A formats.
With the above code, you can implement basic PDF merging in C# and also flexibly control page order and skip specific pages to meet complex business scenarios.