通过 Acrobat COM 接口使用 Python 将页脚添加到 PDF (AddWatermarkFromText)

问题描述 投票:0回答:1

编辑:我已经找到了解决方案,请参阅下面的回复。

原帖:
我可以使用以下代码通过 VBA 添加页脚:

Dim PDDocDestination As Object
Dim JSO As Object
Dim i As Long, numPages As Long

Set PDDocDestination = CreateObject("AcroExch.PDDoc")

Set JSO = PDDocDestination.GetJSObject
numPages = PDDocDestination.GetNumPages

' Loop through each page and add the footer
For i = 1 To numPages
    JSO.addWatermarkFromText cText:="text", cFont:="CenturyGothic", nFontSize:=7, nHorizAlign:=1, nVertAlign:=4, nVertValue:=12.5, nStart:=i - 1, nEnd:=i - 1
Next i

'Save destination (merged) PDF
PDDocDestination.Save PDSaveFull, mergedPDF
PDDocDestination.Close

'Cleanup
Set PDDocDestination = Nothing
Set JSO = Nothing

但是,当我尝试将其转换为 Python 时,我在 AddWatermarkFromText 方法上收到以下错误:

pywintypes.com_error: (-2147467263, 'Not implemented', None, None)
。我已经尝试了所有我能想到的排列。这是我的代码:

def add_footer_to_pdf(pdf_path, output_path, text, font="CenturyGothic", font_size=7, horiz_align=1, vert_align=4, vert_value=12.5):
    # Create COM object to interact with Acrobat
    try:
        AcroApp = Dispatch("AcroExch.App")
        AcroPDDoc = Dispatch("AcroExch.PDDoc")
        AcroPDDoc.Open(pdf_path)
        JSO = AcroPDDoc.GetJSObject()
        num_pages = AcroPDDoc.GetNumPages()

        # Loop through each page and add the footer
        for i in range(num_pages):
            JSO.addWatermarkFromText(cText=f"{text}, page {i+1}", cFont=font, nFontSize=font_size, nHorizAlign=horiz_align, nVertAlign=vert_align, nVertValue=vert_value, nStart=i, nEnd=i)

        # Save the modified PDF
        AcroPDDoc.Save(1, output_path)
        # if not AcroPDDoc.Save(1, output_path):
        #     print("Failed to save the PDF")
    finally:
        AcroPDDoc.Close()
        AcroApp.Exit()
        del AcroApp, AcroPDDoc

我不知道这是否是因为该方法无法通过 pywin32/win32com 获得,但我认为既然它在 VBA 中可用,那么它应该在 Python 中可用。我担心 PDDoc 对象未正确初始化或文档未正确打开,但据我所知,两者似乎都很好;我使用 AcroPDDoc.GetNumPages() 获得了正确的页数。

我尝试过使用或不使用参数、带或不带括号调用 addWatermarkFromText,甚至使用大写和小写的“A”。

如有任何帮助,我们将不胜感激!谢谢!

python adobe footer com-interface
1个回答
0
投票

要修复 JSObject 不起作用的问题,请从 win32com.client.dynamic(而不是 win32com.client)导入 Dispatch,并将 winerror.E_NOTIMPL 添加到dynamic.py 中的 ERRORS_BAD_CONTEXT 列表中。

ERRORS_BAD_CONTEXT = [
    winerror.DISP_E_MEMBERNOTFOUND,
    winerror.DISP_E_BADPARAMCOUNT,
    winerror.DISP_E_PARAMNOTOPTIONAL,
    winerror.DISP_E_TYPEMISMATCH,
    winerror.E_INVALIDARG,
    winerror.E_NOTIMPL,
]

解决方案由 Subhobroto 发布于here。太棒了!

© www.soinside.com 2019 - 2024. All rights reserved.