0

我正在尝试遍历一堆 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 个文件,这似乎就会发生。

4

0 回答 0