这是我的第一个问题。
我有许多MSWord文件,其中插入了1个或多个PDF作为对象,我需要处理所有de word文件并提取pdf以将它们另存为pdf文件,而留下de MS word文件就像我发现它一样。 到目前为止,我已经使用此代码在一个文件中对其进行测试:
import win32com.client as win32
word = win32.Dispatch('Word.Application')
word.Application.Visible = False
doc1 = word.Documents.Open('C:\\word_merge\\docx_con_pdfs.docx')
for s in doc1.InlineShapes:
if s.OLEFormat.ClassType == 'AcroExch.Document.DC':
s.OLEFormat.DoVerb()
_ = input("Hit Enter to Quit")
doc1.Close()
word.Application.Quit()
我知道这项工作是因为 s.OLEFormat.DoVerb()有效地打开了 Adobe Reader 中的文件,并一直保持打开状态,直到“命中输入”时刻为止。用word文件关闭。
此时我需要用一些将OLE对象保存到PDF文件中的代码替换 DoVerb()。
在这一点上, s 包含我需要的文件,但是我找不到将其保存为文件的方法,而不仅仅是打开它。
请帮助我,到目前为止我已经阅读了很多小时,却没有找到答案。
答案 0 :(得分:0)
我在python-win32邮件列表中找到了一种解决方法……多亏克里斯·埃尔斯(Chris Else),就像有人在一条评论中说的那样,.bin文件无法转换为pdf,这是克里斯发送给我的代码原为:
import olefile
from zipfile import ZipFile
from glob import glob
# How many PDF documents have we saved
pdf_count = 0
# Loop through all the .docx files in the current folder
for filename in glob("*.docx"):
try:
# Try to open the document as ZIP file
with ZipFile(filename, "r") as zip:
# Find files in the word/embeddings folder of the ZIP file
for entry in zip.infolist():
if not entry.filename.startswith("word/embeddings/"):
continue
# Try to open the embedded OLE file
with zip.open(entry.filename) as f:
if not olefile.isOleFile(f):
continue
ole = olefile.OleFileIO(f)
# CLSID for Adobe Acrobat Document
if ole.root.clsid != "B801CA65-A1FC-11D0-85AD-444553540000":
continue
if not ole.exists("CONTENTS"):
continue
# Extract the PDF from the OLE file
pdf_data = ole.openstream('CONTENTS').read()
# Does the embedded file have a %PDF- header?
if pdf_data[0:5] == b'%PDF-':
pdf_count += 1
pdf_filename = "Document %d.pdf" % pdf_count
# Save the PDF
with open(pdf_filename, "wb") as output_file:
output_file.write(pdf_data)
except:
print("Unable to open '%s'" % filename)
print("Extracted %d PDF documents" % pdf_count)