使用win32com python在MS Word中提取PDF OLE对象。

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

这是我的第一个问题......。

我有很多MSWord文件,其中插入了1个或多个PDF文件作为对象,我需要处理所有的word文件,并提取pdf文件,将它们保存为pdf文件,使MSword文件和我发现的一样。

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阅读器 并保持他们打开,直到 "点击输入 "的时刻,当被关闭的word文件。

在这一点上,我是否需要更换 DoVerb() 用一些代码将OLE对象保存为PDF文件。

在这一点上 s 含有我需要的文件,但我找不到方法将其保存为文件,而不是只打开它。

请帮助我,我已经读了很多文章,现在没有找到答案。

python pdf ms-word win32com ole
1个回答
1
投票

我在Python-win32邮件列表中找到了一个变通的方法......感谢Chris Else,就像一些人在评论中说的那样,.bin文件不能被转换为pdf,Chris发给我的代码是。

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)
© www.soinside.com 2019 - 2024. All rights reserved.