Files
diw/test.py
2024-11-07 17:14:35 +09:00

98 lines
3.3 KiB
Python

# from pyhwpx import Hwp # 임포트
# hwp = Hwp() # 아래아한글 실행(프로그램이 실행되어 있는 경우, 기존 한/글 프로그램에 연결됨)
# hwp.insert_text("Hello world!\r\n") # 문자열 삽입
# hwp.create_table(5, 5, treat_as_char=True) # 5행5열의 표 삽입(글자처럼 취급)
# for i in range(25): # 표에 내용 삽입
# hwp.insert_text(i)
# hwp.TableRightCell()
# hwp.MoveDown()
# hwp.insert_picture("https://ultralytics.com/images/zidane.jpg") # 이미지 삽입
# hwp.ShapeObjAttachCaption() # 캡션 삽입
# hwp.insert_text("Zidane") # 캡션 문자열 입력
# hwp.ParagraphShapeAlignCenter() # 캡션 가운데정렬
# hwp.SelectAll() # 캡션 전체선택
# hwp.set_font(Bold=True, FaceName="돋움", Height=20, TextColor="Red") # 캡션 글자모양 변경
# hwp.Cancel() # 선택해제
# hwp.Close() # 캡션 편집 종료
import win32com.client
import os
import logging
from pathlib import Path
def setup_logging():
"""로깅 설정"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('hwp_conversion.log'),
logging.StreamHandler()
]
)
def convert_hwp_to_xml(input_folder, output_folder):
"""
지정된 폴더 내의 모든 HWP 파일을 XML로 변환
Args:
input_folder (str): HWP 파일이 있는 폴더 경로
output_folder (str): XML 파일을 저장할 폴더 경로
"""
try:
# 한글 애플리케이션 객체 생성
hwp = win32com.client.Dispatch("HWPFrame.HwpObject")
# 자동화 보안 설정
hwp.XHwpWindows.Item(0).Visible = False
hwp.RegisterModule("FilePathCheckDLL", "FilePathCheckerModule")
# 출력 폴더가 없으면 생성
os.makedirs(output_folder, exist_ok=True)
# HWP 파일 검색 및 변환
input_path = Path(input_folder)
for hwp_file in input_path.glob("*.hwp"):
try:
# 파일 열기
hwp.Open(str(hwp_file))
# XML 파일 경로 설정
xml_filename = hwp_file.stem + ".xml"
xml_path = os.path.join(output_folder, xml_filename)
# XML로 저장
hwp.SaveAs(xml_path, "HWPML2X")
logging.info(f"변환 성공: {hwp_file.name} -> {xml_filename}")
except Exception as e:
logging.error(f"파일 변환 실패: {hwp_file.name} - {str(e)}")
finally:
# 현재 문서 닫기
hwp.Clear(3)
except Exception as e:
logging.error(f"프로그램 실행 오류: {str(e)}")
finally:
# 한글 프로그램 종료
try:
hwp.Quit()
except:
pass
if __name__ == "__main__":
# 로깅 설정
setup_logging()
# 변환할 폴더 경로 설정
input_folder = r"C:\Users\gzero-ser7-win11\Documents\hwpTest\Input" # HWP 파일이 있는 폴더
output_folder = r"C:\Users\gzero-ser7-win11\Documents\hwpTest\Output" # XML 파일을 저장할 폴더
# 변환 실행
convert_hwp_to_xml(input_folder, output_folder)