Pdf Merge | |
Select.Pdf can be used to merge several existing pdf documents into a single pdf document.
To achive this task, individual pdf files need to be loaded into PdfDocument objects. The following sample code shows how to load an existing file from the disk:
Another important method that will be used by the pdf merge feature is Append(PdfDocument) of the PdfDocument object. Using this method, a pdf document can be appended to another pdf document:
This sample code shows how to use SelectPdf Library for .NET to merge 2 different pdf documents into a new pdf document.
// the 2 initial files string file1 = Server.MapPath("~/files/doc1.pdf"); string file2 = Server.MapPath("~/files/doc2.pdf"); // load the 2 pdf documents PdfDocument doc1 = new PdfDocument(file1); PdfDocument doc2 = new PdfDocument(file2); // create a new pdf document PdfDocument doc = new PdfDocument(); // add the pages of those 2 documents to the new document doc.Append(doc1); doc.Append(doc2); // save pdf document doc.Save(Response, false, "Sample.pdf"); // close pdf document doc.Close(); // close the original pdf documents doc1.Close(); doc2.Close();
PdfMergeManager is an alternative merge API that accepts inputs in different shapes (file path, stream, byte array, or PdfDocument), supports password-protected inputs directly, and can target a specific PDF standard at save time (PDF/A, PDF/X, PDF/SiqQ) via its constructor. Each input shape has a password-protected variant:
Append(string fileName) / Append(string fileName, string password)
Append(Stream stream) / Append(Stream stream, string password)
Append(byte[] fileBytes) / Append(byte[] fileBytes, string password)
Append(PdfDocument document) / Append(PdfDocument document, string password)
The parameterless constructor produces a Full PDF (no compliance constraints). Passing a PdfStandard value to the other constructor requests a specific profile - for example PdfStandard.PdfA for archival output or PdfStandard.PdfX for print-oriented compliance.
// merge a file, a stream and a password-protected file, targeting PDF/A using (FileStream fs = File.OpenRead("second.pdf")) { PdfMergeManager merger = new PdfMergeManager(PdfStandard.PdfA); merger.Append("first.pdf"); merger.Append(fs); merger.Append("third-protected.pdf", "userpwd"); merger.Save("combined.pdf"); merger.Close(); }