系统:

Python 3.6
Windows 10


目标:
使用Adobe Acrobat API使用“另存为”功能将pdf保存为jpeg。
注意:出于我的目的,我不能使用Wand或其他软件包。

资源:
Adobe_API_Documentation
Implementation_Example 1
Error_Handling_Issue
VBA_Example

当前代码:

import winerror
import win32com
from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT

ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)

my_dir = r"path\\to\\example\\"
my_pdf = "example.pdf"

os.chdir(my_dir)
src = os.path.abspath(my_pdf)

pdDoc = Dispatch("AcroExch.PDDoc")
pdDoc.Open(src)

jsObject = pdDoc.GetJSObject()

jsObject.SaveAs(os.path.abspath('./output_example.jpeg'), "com.adobe.acrobat.jpeg")


问题:
 jsObject为Null
 导致以下回溯:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-9c82c454eb2a> in <module>()
----> 1 jsObject.SaveAs(os.path.abspath('./output_example.jpeg'), "com.adobe.acrobat.jpeg")

AttributeError: 'NoneType' object has no attribute 'SaveAs'


错误文档说明:

GetJSObject
Gets a dual interface to the JavaScript object associated with the PDDoc. This allows automation clients full access to both built-in and user-defined JavaScript methods available in the document. For more information on working with JavaScript, see Developing Applications Using Interapplication Communication.

Syntax
LDispatch* GetJSObject();

Returns
The interface to the JavaScript object if the call succeeded, NULL otherwise.

最佳答案

考虑在与您的链接之一显示其用法时与AvDoc对象进行接口,然后从中构建pdDoc和jsObject。确保也将进程包装在try/except/finally块中以有效释放COM对象,而不管错误如何。

import os
import winerror
from win32com.client.dynamic import Dispatch, ERRORS_BAD_CONTEXT

ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)

my_dir = r"C:\\path\\to\\example\\"
my_pdf = "example.pdf"

os.chdir(my_dir)
src = os.path.abspath(my_pdf)

try:
    AvDoc = Dispatch("AcroExch.AVDoc")

    if AvDoc.Open(src, ""):
        pdDoc = AvDoc.GetPDDoc()
        jsObject = pdDoc.GetJSObject()
        jsObject.SaveAs(os.path.join(my_dir, 'output_example.jpeg'), "com.adobe.acrobat.jpeg")

except Exception as e:
    print(str(e))

finally:
    AvDoc.Close(True)

    jsObject = None
    pdDoc = None
    AvDoc = None

关于python - Python中的Adobe Acrobat API,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51530305/

10-12 23:24