我正在尝试遍历一堆PDF,并且每个PDF都使用Acrobat API将其展平以访问PDF的JS对象。因为VBA没有代码可访问的堆栈跟踪,所以我有一个包装类AcroExchWrapper
,它包装每个Acrobat API函数以在函数失败时识别该函数,例如。
Public Sub ClosePDF()
On Error GoTo errHandler
'AcroDoc is created with CreateObject("AcroExch.PDDoc")
AcroDoc.Close
Exit Sub
errHandler:
Err.Raise Err.Number, "AcroExchWrapper.ClosePDF (" & Err.source & ")", Err.Description, Err.HelpFile, Err.HelpContext
End Sub
使用以下代码展平每个PDF:
Private Function flattenPDF(pdfPath As String, savePath As String, deleteOld As Boolean) As String
Dim pageCount As Integer
Dim jso As Object
Dim saveResult As Long
Dim openResult As Long
Dim creatingApp As String
On Error GoTo errHandler
creatingApp = ""
If deleteOld Then
If fso.FileExists(savePath) Then
fso.DeleteFile savePath
End If
End If
acroExch.ClosePDF
openResult = acroExch.OpenPDF(pdfPath)
If openResult = 0 Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to open PDF"
End If
DoEvents
Set jso = acroExch.GetJSObject
DoEvents
If jso Is Nothing Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to get JS object"
Else
pageCount = acroExch.GetNumPages
creatingApp = acroExch.GetInfo("Creator")
If pageCount <> -1 Then
flattenPages jso, 0, pageCount - 1
Else
flattenPages jso
End If
DoEvents
saveResult = acroExch.SavePDF(savePath)
If saveResult = 0 Then
Err.Raise "-1", "Flattener.flattenPDF", "unable to save PDF"
End If
acroExch.ClosePDF
If pdfPath <> savePath Then
loggerObj.addEntry pdfPath, savePath, "flattened", creatingApp
End If
End If
flattenPDF = savePath
Exit Function
errHandler:
loggerObj.addErrorEntryFromErrorObj pdfPath, "", "flattenPDF", Err, creatingApp
flattenPDF = ""
End Function
'wrapper for jso.flattenPages to allow for stack trace
Private Sub flattenPages(jso As Object, Optional startPage As Long = -1, Optional endPage As Long = -1)
On Error GoTo errHandler
If startPage = -1 Then
jso.flattenPages
Else
jso.flattenPages startPage, endPage
End If
Exit Sub
errHandler:
Err.Raise Err.Number, "flattenPages (" & Err.source & ")", Err.Description, Err.HelpFile, Err.HelpContext
End Sub
经过几千个文件后 - 每次运行脚本时数字都不同 - flattenPages()
会引发以下错误:
Automation error
The remote procedure call failed.
之后,对于所有剩余文件,当flattenPDF()
运行时,第一次调用acroExch.ClosePDF()
会引发此错误:
The remote server machine does not exist or is unavailable
我无法找到任何关于使用Acrobat API时出现这些错误的文档,无论是使用Javascript API(jso.flattenPages()
)还是使用IAC API(PDDoc.Close()
)。更神秘的是应用程序运行正常,直到它到达一些不同数量的文件,然后才开始抛出这些异常。
编辑:我将以下函数添加到AcroExchWrapper
以重置Acrobat,每100个文件执行一次:
Public Sub Reset()
ClosePDF
AcroApp.Exit
Set AcroApp = CreateObject("AcroExch.App")
Set AcroDoc = CreateObject("AcroExch.PDDoc")
Exit Sub
但是,仍然会抛出相同的例外情况。一旦处理了1500-2500个文件,这似乎就会发生。