Append multiple PDF documents

Append multiple PDF documents

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.

   static void Main(string[] args)
   {
      string inputFolder = @"inputDocuments\";
      DirectoryInfo directoryInfo = new DirectoryInfo(inputFolder);
      Document documentOut = new Document();

      foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.pdf"))
         Append(documentOut, fileInfo.FullName);

      using (FileStream outFile = new FileStream("appendMultiple.pdf", FileMode.Create,
                                      FileAccess.Write))
      {
         documentOut.Write(outFile);
      }
   }

   static void Append(TallComponents.PDF.Layout.Document document, String fileName)
   {
      using (FileStream fileIn = new FileStream(fileName,FileMode.Open,FileAccess.Read))
      {
         
         PageShape pageShape = new PageShape(fileIn, 0, "");
         int n = pageShape.PageCount;

         for (int i = 0; i < n; i++)
         {
            pageShape = pageShape.Clone() as PageShape;
            pageShape.PageIndex = i;
            Section section = new Section();
            section.StartOnNewPage = true;
            section.PageSize = new PageSize(pageShape.Width, pageShape.Height);
            section.Margin.Left = 0;
            section.Margin.Right = 0;
            section.Margin.Top = 0;
            section.Margin.Bottom = 0;
            document.Sections.Add(section);

            Drawing drawing = new Drawing(pageShape.Width, pageShape.Height);
            drawing.Shapes.Add(pageShape);
            section.Paragraphs.Add(drawing);
         }
      }
   }
Shared Sub Main()
    Dim inputFolder As String = "..\..\..\inputDocuments\"
    Dim directoryInfo As New DirectoryInfo(inputFolder)

    ' Create the result document, and a list for keeping track of the input files.
    Dim documentOut As New Document()
    Dim inputFiles As New LinkedList(Of FileStream)

    For Each fileInfo As FileInfo In directoryInfo.GetFiles("*.pdf")
        Append(documentOut, fileInfo.FullName, inputFiles)
    Next

    ' Write the result. During writing, access to the input files will be needed, so these should not
    ' yet be closed.
    Using outFile As New FileStream("..\..\appendMultiple.pdf", FileMode.Create, FileAccess.Write)
        documentOut.Write(outFile)
    End Using

    For Each inputFile As FileStream In inputFiles
        inputFile.Close()
    Next

End Sub

Private Shared Sub Append(ByVal documentOut As Document, ByVal fileName As String, inputFiles As LinkedList(Of FileStream))
    ' append document
    Dim inFile As New FileStream(fileName, FileMode.Open, FileAccess.Read)
    Dim documentIn As New Document(inFile)

    ' append all pages to the target document
    documentOut.Pages.AddRange(documentIn.Pages.CloneToArray())
    inputFiles.AddLast(inFile)
End Sub