簡體   English   中英

使用 win32com python 在 MS Word 中提取 PDF OLE Object

[英]Extract PDF OLE Object in MS Word using win32com python

這是我在這里的第一個問題....

我有很多 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中打開文件並保持它們打開直到“Hit Enter”時刻,當用 word 文件關閉時。

在這一點上,當我需要用一些將 OLE Object 保存到 PDF 文件中的代碼替換DoVerb()時。

在這一點s包含我需要的文件,但我找不到將其保存為文件的方法,而不僅僅是打開它。

請幫助我,我已經閱讀了很多小時的文章,但沒有找到答案。

我在 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM