Merge 2 or more PDF documents into one using VB.NET

Posted on 2012-09-04
Last Modified: 2012-09-12
I am using the attached code that I found

Open in new window

on one of the tech sites to Merge 2 or more PDF documents. But the result document is getting corrupted for some reason. My source PDF files and fine. I have tested them. But once this Merge function is called, the combined PDF is getting corrupted. Please advise.
Question by:Angel02
    LVL 2

    Expert Comment

    Maybe you can try this:

    Regards Kristof

    Author Comment

    I tried to convert this code into VB.NET using my regular link

    But it does not successfully convert. Can you please provide VB.NET code?
    LVL 2

    Expert Comment


    Author Comment

    Is spire.PDF free to download? It looks like it needs to be purchased.
    I was looking for code using itextsharp.
    LVL 2

    Assisted Solution

    LVL 26

    Expert Comment

    by:Alan Warren
    Getting a few issues with this line:
    While (i < numPagesCurrentPDF) i += 1 If (pdfWriter IsNot Nothing) Then Dim page As PdfImportedPage = pdfWriter.GetImportedPage(reader, i) pdfWriter.AddPage(page) End If End While Dim formContent As PRAcroForm = reader.AcroForm If (formContent IsNot Nothing And pdfWriter IsNot Nothing) Then pdfWriter.CopyAcroForm(reader) FileNum += 1 If (master.Count > 0 And pdfWriter IsNot Nothing) Then pdfWriter.Outlines = master

    Open in new window

            pdfWriter.Outlines = master
            ' missing end if here

    Open in new window

    LVL 26

    Accepted Solution

    Hi Angel02,
    Got it working on my localhost, not tried it on production yet.
    Had to modify the code a bit, anyhow, take a look:
    <%@ Page Language="VB" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <script runat="server">
      Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        'Destination file name
        Dim TimeStamp As String = DateAndTime.Now.ToString
        TimeStamp = TimeStamp.Replace("/", "")
        TimeStamp = TimeStamp.Replace(" ", "")
        TimeStamp = TimeStamp.Replace(":", "")
        Dim destinationFile As String = Server.MapPath("~/the-files-folder/") & TimeStamp & ".pdf"
        'Source file name 1
        Dim SourceFile1 As String = Server.MapPath("~/the-files-folder/Document1.pdf")
        'Source file name 2
        Dim SourceFile2 As String = Server.MapPath("~/the-files-folder/Document2.pdf")
        Dim sourceFiles() As String = {SourceFile1, SourceFile2}
        Dim ret As Boolean = False
        ret = pdfmerge.MergeFiles(destinationFile, sourceFiles)
        If ret = True Then
          Dim s As String = "<iframe id='pdf-merge-preview' frameborder='0' height='800px' src='./the-files-folder/" & TimeStamp & ".pdf' width='800px'></iframe>"
        End If
      End Sub
    <html xmlns="">
    <head runat="server">
        <form id="form1" runat="server">

    Open in new window

    And the Class:
    Imports Microsoft.VisualBasic
    Imports System
    Imports System.IO
    Imports iTextSharp.text
    Imports iTextSharp.text.pdf
    Public Class pdfmerge
      Public Shared Function MergeFiles(ByVal destinationFile As String, ByVal sourceFiles() As String) As Boolean
        Dim pageOffset As Integer = 0
        Dim master As ArrayList = New ArrayList()
        Dim FileNum As Integer = 0
        Dim outputPDFDocument As Document = Nothing
        Dim pdfWriter As PdfCopy = Nothing
        Dim blResult As Boolean = False
        Dim reader As PdfReader = Nothing
        Dim numPagesCurrentPDF As Integer = 0
        Dim bookmarks As ArrayList = New ArrayList()
        Dim page As PdfImportedPage = Nothing
        Dim formContent As PRAcroForm = Nothing
        Dim SourceFilesCount As Integer = 0
        Dim PagesToAdd As Integer = 0
        For SourceFilesCount = 0 To sourceFiles.Length - 1
          reader = New PdfReader(sourceFiles(SourceFilesCount))
          numPagesCurrentPDF = reader.NumberOfPages
          bookmarks = SimpleBookmark.GetBookmark(reader)
          If (bookmarks IsNot Nothing) Then
            If (pageOffset <> 0) Then SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, Nothing)
          End If
          pageOffset += numPagesCurrentPDF
          If (SourceFilesCount = 0) Then
            ' step 1: creation of a document-object
            outputPDFDocument = New Document(reader.GetPageSizeWithRotation(1))
            ' step 2: we create a writer that listens to the document
            ' Encountered Exception: System.UnauthorizedAccessException was unhandled by user code
            ' Gave iis_iusrs full control of the ~/the-files-folder/ folder, bit over the top, but sure to suffice
            ' second time though the loop
            ' encountered error: The process cannot access the file 'C:\inetpub\wwwroot\session-test\the-files-folder\output.pdf' because it is being used by another process.
            ' Modified script to only open the pdfWriter the first time through the loop
            If pdfWriter Is Nothing Then
              pdfWriter = New PdfCopy(outputPDFDocument, New FileStream(destinationFile, FileMode.Create))
              ' step 3: we open the output document
            End If
          End If
          ' step 4: we add pages to the output file
          For PagesToAdd = 1 To numPagesCurrentPDF
            If (pdfWriter IsNot Nothing) Then
              page = pdfWriter.GetImportedPage(reader, PagesToAdd)
            End If
          formContent = reader.AcroForm
          If (formContent IsNot Nothing And pdfWriter IsNot Nothing) Then
            SourceFilesCount += 1
            If (master.Count > 0 And pdfWriter IsNot Nothing) Then
              ' huh?
            End If
            pdfWriter.Outlines = master
          End If
        ' step 5: we close the document
        If (outputPDFDocument IsNot Nothing) Then
          blResult = True
        End If
        Return blResult
      End Function
      Private Function CountPageNo(ByVal strFileName As String) As Integer
        ' we create a reader for a certain document
        Dim reader As PdfReader = New PdfReader(strFileName)
        ' we retrieve the total number of pages
        Return reader.NumberOfPages
      End Function
    End Class

    Open in new window


    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Suggested Solutions

    The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now