Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Created October 24, 2025 09:01
Show Gist options
  • Save gnh1201/a0448c06c96e3b6b409f3a9f9dbfc453 to your computer and use it in GitHub Desktop.
Save gnh1201/a0448c06c96e3b6b409f3a9f9dbfc453 to your computer and use it in GitHub Desktop.
HWP to PDF conversion python
# batch_hwp_to_pdf_recover.py
# Namhyeon Go <[email protected]>
# MIT license
import os
import time
import subprocess
import pythoncom
from win32com.client import Dispatch
HWP_EXE_PATH = r"C:\Program Files (x86)\HNC\Office 2020\HOffice110\Bin\Hwp.exe"
def launch_hwp():
print("한글 인스턴스를 실행합니다...")
subprocess.Popen([HWP_EXE_PATH])
time.sleep(5) # 한글 실행 대기 시간 (필요시 조정)
def get_hwp_instance():
pythoncom.CoInitialize()
context = pythoncom.CreateBindCtx(0)
rot = pythoncom.GetRunningObjectTable()
moniker_list = rot.EnumRunning()
while True:
moniker = moniker_list.Next(1)
if not moniker:
break
display_name = moniker[0].GetDisplayName(context, None)
if "!HwpObject.110.1" in display_name:
return rot.GetObject(moniker[0])
return None
def get_or_recover_hwp_dispatch():
obj = get_hwp_instance()
if obj is None:
launch_hwp()
obj = get_hwp_instance()
if obj is None:
raise RuntimeError("한글 인스턴스를 복구할 수 없습니다.")
return Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch))
def convert_hwp_to_pdf_in_directory(dir_path):
hwp = get_or_recover_hwp_dispatch()
for file_name in os.listdir(dir_path):
if file_name.lower().endswith(".hwp"):
hwp_path = os.path.join(dir_path, file_name)
pdf_path = os.path.join(dir_path, os.path.splitext(file_name)[0] + ".pdf")
try:
hwp.Open(hwp_path, Format="HWP", arg="forceopen:True;suspendpassword:True;versionwarning:False")
hwp.HAction.GetDefault("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
hwp.HParameterSet.HFileOpenSave.filename = pdf_path
hwp.HParameterSet.HFileOpenSave.Format = "PDF"
hwp.HAction.Execute("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
print("변환 성공:", pdf_path)
except Exception as e:
print("변환 실패:", hwp_path, "오류:", e)
print("한글 인스턴스를 재시도합니다...")
try:
hwp = get_or_recover_hwp_dispatch()
hwp.Open(hwp_path, Format="HWP", arg="forceopen:True;suspendpassword:True;versionwarning:False")
hwp.HAction.GetDefault("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
hwp.HParameterSet.HFileOpenSave.filename = pdf_path
hwp.HParameterSet.HFileOpenSave.Format = "PDF"
hwp.HAction.Execute("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
print("재시도 성공:", pdf_path)
except Exception as e2:
print("재시도 실패:", hwp_path, "오류:", e2)
time.sleep(1)
if __name__ == "__main__":
target_dir = r"C:\Users\user\AppData\Roaming\WelsonJS\DDoS 훈련 결과 보고서(송부용)" # 원하는 폴더 경로로 수정
convert_hwp_to_pdf_in_directory(target_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment