converter.xlsx2img のソースコード

"""
Excelファイルを画像に変換するスクリプト。

このスクリプトは、指定されたExcelファイル(.xlsx)をまずPDF形式に変換し、
その後、そのPDFをページごとに個別の画像ファイルに変換します。
Windows環境でExcelアプリケーションとPyMuPDF(fitz)ライブラリを使用します。

:doc:`xlsx2img_usage`
"""
import os
import sys
from comtypes.client import CreateObject
import fitz  # PyMuPDF


excel_file = 'test.xlsx'
pdf_file = 'output.pdf'
out_dir = 'images'
image_format = 'png'


nargv = len(sys.argv)
if nargv >= 2: infile = sys.argv[1]
if nargv >= 3: out_dir = sys.argv[2]
if nargv >= 4: image_format = sys.argv[3]


[ドキュメント] def convert_excel_to_pdf(excel_file: str, pdf_file: str): """ 指定されたExcelファイルをPDF形式に変換します。 この関数はCOMを通じてExcelアプリケーションを起動し、指定されたExcelファイルを開いてPDFとして保存します。 Excelアプリケーションは変換完了後に終了されます。 :param excel_file: 変換元のExcelファイルのパス。 :type excel_file: str :param pdf_file: 変換後のPDFファイルの保存パス。 :type pdf_file: str :returns: なし :rtype: None """ excel = CreateObject('Excel.Application') excel.Visible = False # Excelファイルを開く workbook = excel.Workbooks.Open(os.path.abspath(excel_file)) # PDFとして保存 workbook.ExportAsFixedFormat(0, os.path.abspath(pdf_file)) # 0はPDF形式を示す定数 workbook.Close(False) excel.Quit()
[ドキュメント] def convert_pdf_to_images(pdf_file: str, out_dir: str, image_format: str): """ 指定されたPDFファイルをページごとに画像ファイルに変換します。 PyMuPDF (fitz) ライブラリを使用してPDFを開き、各ページをピクセルマップとして抽出し、 指定された出力ディレクトリに指定された画像形式で保存します。 出力ディレクトリが存在しない場合は、自動的に作成されます。 :param pdf_file: 変換元のPDFファイルのパス。 :type pdf_file: str :param out_dir: 画像ファイルを保存するディレクトリのパス。 :type out_dir: str :param image_format: 出力する画像ファイルのフォーマット(例: 'png', 'jpeg')。 :type image_format: str :returns: なし :rtype: None """ # 画像を保存するディレクトリが存在しない場合は作成 if not os.path.exists(out_dir): os.makedirs(out_dir) # PDFを開く doc = fitz.open(pdf_file) 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}.{image_format}') pix.save(output_path)
if __name__ == '__main__': # 現在のディレクトリを取得 current_dir = os.getcwd() # ファイルパスを作成 excel_path = os.path.join(current_dir, excel_file) pdf_path = os.path.join(current_dir, pdf_file) # ExcelファイルをPDFに変換 convert_excel_to_pdf(excel_path, pdf_path) # PDFを画像に変換 convert_pdf_to_images(pdf_path, out_dir, image_format)