如何使用python 3将可填充pdf转换为常规pdf?

时间:2019-06-11 18:36:30

标签: python-3.x

我正在尝试将可填充的pdf保存为常规pdf。在Adobe中,您可以将pdf打印到“ Adob​​e pdf”打印机。如何在python 3中做到这一点?

1 个答案:

答案 0 :(得分:0)

我做了一些研究,找到了一种方法。也许这不是最好的方法,但是对我有用。我希望有人能提出更好的方法。

我所做的是先将可填充pdf转换为word,然后将word文档转换回pdf。如果我将可填充的pdf转换为html / csv,我会丢失很多信息,而且我不知道为什么。如果我将pdf转换为word或pptx,效果很好。

这是我使用的代码:

import win32com.client, win32com.client.makepy, os, winerror, pandas as pd, errno, re
from win32com.client.dynamic import ERRORS_BAD_CONTEXT
import win32com.client as win32  
import time 
import sys
import comtypes.client

# convert pdf to docx
ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)

win32com.client.makepy.GenerateFromTypeLibSpec('Acrobat')
adobe = win32com.client.DispatchEx('AcroExch.App')
avDoc = win32com.client.DispatchEx('AcroExch.AVDoc')

src = r'C:\Users\test.pdf'
ret = avDoc.Open(src, src)
assert(ret)   
pdDoc = avDoc.GetPDDoc()
jObject = pdDoc.GetJSObject()
word_file = src.replace('.pdf','.docx')
if os.path.exists(word_file):
    os.remove(word_file)
    open(word_file,'w').close()      
jObject.SaveAs(word_file, "com.adobe.acrobat.docx")
pdDoc.Close()
avDoc.Close(True)
del pdDoc

#convert word document to pdf 
word =  comtypes.client.CreateObject('Word.Application')
word.Visible = False
time.sleep(3)
wdFormatPDF = 17
doc = word.Documents.Open(word_file)
out_file = src.replace('.pdf','tempt.pdf')
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()