converter.docx2img のソースコード

"""
概要: Word文書をPDFに変換し、さらにそのPDFを画像ファイルに変換するスクリプト。

詳細説明:
このスクリプトは、Microsoft Word文書 (.docx) をPDF形式に変換し、
その後、変換されたPDFファイル内の各ページを個別のPNG画像ファイルとして出力します。
WordからPDFへの変換にはcomtypesライブラリを介したWordアプリケーションのCOMオートメーションを使用し、
PDFから画像への変換にはPyMuPDF (fitz) ライブラリを使用します。
変換された画像は指定された出力ディレクトリに保存されます。

関連リンク:
:doc:`docx2img_usage`
"""
import os
import sys
import comtypes.client
try:
    import fitz  # PyMuPDF
except:
    print("\npptx2pdf_recursive.py: Import error: fitz")
    input("Install: pip install pymupdf\n")


# 入力ファイルと出力ディレクトリの設定
infile = '20240815-Coverletter.docx'
pdf_file = 'output.pdf'
out_dir = 'images_doc'

import os
import comtypes.client

[ドキュメント] def convert_word_to_pdf(word_file, pdf_file): """ 概要: 指定されたWord文書をPDFファイルに変換します。 詳細説明: Microsoft WordアプリケーションのCOMオブジェクトを介してWord文書を開き、 PDF形式で保存します。Wordアプリケーションは非表示モードで実行されます。 変換が成功した場合は"変換成功。"と表示し、失敗した場合はエラーメッセージを表示し、 例外を再発生させます。処理の完了後にはWordアプリケーションを確実に終了します。 :param word_file: 入力Word文書のパス (例: 'document.docx') :type word_file: str :param pdf_file: 出力PDFファイルのパス (例: 'output.pdf') :type pdf_file: str :returns: なし :rtype: None """ print(f"Convert [{word_file}] to [{pdf_file}]") application = None # 初期化 doc = None # 初期化 try: application = comtypes.client.CreateObject('Word.Application') application.Visible = False # Wordのウィンドウを非表示にする(任意) doc = application.Documents.Open(word_file) # Wordのコマンドを実行 doc.SaveAs(pdf_file, FileFormat=17) # 17 はPDF形式を示す定数 print("変換成功。") except Exception as e: # 例外が発生した場合、エラーメッセージを表示 print(f"エラー: {e}", file=sys.stderr) # 再度例外を発生させ、プログラムを終了させる raise finally: # docオブジェクトとWordアプリケーションを確実にクローズする if doc: doc.Close() if application: application.Quit()
[ドキュメント] def convert_pdf_to_images(pdf_file, out_dir): """ 概要: 指定されたPDFファイルをページごとにPNG画像に変換し、保存します。 詳細説明: PyMuPDF (fitz) を使用してPDFファイルを開き、各ページをピクセルマップとして抽出し、 PNG形式で指定された出力ディレクトリに保存します。 出力ディレクトリが存在しない場合は、この関数内で自動的に作成されます。 出力される画像ファイル名は 'page_1.png', 'page_2.png' のようになります。 :param pdf_file: 入力PDFファイルのパス (例: 'output.pdf') :type pdf_file: str :param out_dir: 画像ファイルを保存する出力ディレクトリのパス (例: 'images_doc') :type out_dir: str :returns: なし :rtype: None """ print(f"Output dir: [{out_dir}]") if not os.path.exists(out_dir): print(f"Create [{out_dir}]") os.makedirs(out_dir) print(f"Open [{pdf_file}]") doc = fitz.open(pdf_file) print(f"Exporting to [{out_dir}]") for page_num in range(len(doc)): page = doc.load_page(page_num) pix = page.get_pixmap() output_path = os.path.join(out_dir, f'page_{page_num + 1}.png') pix.save(output_path)
if __name__ == '__main__': current_dir = os.getcwd() word_path = os.path.join(current_dir, infile) pdf_path = os.path.join(current_dir, pdf_file) # Word文書をPDFに変換 convert_word_to_pdf(word_path, pdf_path) # PDFを画像に変換 convert_pdf_to_images(pdf_path, out_dir)