【问题标题】:Extract PDF OLE Object in MS Word using win32com python使用win32com python在MS Word中提取PDF OLE对象
【发布时间】:2020-05-23 23:02:59
【问题描述】:

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

我有很多 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 包含我需要的文件,但我找不到将其保存为文件的方法,而只能打开它。

请帮助我,我已经阅读了很多小时的文章并没有找到答案。

【问题讨论】:

  • 嵌入的 Acrobat 文件在 Word 文件中时会打开。但是,如果您展开该文件并查看 word\embeddings 文件夹,它被称为“oleObject1.bin”。它是一个二进制文件,大约是原始 PDF 大小的四分之一,主要是文本。将文件结尾更改为 PDF 不会创建可以在 Acrobat 中打开的文件。因此,Word 似乎在嵌入文件时对其进行了转换。您的提取还必须撤消 AFAIK 未记录的转换。
  • 我在 python-win32 邮件列表中找到了一种解决方法......感谢 Chris Else,就像一些评论中所说的那样,.bin 文件不能转换为 pdf,克里斯发给我的代码是:
  • 来自 chris 的信息是:如果您的 MS Word 文档是 .docx 类型的,那么它们基本上是包含大量 XML 元数据和任何嵌入文档的 ZIP 文件。我没有使用 python-win32 的解决方案,但写了这个,它确实有效:-

标签: python pdf ms-word win32com ole


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 2012-04-14
    • 2020-05-05
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多