한글 파일 내 표 서식 일괄 재설정

한글파일 내 여러 표들에 대해서 서식을 일괄적으로 통일시킬 수 있을까요? 가로 폭 166mm과 글자처럼 적용 미적용 정도의 바깥여백 정도의 요소를 통일시키고 싶습니다. 파이썬 이용해서 xml파일과 xsl파일을 수정하여 서식을 조정해보려 했는데 hwpx로 전환하는 과정에서 깨지는 듯 합니다. 더 효율적인 방법이나 쉬운 방안이 있는지 궁금합니다,

혹시몰라 아래 만들었던 코드 같이 첨부합니다

import os
import zipfile
import xml.etree.ElementTree as ET

# 파일 경로 설정
xml_path = "C:/Users/user/Desktop/파일명.xml"
xsl_path = "C:/Users/user/Desktop/파일명.xsl"
output_hwpx = "C:/Users/user/Desktop/파일명_수정본.hwpx"
extract_folder = "C:/Users/user/Desktop/hpwx_extract"

# 🔹 XML 수정: <TABLE> 속성 변경 + 셀 크기 조정
def modify_xml(xml_path):
    try:
        tree = ET.parse(xml_path)
        root = tree.getroot()

        tables = root.findall(".//TABLE")
        modified_count = 0

        for table in tables:
            # ✅ 표 너비 조정 (166mm)
            table.set("width", "166mm")
            table.set("align", "center")

            # ✅ 표 위치 설정
            table.set("treatAsChar", "false")  # 글자처럼 취급 ❌
            table.set("textWrap", "3")  # 자리차지
            table.set("horzAlign", "1")  # 단 왼쪽 기준 0mm
            table.set("marginLeft", "6mm")
            table.set("marginTop", "1mm")
            table.set("marginRight", "1mm")
            table.set("marginBottom", "1mm")

            # ✅ 표 크기 조정 불가할 경우 셀 크기 개별 조정
            cells = table.findall(".//CELL")
            if cells:
                cell_width = 16600 // len(cells)  # 셀 개수에 따라 크기 나누기
                for cell in cells:
                    cell.set("width", f"{cell_width}")

            modified_count += 1

        tree.write(xml_path, encoding="utf-8", xml_declaration=True)
        print(f"✅ XML 수정 완료: {modified_count}개의 표 변경됨")

    except Exception as e:
        print(f"❌ XML 수정 실패: {e}")

# 🔹 XSL 수정: 표 스타일 조정 (166mm, 정렬, 테두리, 여백, 폰트)
def modify_xsl(xsl_path):
    try:
        with open(xsl_path, "r", encoding="utf-8") as file:
            xsl_content = file.read()

        # ✅ 표 스타일 수정 (166mm 너비, 가운데 정렬, 바탕글 스타일 적용)
        xsl_content = xsl_content.replace("width: auto", "width: 166mm")
        xsl_content = xsl_content.replace("text-align: left", "text-align: center")
        
        # ✅ 표 위치 관련 속성 추가
        xsl_content = xsl_content.replace(
            "border: none", 
            "border: 1px solid black; margin-left: 6mm; margin-top: 1mm; margin-right: 1mm; margin-bottom: 1mm"
        )

        with open(xsl_path, "w", encoding="utf-8") as file:
            file.write(xsl_content)

        print("✅ XSL 스타일 수정 완료")

    except Exception as e:
        print(f"❌ XSL 수정 실패: {e}")

# 🔹 수정된 파일을 다시 HWPX로 압축
def create_hwpx(output_hwpx, extract_folder):
    try:
        with zipfile.ZipFile(output_hwpx, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, _, files in os.walk(extract_folder):
                for file in files:
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, extract_folder)  # ZIP 내 상대 경로
                    zipf.write(file_path, arcname)

        print(f"✅ HWPX 파일 생성 완료: {output_hwp}")

    except Exception as e:
        print(f"❌ HWPX 생성 실패: {e}")

# 실행
modify_xml(xml_path)
modify_xsl(xsl_path)
create_hwpx(output_hwpx, extract_folder)
1개의 좋아요

안녕하세요

아래코드 참고하시고 필요한 사항 수정하시면서 사용하면 좋을 것 같아요.

  • 한글 2024에서 새로 추가된 함수( SelectCtrl, GetCtrlInstID)를 사용합니다.
import win32com.client as win32
import os

def GetTableCellAddr():
    return hwp.KeyIndicator()[-1][1:].split(")")[0]

def GetTableCellCount():
    CellCount = 0
    hwp.HAction.Run("ShapeObjTextBoxEdit")
    OldCellAddrName = GetTableCellAddr()
    while hwp.HAction.Run("MoveRight") :
        CellCount += 1
        NewCellAddrName = GetTableCellAddr()
        if NewCellAddrName == OldCellAddrName :
            break
        elif NewCellAddrName[-1] != "1" :
            break
        OldCellAddrName = NewCellAddrName
    return CellCount

def setTableWidth(TotalWidth, cellCount) :
    hwp.HAction.Run("TableCellBlock");
    hwp.HAction.Run("TableCellBlockExtend");
    hwp.HAction.Run("TableCellBlockExtend");
    hwp.HAction.GetDefault("TablePropertyDialog", hwp.HParameterSet.HShapeObject.HSet);  
    hwp.HParameterSet.HShapeObject.ShapeTableCell.Width = hwp.MiliToHwpUnit(160.0/ cellCount);        
    hwp.HAction.Execute("TablePropertyDialog", hwp.HParameterSet.HShapeObject.HSet);


hwp = win32.gencache.EnsureDispatch("HWPFrame.HwpObject")
hwp.XHwpWindows.Active_XHwpWindow.Visible = True
hwp_file_path = "C:\\Temp\\table.hwpx"
hwp.Open(hwp_file_path)

ctrl = hwp.HeadCtrl
while ctrl is not None:
    if ctrl.CtrlID == "tbl":
        hwp.SelectCtrl(ctrl.GetCtrlInstID()  , 1)        
        hwp.HAction.GetDefault("ShapeObjDialog", hwp.HParameterSet.HShapeObject.HSet)
        hwp.HParameterSet.HShapeObject.OutsideMarginLeft = hwp.MiliToHwpUnit(6.0)
        hwp.HParameterSet.HShapeObject.OutsideMarginRight = hwp.MiliToHwpUnit(1.0)
        hwp.HParameterSet.HShapeObject.OutsideMarginTop = hwp.MiliToHwpUnit(1.0)
        hwp.HParameterSet.HShapeObject.OutsideMarginBottom = hwp.MiliToHwpUnit(1.0)
        hwp.HParameterSet.HShapeObject.TreatAsChar = 1
        hwp.HAction.Execute("ShapeObjDialog", hwp.HParameterSet.HShapeObject.HSet)
        setTableWidth(160.0, GetTableCellCount())
    ctrl = ctrl.Next

hwp.Quit()

안녕하세요.

답변 내용 중에서
한글 2024에서 새로 추가된 함수( SelectCtrl, GetCtrlInstID)를 말씀하셨는데
이렇게 새로 추가된 함수를 사용자가 알 수 있는 방법은 무엇인지 궁금합니다.
또, 함수에 대한 설명을 볼 수 있는 곳이 어딘지 궁금합니다.

수고하세요~

안녕하세요

SelectCtrl API는 개체를 선택할 수 있는 API입니다.
parmeters에 대해 말씀드리면 다음과 같습니다.

Parameters

ctrlList: 선택할 컨트롤 ID. 문자코드 0x02를 이용해서 여러 개의 컨트롤ID를 지정할 수 있다.

  • 컨트롤 ID는 HwpCtrl.CtrlID가 리턴하는 ID와 동일하다. 자세한 것은 Ctrl 오브젝트 Properties인 CtrlID를 참조.

option : 현재 선택된 컨트롤에서 추가로 선택을 할지, 취소 후 다시 선택할지에 대한 옵션.

  • 0 = 추가로 선택
  • 1 = 취소 후 ctrlList에 등록된 컨트롤만 선택

현재 개발 가이드 문서를 2024버전으로 업데이트 진행 중입니다.
추후 아래 개발 가이드 사이트에 업데이트 할 예정입니다.

추가로 궁금하신 사항이 있으시면 말씀 부탁드립니다.

감사합니다.

1개의 좋아요