Append multiple PDF documents

Generate PDF, Manipulate PDF, Shapes
4/13/2011

Downloads

Append multiple PDF documents

This code sample illustrates to loop through a given folder and append each PDF documents found in that folder into a new generated PDF document.

C# code sample

1 static void Main(string[] args) 2 { 3 string inputFolder = @"inputDocuments\"; 4 DirectoryInfo directoryInfo = new DirectoryInfo(inputFolder); 5 Document documentOut = new Document(); 6 7 foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.pdf")) 8 Append(documentOut, fileInfo.FullName); 9 10 using (FileStream outFile = new FileStream("appendMultiple.pdf", FileMode.Create, 11 FileAccess.Write)) 12 { 13 documentOut.Write(outFile); 14 } 15 } 16 17 static void Append(TallComponents.PDF.Layout.Document document, String fileName) 18 { 19 using (FileStream fileIn = new FileStream(fileName,FileMode.Open,FileAccess.Read)) 20 { 21 22 PageShape pageShape = new PageShape(fileIn, 0, ""); 23 int n = pageShape.PageCount; 24 25 for (int i = 0; i < n; i++) 26 { 27 pageShape = pageShape.Clone() as PageShape; 28 pageShape.PageIndex = i; 29 Section section = new Section(); 30 section.StartOnNewPage = true; 31 section.PageSize = new PageSize(pageShape.Width, pageShape.Height); 32 section.Margin.Left = 0; 33 section.Margin.Right = 0; 34 section.Margin.Top = 0; 35 section.Margin.Bottom = 0; 36 document.Sections.Add(section); 37 38 Drawing drawing = new Drawing(pageShape.Width, pageShape.Height); 39 drawing.Shapes.Add(pageShape); 40 section.Paragraphs.Add(drawing); 41 } 42 } 43 }

VB.NET code sample

1 Shared Sub Main() 2 Dim inputFolder As String = "..\..\..\inputDocuments\" 3 Dim directoryInfo As New DirectoryInfo(inputFolder) 4 5 ' Create the result document, and a list for keeping track of the input files. 6 Dim documentOut As New Document() 7 Dim inputFiles As New LinkedList(Of FileStream) 8 9 For Each fileInfo As FileInfo In directoryInfo.GetFiles("*.pdf") 10 Append(documentOut, fileInfo.FullName, inputFiles) 11 Next 12 13 ' Write the result. During writing, access to the input files will be needed, so these should not 14 ' yet be closed. 15 Using outFile As New FileStream("..\..\appendMultiple.pdf", FileMode.Create, FileAccess.Write) 16 documentOut.Write(outFile) 17 End Using 18 19 For Each inputFile As FileStream In inputFiles 20 inputFile.Close() 21 Next 22 23 End Sub 24 25 Private Shared Sub Append(ByVal documentOut As Document, ByVal fileName As String, inputFiles As LinkedList(Of FileStream)) 26 ' append document 27 Dim inFile As New FileStream(fileName, FileMode.Open, FileAccess.Read) 28 Dim documentIn As New Document(inFile) 29 30 ' append all pages to the target document 31 documentOut.Pages.AddRange(documentIn.Pages.CloneToArray()) 32 inputFiles.AddLast(inFile) 33 End Sub