Reputation: 1
I got stumped on the attached VBA code trying to pass a javascript string from VBA to Adobe. The javascript "jsobject.app.alert" message executes fine and pops up in Adobe, but the "jsobject.ExecuteJS jsScript" line does not execute and throws error message 438. ChatGPT has got me this far, but I can't seem to get past this error. I have the latest versions of Excel Pro and Adobe Acrobat DC installed and I have tried on both 32-bit and 64-bit machines. I have tested the jscript string in the Acrobat javascript console and it works fine. Any help would be appreciated. https://imgur.com/a/9lQQNAu
Sub AddTextToPDF()
Dim acroApp As Object
Dim acroAVDoc As Object
Dim acroPDDoc As Object
Dim jsObject As Object
Dim pdfPath As String
Dim jsScript As String
' Path to the PDF file
pdfPath = "E:\test.pdf"
' Check if the PDF file exists
If Dir(pdfPath) = "" Then
MsgBox "PDF file not found: " & pdfPath, vbExclamation, "Error"
Exit Sub
End If
' Create an Acrobat application object
On Error Resume Next
Set acroApp = CreateObject("AcroExch.App")
Set acroAVDoc = CreateObject("AcroExch.AVDoc")
On Error GoTo 0
If acroApp Is Nothing Or acroAVDoc Is Nothing Then
MsgBox "Adobe Acrobat is not installed or not available.", vbExclamation, "Error"
Exit Sub
End If
' Open the PDF file
If acroAVDoc.Open(pdfPath, "") Then
' Get the PDDoc object from the AVDoc
Set acroPDDoc = acroAVDoc.GetPDDoc
' Get the JavaScript object
Set jsObject = acroPDDoc.GetJSObject
'jsObject.app.alert "JavaScript is enabled and working!" ' this code is working
' JavaScript to add a text annotation
jsScript = "this.addAnnot({type: 'Text', page: 0, rect: [100, 500, 200, 550], contents: 'Finally, it works!'});"
' Execute the JavaScript
jsObject.ExecuteJS jsScript
' Save the changes to the PDF
acroPDDoc.Save &H1, pdfPath ' &H1 indicates incremental save
MsgBox "Text annotation added successfully!", vbInformation, "Success"
' Close the PDF
acroAVDoc.Close True
Else
MsgBox "Failed to open the PDF file.", vbExclamation, "Error"
End If
' Quit Acrobat
acroApp.Exit
Set acroPDDoc = Nothing
Set acroAVDoc = Nothing
Set acroApp = Nothing
Set jsObject = Nothing
End Sub
I have the latest versions of Excel Pro and Adobe Acrobat DC installed and I have tried on both 32-bit and 64-bit machines. I have tested the jscript string in the Acrobat javascript console and it works fine. Any help would be appreciated.
Upvotes: 0
Views: 71