Append two or more existing PDF files

Manipulate PDF
11/2/2011

Downloads

The following code sample shows how to append PDF files.

C# code sample

1 // create the target document 2 Document documentOut = new Document(); 3 4 // append 2 documents 5 using (FileStream file1 = new FileStream("1.pdf", FileMode.Open, FileAccess.Read)) 6 using (FileStream file2 = new FileStream("2.pdf", FileMode.Open, FileAccess.Read)) 7 { 8 Document documentIn = new Document(file1); 9 foreach (Page page in documentIn.Pages) 10 { 11 // append each page to the target document 12 // it is required to clone the page 13 documentOut.Pages.Add(page.Clone()); 14 } 15 16 documentIn = new Document(file2); 17 18 // append all pages to the target document 19 documentOut.Pages.AddRange(documentIn.Pages.CloneToArray()); 20 }

VB.NET code sample

1 ' create the target document 2 Dim documentOut As New Document() 3 4 ' append 2 documents 5 Using inFile1 As New FileStream("..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read) 6 Using inFile2 As New FileStream("..\..\..\inputDocuments\TheresMoreToAcrobat.pdf", FileMode.Open, FileAccess.Read) 7 Dim documentIn As Document 8 9 documentIn = New Document(inFile1) 10 For Each page As Page In documentIn.Pages 11 ' append page to the target document, we don't want to change the documentIn, so Clone the page. 12 documentOut.Pages.Add(page.Clone()) 13 Next 14 15 documentIn = New Document(inFile2) 16 17 ' append all pages to the target document 18 documentOut.Pages.AddRange(documentIn.Pages.CloneToArray()) 19 20 ' write the target document to disk 21 ' note that when the target document is written, the source streams 22 ' must still be open. for efficiency reasons, all source page content 23 ' is extracted as late as possible 24 Using outFile As New FileStream("..\..\append.pdf", FileMode.Create, FileAccess.Write) 25 documentOut.Write(outFile) 26 End Using 27 End Using 28 End Using