hwp to pdf 변환 (파일열지않고)

튜토리얼: 작성중.

>> 다운로드하러 가기

코드는 아래에..

import os
import win32com.client as win32
import tkinter as tk
from tkinterdnd2 import DND_FILES, TkinterDnD
import threading
import pythoncom
import webbrowser

# --- 설정값 (디자인) ---
FONT_MAIN = ("맑은 고딕", 10, "bold")
FONT_CREDIT = ("맑은 고딕", 8, "bold")  # 완료 시 나오는 작은 글씨
COLOR_IDLE = "#2E2E2E"  # 평상시 (진한 회색)
COLOR_PROCESSING = "#124fb3"  # 처리 중 (파란색)
COLOR_DONE = "#23754c"  # 완료 시 (초록색)
TEXT_COLOR = "white"


def open_link(event):
    # 제작자 링크 클릭 시 이동
    webbrowser.open("https://cha-record.studio/")


def update_ui_colors(bg_color):
    # 배경색과 라벨색을 동시에 변경하는 함수
    root.configure(bg=bg_color)
    lbl_main.configure(bg=bg_color)
    lbl_credit.configure(bg=bg_color)


def convert_hwp_to_pdf(file_list, main_label, credit_label):
    # 스레드 초기화
    pythoncom.CoInitialize()

    hwp = None
    try:
        # [상태 1] 처리 시작 -> 파란색 변경
        update_ui_colors(COLOR_PROCESSING)
        credit_label.config(text="")  # 처리 중엔 제작자 문구 숨김
        main_label.config(text="백그라운드 엔진 구동 중...")

        # HWP 백그라운드 실행 (창 숨김 모드)
        hwp = win32.gencache.EnsureDispatch("HWPFrame.HwpObject")
        hwp.RegisterModule("FilePathCheckDLL", "FilePathCheckerModule")  # 보안 팝업 승인
        hwp.XHwpWindows.Item(0).Visible = False  # 창 숨김

        total = len(file_list)
        success_count = 0

        for idx, file_path in enumerate(file_list):
            # 경로 정리
            file_path = file_path.replace("{", "").replace("}", "")

            if not file_path.lower().endswith('.hwp'):
                continue

            file_name = os.path.basename(file_path)
            main_label.config(text=f"처리 중 ({idx + 1}/{total}): {file_name}")

            try:
                # 파일 열기
                hwp.Open(file_path, "HWP", "forceopen:true")

                # PDF 저장 설정
                pdf_path = os.path.splitext(file_path)[0] + ".pdf"

                act = hwp.CreateAction("FileSaveAs_S")
                pset = act.CreateSet()
                act.GetDefault(pset)
                pset.SetItem("FileName", pdf_path)
                pset.SetItem("Format", "PDF")
                act.Execute(pset)

                success_count += 1

                # 문서 닫기
                hwp.Clear(1)

            except Exception as e:
                print(f"Error ({file_name}): {e}")

        # [상태 2] 완료 -> 초록색 변경
        update_ui_colors(COLOR_DONE)
        main_label.config(text=f"완료! ({success_count}개 변환)")

        # 제작자 문구 표시 (작은 글씨)
        credit_label.config(text="제작 및 업그레이드버전: 차민경(https://cha-record.studio/)")

    except Exception as e:
        update_ui_colors("red")
        main_label.config(text="오류 발생! 다시 시도해주세요.")
        print(f"System Error: {e}")

    finally:
        # 한글 종료
        if hwp:
            try:
                hwp.Quit()
            except:
                pass
        pythoncom.CoUninitialize()


def drop(event):
    files = event.data
    # 드래그된 파일 경로 파싱
    if "{" in files:
        file_list = [f.strip("{}") for f in files.split("} {")]
    else:
        file_list = files.split()

    # 별도 스레드로 작업 시작
    t = threading.Thread(target=convert_hwp_to_pdf, args=(file_list, lbl_main, lbl_credit))
    t.daemon = True
    t.start()


# --- GUI 화면 구성 ---
root = TkinterDnD.Tk()
root.title("HWP to PDF Converter")

# 창 크기 및 위치 (항상 위)
root.geometry("320x65")
root.attributes("-topmost", True)

# 1. 메인 문구 라벨 (위쪽)
lbl_main = tk.Label(root,
                    text="HWP파일을 드래그앤드롭하세요 (여러개 가능)",
                    fg=TEXT_COLOR,
                    bg=COLOR_IDLE,
                    font=FONT_MAIN)
lbl_main.pack(expand=True, fill="both", side="top", pady=(5, 0))

# 2. 제작자 문구 라벨 (아래쪽)
lbl_credit = tk.Label(root,
                      text="",
                      fg=TEXT_COLOR,
                      bg=COLOR_IDLE,
                      font=FONT_CREDIT,
                      cursor="hand2")  # 클릭 가능한 손가락 모양
lbl_credit.pack(side="bottom", fill="x", pady=(0, 5))
lbl_credit.bind("<Button-1>", open_link)

# [수정된 부분] 라벨을 다 만든 후에 색상을 초기화해야 에러가 안 납니다.
update_ui_colors(COLOR_IDLE)

# 드래그 앤 드롭 기능 연결
root.drop_target_register(DND_FILES)
root.dnd_bind('<<Drop>>', drop)

root.mainloop()


코멘트

댓글 남기기

Cha's Record에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기