• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Merge and save write protected PDF from VBA

New Here ,
Aug 16, 2024 Aug 16, 2024

Copy link to clipboard

Copied

Hi

We use a VBA macro to populate and save Excel sheets into PDF files. In the last step we use Acrobat to merge all the individual PDF into one final PDF with the code below. This work very well but we would like the final PDF to be generated with password protection for editing (not for viewing). Is it possible to add this to the code?

 

Sub MergePDFs(FilesPath As String, FileNames As String, ResultName As String)
' Reference required: "VBE - Tools - References - Acrobat"

  Dim a As Variant, i As Long, n As Long, ni As Long, p As String
  Dim AcroApp As New Acrobat.AcroApp, PartDocs() As Acrobat.CAcroPDDoc

  If Right(FilesPath, 1) = "\" Then p = FilesPath Else p = FilesPath & "\"
  a = Split(FileNames, ",")
  ReDim PartDocs(0 To UBound(a))

  On Error GoTo exit_
  If Len(Dir(p & ResultName)) Then Kill p & ResultName
  For i = 0 To UBound(a)
    ' Check PDF file presence
    If Dir(p & Trim(a(i))) = "" Then
      MsgBox "File not found" & vbLf & p & a(i), vbExclamation, "Canceled"
      Exit For
    End If
    ' Open PDF document
    Set PartDocs(i) = CreateObject("AcroExch.PDDoc")
    PartDocs(i).Open p & Trim(a(i))
    If i Then
      ' Merge PDF to PartDocs(0) document
      ni = PartDocs(i).GetNumPages()
      If Not PartDocs(0).InsertPages(n - 1, PartDocs(i), 0, ni, True) Then
        MsgBox "Cannot insert pages of" & vbLf & p & a(i), vbExclamation, "Canceled"
      End If
      ' Calc the number of pages in the merged document
      n = n + ni
      ' Release the memory
      PartDocs(i).Close
      Set PartDocs(i) = Nothing
    Else
      ' Calc the number of pages in PartDocs(0) document
      n = PartDocs(0).GetNumPages()
    End If
  Next

  If i > UBound(a) Then
    ' Save the merged document to ResultName
    If Not PartDocs(0).Save(PDSaveFull, p & ResultName) Then
      MsgBox "Cannot save the resulting document" & vbLf & p & ResultName, vbExclamation, "Canceled"
    End If
  End If

exit_:

  ' Inform about error/success
  If Err Then
    MsgBox Err.Description, vbCritical, "Error #" & Err.Number
  End If

  ' Release the memory
  If Not PartDocs(0) Is Nothing Then PartDocs(0).Close
  Set PartDocs(0) = Nothing

  ' Quit Acrobat application
  AcroApp.Exit
  Set AcroApp = Nothing
End Sub

 

TOPICS
Acrobat SDK and JavaScript , Mac , Windows

Views

42

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
no replies

Have something to add?

Join the conversation