问题
I'm trying to call the Acrobat Javascript API from VBA to flatten all annotations in a document, using the following code:
Sub flattenPDF()
Dim AcroApp As Acrobat.AcroApp
Dim AcroDoc As Acrobat.AcroPDDoc
Dim jso As Object
Dim path As String
path = "C:\Users\userID\Desktop\thisfile.pdf"
Set AcroApp = CreateObject("AcroExch.App")
Set AcroDoc = CreateObject("AcroExch.PDDoc")
AcroDoc.Open path
Set jso = AcroDoc.GetJSObject
jso.flattenPages
AcroDoc.Save PDSaveFull, path
AcroDoc.Close
AcroApp.Exit
End Sub
The code runs successfully, but then when I open the PDF, all the annotations can still be edited--the flattening should have made them read-only, right?
Edit: I changed the first parameter of AcroDoc.Save
from "1" to "PDSaveFull", and now the annotations are flattened if I run the script twice. Why don't they flatten the first time?
Update:
I modified the script to get the page count and pass it to flattenPages()
per joelgaraci's suggestion, as well as passing in the PDF path to the function:
Sub flattenPDF(pdfPath As String)
Dim AcroApp As Acrobat.AcroApp
Dim AcroDoc As Acrobat.AcroPDDoc
Dim pageCount As Integer
Dim jso As Object
Set AcroApp = CreateObject("AcroExch.App")
Set AcroDoc = CreateObject("AcroExch.PDDoc")
AcroDoc.Open pdfPath
pageCount = AcroDoc.GetNumPages
Set jso = AcroDoc.GetJSObject
jso.flattenPages 0, pageCount - 1
AcroDoc.Save PDSaveFull, pdfPath
AcroDoc.Close
AcroApp.Exit
End Sub
But this got the same result: the annotations only flatten after I run the script twice.
回答1:
Just thought I would add my solution in case it helps someone... I wanted to flatten all PDF files in a folder and this seems to do the trick.
Sub Flatten_Folder()
Dim MyFile As String
Mypath = InputBox("Enter the path to the folder where the PDF files are
Located **MUST END WITH \**")
MyFile = Dir(Mypath)
Do While MyFile <> ""
If MyFile Like "*.PDF" Or MyFile Like "*.pdf" Then
Fullpath = Mypath & MyFile
Set App = CreateObject("AcroExch.app")
Set avdoc = CreateObject("AcroExch.AVDoc")
Set pdDoc = CreateObject("AcroExch.PDDoc")
Set AForm = CreateObject("AFormAut.App")
pdDoc.Open (Fullpath)
Set avdoc = pdDoc.OpenAVDoc(Fullpath)
js = "this.flattenPages();"
'//execute the js code
AForm.Fields.ExecuteThisJavaScript js
Set pdDoc = avdoc.GetPDDoc
pdDoc.Save PDSaveFull, Fullpath
pdDoc.Close
Set AForm = Nothing
Set avdoc = Nothing
Set App = Nothing
End If
MyFile = Dir
Loop
End Sub
On running the macro you get a message box prompt to paste the folder path in. Also this method seems to avoid the issue the OP was having.
来源:https://stackoverflow.com/questions/41371693/trying-to-flatten-pdf-using-flattenpages-but-nothing-happens