Merge PDF

Generate PDF
11/16/2010

Downloads

It is possible to merge PDFs in .NET using TallPDF. In this code sample we will create a new PDF by stitching two existing PDF documents

C# merge PDF code sample

C# code sample

1 using System; 2 using System.IO; 3 4 using TallComponents.PDF.Layout; 5 using TallComponents.PDF.Layout.Paragraphs; 6 using TallComponents.PDF.Layout.Shapes; 7 8 namespace PageShapeSample 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 using ( FileStream fileA = new FileStream( 15 "SuccesStory_Gems.pdf", FileMode.Open, FileAccess.Read)) 16 using ( FileStream fileB = new FileStream( 17 "SuccesStory_Netco.pdf", FileMode.Open, FileAccess.Read)) 18 { 19 Document document = new Document(); 20 addPages(document, fileA); 21 addPages(document, fileB); 22 23 using (FileStream file = new FileStream( 24 "out.pdf", FileMode.Create, FileAccess.Write)) 25 { 26 document.Write(file); 27 } 28 } 29 } 30 31 static void addPages(Document document, FileStream file) 32 { 33 PageShape pageShape = new PageShape(file, 0, ""); 34 int n = pageShape.PageCount; 35 for (int i = 0; i < n; i++) 36 { 37 pageShape.PageIndex = i; 38 Section section = new Section(); 39 section.StartOnNewPage = true; 40 section.PageSize = new PageSize( 41 pageShape.Width, pageShape.Height); 42 section.Margin.Left = 0; 43 section.Margin.Right = 0; 44 section.Margin.Top = 0; 45 section.Margin.Bottom = 0; 46 document.Sections.Add(section); 47 Drawing drawing = new Drawing( 48 pageShape.Width, pageShape.Height); 49 drawing.Shapes.Add(pageShape.Clone()); 50 section.Paragraphs.Add(drawing); 51 } 52 } 53 } 54 }

VB.NET code sample

1 Sub Main() 2 ' Find all pdf documents in input folder. 3 Dim directoryInfo As New DirectoryInfo("..\..\../inputdocuments") 4 Dim allPDFs As FileInfo() = directoryInfo.GetFiles("*.pdf") 5 6 ' Create a document for the merged result. 7 Dim mergedDocument As New Document() 8 9 ' Keep a list of input streams to close when done. 10 Dim streams As New List(Of FileStream)() 11 For Each fileInfo As FileInfo In allPDFs 12 ' Open input stream and add to list of streams. 13 Dim stream As New FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read) 14 streams.Add(stream) 15 16 ' Open input document. 17 Dim document As New Document(stream) 18 19 ' Append all pages to target document. 20 ' The target document holds references to data in the input stream. 21 ' For efficiency it does not copy this data so the input streams 22 ' should not be closed before the merged document is saved. 23 mergedDocument.Pages.AddRange(document.Pages.CloneToArray()) 24 Next 25 26 ' Save merged document. 27 Using output As New FileStream("..\..\output.pdf", FileMode.Create, FileAccess.Write) 28 mergedDocument.Write(output) 29 End Using 30 31 ' Close all input streams. 32 For Each stream As FileStream In streams 33 stream.Close() 34 Next 35 36 End Sub