Search code examples
vbscriptbatch-filemergepdftk

Merging PDF's in multiple locations with pdftk


I'm trying to merge multiple PDF's calling pdftk from a batch or VBS script file. The issue is that the PDF's are all located in subfolders within a common parent directory. Example: parent folder > subfolder1, subfolder2, subfolder3, where the script/BAT file is located in parent folder and each subfolder contains a PDF.

pdftk is called as follows: pdftk.exe *.pdf cat output OutputFile.pdf

This will merge only the PDF's in the current directory though, and not in the subfolders. Is there a way to do one of the following:

  1. Use the VBS/BAT file to copy all PDF's in the subfolders to another directory, and not error-out if some of the subfolders are empty
  2. Have pdftk look through the subfolders to select the PDF's to merge

Any help would be appreciated.


Solution

  • Try this:

    Wscript.Echo "begin."
    Dim pdffiles
    pdffiles=""
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
    Call ShowSubfolders (objSuperFolder)
    
    Dim objShell
    Set objShell = CreateObject("Shell.Application")
    objShell.ShellExecute "pdftk.exe", pdffiles & " output combined.pdf", "", "runas", 1
    
    Wscript.Echo "end."
    
    WScript.Quit 0
    
    Sub ShowSubFolders(fFolder)
        Set objFolder = objFSO.GetFolder(fFolder.Path)
        Set colFiles = objFolder.Files
        For Each objFile in colFiles
            If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
                pdffiles=pdffiles & " " & objFile.Name
            End If
        Next
    
        For Each Subfolder in fFolder.SubFolders
            ShowSubFolders(Subfolder)
        Next
    End Sub