inspiration

워드파일을 pdf로 만드려면, 워드파일을 열고, 다른이름으로 저장, pdf로 저장하면 끝날일이다.
하지만 여러개의 파일을 한꺼번에 바꾸자니, 그 또한 귀찮은 일이다.



execution

파이썬으로 충분히 가능할 것 같으니, exe파일을 만들어서, 일괄변경을 해보자.

sample.py

import os
import tkinter as tk
from tkinter import filedialog, messagebox
import comtypes.client
import traceback

def convert_word_to_pdf(file_path):
    file_path = os.path.abspath(file_path)
    pdf_path = os.path.splitext(file_path)[0] + ".pdf"
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = False
    try:
        doc = word.Documents.Open(file_path)
        doc.SaveAs(pdf_path, FileFormat=17)  # 17 = PDF
        doc.Close()
        return True, pdf_path
    except Exception as e:
        err_msg = f"Word 변환 오류: {str(e)}\n{traceback.format_exc()}"
        return False, err_msg
    finally:
        word.Quit()

def convert_ppt_to_pdf(file_path):
    file_path = os.path.abspath(file_path)
    pdf_path = os.path.splitext(file_path)[0] + ".pdf"
    ppt = comtypes.client.CreateObject("PowerPoint.Application")
    ppt.Visible = True  # PowerPoint는 False 불가, True로 설정

    try:
        presentation = ppt.Presentations.Open(file_path, WithWindow=False)
        presentation.SaveAs(pdf_path, 32)  # 32 = PDF
        presentation.Close()
        return True, pdf_path
    except Exception as e:
        err_msg = f"PPT 변환 오류: {str(e)}\n{traceback.format_exc()}"
        return False, err_msg
    finally:
        ppt.Quit()

def convert_excel_to_pdf(file_path):
    file_path = os.path.abspath(file_path)
    pdf_path = os.path.splitext(file_path)[0] + ".pdf"
    excel = comtypes.client.CreateObject("Excel.Application")
    excel.Visible = False

    try:
        workbook = excel.Workbooks.Open(file_path)
        workbook.ExportAsFixedFormat(0, pdf_path)  # 0 = PDF
        workbook.Close(False)
        return True, pdf_path
    except Exception as e:
        err_msg = f"Excel 변환 오류: {str(e)}\n{traceback.format_exc()}"
        return False, err_msg
    finally:
        excel.Quit()

def main():
    root = tk.Tk()
    root.withdraw()

    file_paths = filedialog.askopenfilenames(
        title="Office 문서 선택",
        filetypes=[
            ("Office Files", "*.doc *.docx *.ppt *.pptx *.xls *.xlsx"),
            ("All Files", "*.*")
        ]
    )

    if not file_paths:
        messagebox.showinfo("취소됨", "파일 선택이 취소되었습니다.")
        return

    success_list = []
    fail_list = []

    for file_path in file_paths:
        ext = os.path.splitext(file_path)[1].lower()
        if ext in [".doc", ".docx"]:
            success, result = convert_word_to_pdf(file_path)
        elif ext in [".ppt", ".pptx"]:
            success, result = convert_ppt_to_pdf(file_path)
        elif ext in [".xls", ".xlsx"]:
            success, result = convert_excel_to_pdf(file_path)
        else:
            success = False
            result = "지원하지 않는 파일 형식"

        if success:
            success_list.append(result)
        else:
            fail_list.append(f"{os.path.basename(file_path)}: {result}")

    msg = ""
    if success_list:
        msg += "✅ 변환 성공:\n" + "\n".join(success_list) + "\n\n"
    if fail_list:
        msg += "❌ 변환 실패:\n" + "\n".join(fail_list)

    if msg:
        messagebox.showinfo("변환 결과", msg)

if __name__ == "__main__":
    main()


conclusion

제목에 ‘파일을 열지 않고’ 라고 적었으나…
아쉽게도, 파워포인트는 열린다음에 진행이 되고, 속도가 마치.. 켠다음 하는 것과 크게 다르지 않으니… 이건 좋다고 할수도, 아쉽다고 하기도 애매하다.

chatGPT의 도움을 받으니, 머리를 쓸 일도, 생각을 할 일도 많지 않다.
이제는 어떤 걸 만들지에 대한 아이디어만 필요한 것이다.

끝.