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, pdf_file):
    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, out_dir, image_format):
    # 画像を保存するディレクトリが存在しない場合は作成
    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)
