Merging PDFs Together Using VBA

A while back, I shared an example of how we could use the power of Modern Web Browser Control (MWBC) to Merge and Split PDF files.

With either of these approaches, you could even fully automate the process. That said, I also know that many do not like the MWBC and prefer more traditional solutions and so I thought I’d very briefly touch upon them in this post as I was just answering a question related to this issue in a discussion forum.
 
So, there are a few possible approach that can be employed to work with PDFs.  These primarily include things like:

  • ActiveX Controls
  • 3rd Party Applications
  • dlls

 

3rd Party Applications

Adobe Acrobat

I think everyone is aware that you can use VBA automation to automate Acrobat to perform any number of operations including merging files together. This however is not possible unless you’ve bought a pro license. Google and you can easily find tons of code samples.

Beyond Acrobat

So beyond Acrobat, there are a number of alternative tools that can be used. Some are free, some are not.

For instance, you could use pdftk and a single line of VBA code to merge pdf files together. Here’s an example of the VBA code that would merge 2 PDFs using pdftk:

Function PDFTK_MergePDFs(ByVal sFirstPDF As String, _
                         ByVal sSecondPDF As String, _
                         ByVal sOutputPDF As String) As Boolean
    Dim sCommand              As String
    Dim sOutputDir            As String

    On Error GoTo Error_Handler

    ' Check if input files exist
    If Dir(sFirstPDF) = "" Then
        MsgBox "The first PDF file does not exist: " & sFirstPDF, vbExclamation
        Exit Function
    End If

    If Dir(sSecondPDF) = "" Then
        MsgBox "The second PDF file does not exist: " & sSecondPDF, vbExclamation
        Exit Function
    End If

    ' Check if output folder exist
    sOutputDir = Left(sOutputPDF, InStrRev(sOutputPDF, "\") - 1)
    If Dir(sOutputDir, vbDirectory) = "" Then
        MsgBox "The output directory does not exist: " & sOutputDir, vbExclamation
        Exit Function
    End If
    
    ' We could check and see if the output file already exists and propmt about overwriting it???

    ' Create the PDFtk command
    sCommand = "pdftk " & sFirstPDF & " " & sSecondPDF & " cat output " & sOutputPDF
    Shell sCommand, vbNormalFocus ' Run the shell command to merge the PDFs

    ' Display a message???
    'MsgBox "PDFs merged successfully! Saved as: " & sOutputPDF, vbInformation
    
    ' Could validate the file was created???
    
    PDFTK_MergePDFs = True

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: PDFTK_MergePDFs" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Over the years, several people have recommended PDFsam.

I’ve previously used/automated PDFCreator.
 

Using a dll

Albert Kallal has kindly provided an example of using a dll to merge files. You can see his article on the subject at: Merge PDF documents in MS-Access.
 

Microsoft Word

Yes, you read that right. Since Word can open PDFs, you can automate it to merge PDFs. Below is a quick example of how such Word automation might look.

Function Word_MergePDFs(ByVal sFirstPDF As String, _
                        ByVal sSecondPDF As String, _
                        ByVal sOutputPDF As String) As Boolean
    Dim oWord                 As Object
    Dim oDoc                  As Object
    Dim oSelection            As Object
    Dim sOutputDir            As String
    Const wdPageBreak = 7
    Const wdFormatPDF = 17

    On Error GoTo Error_Handler

    ' Check if input files exist
    If Dir(sFirstPDF) = "" Then
        MsgBox "The first PDF file does not exist: " & sFirstPDF, vbExclamation
        Exit Function
    End If

    If Dir(sSecondPDF) = "" Then
        MsgBox "The second PDF file does not exist: " & sSecondPDF, vbExclamation
        Exit Function
    End If

    sOutputDir = Left(sOutputPDF, InStrRev(sOutputPDF, "\") - 1)
    If Dir(sOutputDir, vbDirectory) = "" Then
        MsgBox "The output directory does not exist: " & sOutputDir, vbExclamation
        Exit Function
    End If
    
    ' We could check and see if the output file already exists and propmt about overwriting it???

    Set oWord = CreateObject("Word.Application")    ' Create Word application object
    Set oDoc = oWord.Documents.Add    ' Create a new Document

    ' Get the oSelection object
    Set oSelection = oWord.selection
    With oSelection
        .InsertFile Filename:=sFirstPDF   ' Insert the first PDF
        .InsertFile Filename:=sSecondPDF  ' Insert the second PDF
    End With

    With oDoc
        .SaveAs2 Filename:=sOutputPDF, FileFormat:=wdFormatPDF    ' Save the Document as PDF
        .Close SaveChanges:=False    ' Close the Document
    End With

    oWord.Quit    ' Quit Word application

    ' Display a message???
    'MsgBox "PDFs merged successfully! Saved as: " & sOutputPDF, vbInformation
    
    ' Could validate the file was created???
    
    Word_MergePDFs = True

Error_Handler_Exit:
    On Error Resume Next
    Set oSelection = Nothing
    Set oDoc = Nothing
    Set oWord = Nothing
    Exit Function

Error_Handler:
    oWord.Visible = True    'Make Word visible to avoid hidden processes in the background
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: Word_MergePDFs" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

However, this wouldn’t be my first choice as it can be slow and Word doesn’t always render the PDFs as they were originally and the resulting PDF are often much larger in file size than they are when using alternative approaches.

One response on “Merging PDFs Together Using VBA

  1. Robert Simard

    Bonjour Daniel,
    Merci pour tes articles plus intéressants les uns que les autres !
    Je me permet de partager un petit utilitaire que j’ai créer pour combiner des PDF avec PDFTK, et j’ai ajouté certaines fonctionnalités comme le Word to PDF, Excel to PDF, JPG to PDF ainsi que le Drag & Drop

    http://profab.ca/files/MergePDF.zip

    Merci!