javascriptvbapdfacrobatacrobat-sdk

Adding custom pdf stamp to document from VBA


I've ran into a problem - I need to add a custom stamp (type of annotation) to a number of .pdf files. I can do it through Actions for Acrobat X Pro, but my clients do not have that license and they still need to do it. The list of files is stored in Excel spreadsheet, so ideally I am looking for a VBA solution. I have came up with the following code :

Option Explicit
Sub code1()
Dim app As Acrobat.AcroApp
Dim pdDoc As Acrobat.CAcroPDDoc
Dim page As Acrobat.CAcroPDPage
Dim recter(3) As Integer 'Array defining the rectangle of the stamp - in real code wil be calculated, simplified for ease of reading

Dim jso As Object
Dim annot As Object
Dim props As Object
Set pdDoc = Nothing
Set app = CreateObject("AcroExch.App")
Set pdDoc = CreateObject("AcroExch.PDDoc")

recter(0) = 100
recter(1) = 100
recter(2) = 350
recter(3) = 350

pdDoc.Open ("C:\Users\maxim_s\Desktop\Code_1\test1.pdf")

Set jso = pdDoc.GetJSObject

If Not jso Is Nothing Then

Set page = pdDoc.AcquirePage(0)

Set annot = jso.AddAnnot

Set props = annot.getprops
    props.page = 0
    props.Type = "Stamp"
    props.AP = "#eIXuM60ZXCv0sI-vxFqvlD" 'this line throws an error. The string is correct name of the stamp I want to add
    props.rect = recter
annot.setProps props

If pdDoc.Save(PDSaveFull, "C:\Users\maxim_s\Desktop\Code_1\test123.pdf") = False Then
    MsgBox "fail"
    pdDoc.Close
Else
    MsgBox "success"
    pdDoc.Close
End If
End If
End Sub

The problem is with the setprops and getprops procedures - it seems that at the moment when annotation is created (jso.AddAnnot) it does not posses the AP property, which is the name of the stamp I want to add. If I set the property Type= "Stamp" first and then try to specify the AP, the result is that one of the default stamps is added and it's AP is renamed to my custom stamps' AP. Also note, that if I launch acrobat and use the code below, the proper stamp is added:

this.addAnnot({page:0,type:"Stamp",rect:[100,100,350,350],AP:"#eIXuM60ZXCv0sI-vxFqvlD"})

If there is a way to execute this Javascript from VBA inside of the PDDoc object, that will solve the problem, but so far I have failed.


Solution

  • You can use "ExecuteThisJavaScript" from the AForm Api. Short example:

    Set AForm = CreateObject("AFormAut.App")

    AForm.Fields.ExecuteThisJavaScript "var x = this.numPages; app.alert(x);"

    It has the advantage that you don't need to translate the js examples into jso code. If you search for ExecuteThisJavaScript you will get some more and longer examples.

    Good luck, reinhard