Fusionar PDF juntos usando VBA
Hace un tiempo, compartí un ejemplo de cómo podríamos usar el poder del control moderno del navegador web (MWBC) para fusionar y dividir los archivos PDF.
Continuar leyendo
Con cualquiera de estos enfoques, incluso podría automatizar completamente el proceso. Dicho esto, también sé que a muchos no les gusta el MWBC y prefieren soluciones más tradicionales, por lo que pensé que los tocaría muy brevemente en esta publicación, ya que solo estaba respondiendo una pregunta relacionada con este tema en un foro de discusión.
Por lo tanto, hay algunos enfoques posibles que se pueden emplear para trabajar con PDF. Estos incluyen principalmente cosas como:
- Controles activos
- Aplicaciones de terceros
- dlls
Aplicaciones de terceros
Adobe Acrobat
Creo que todos son conscientes de que puede usar la automatización de VBA para automatizar Acrobat para realizar cualquier cantidad de operaciones, incluida la fusión de archivos juntos. Sin embargo, esto no es posible a menos que haya comprado una licencia profesional. Google y puede encontrar fácilmente toneladas de muestras de código.
Más allá del acrobat
Entonces, más allá de Acrobat, hay una serie de herramientas alternativas que se pueden usar. Algunos son gratis, otros no.
Por ejemplo, podrías usar pdftk y una sola línea de código VBA para fusionar archivos PDF juntos. Aquí hay un ejemplo del código VBA que fusionaría 2 PDF usando 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
Con los años, varias personas han recomendado Pdfsam.
He usado/automatizado anteriormente Pdfcreator.
Usando una DLL
Albert Kallal ha proporcionado amablemente un ejemplo de uso de una DLL para fusionar archivos. Puedes ver su artículo sobre el tema en: Fusionar documentos PDF en MS-Access.
Microsoft Word
Sí, lo leíste bien. Dado que Word puede abrir PDFS, puede automatizarlo para fusionar PDFS. A continuación se muestra un ejemplo rápido de cómo se vería esa automatización de palabras.
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
Sin embargo, esta no sería mi primera opción, ya que puede ser lenta y la palabra no siempre representa los PDF, ya que originalmente eran.