다음 예제는 python-hwpx의 주요 API를 조합해 실제 시나리오를 해결하는 방법을 보여 줍니다. examples/ 디렉터리에 포함된 샘플 HWPX 파일(FormattingShowcase.hwpx)을 기준으로 작성되었으며, 해당 파일은 저장소를 직접 클론했을 때만 사용할 수 있습니다. PyPI로 설치했다면 보유 중인 HWPX 문서를 사용하거나, hwpx.templates.blank_document_bytes()로 임시 문서를 생성해 실습하세요.
Python 블록 판정: 실행 분류 ledger가 이 current manual의 모든 Python 블록을 동결합니다. 독립 실행 예제 표시가 없는 블록은 기존 입력 파일이나 앞 문맥이 필요한 조각입니다.
독립 실행 예제 — 내장 템플릿 바이트만 사용합니다.
from io import BytesIO from hwpx import HwpxDocument from hwpx.templates import blank_document_bytes document = HwpxDocument.open(BytesIO(blank_document_bytes())) document.add_paragraph("첫 문단입니다.") document.save_to_path("playground.hwpx")
from hwpx import HwpxDocument document = HwpxDocument.open("examples/FormattingShowcase.hwpx") section = document.sections[-1] # 머리글 문단을 추가하고 강조 스타일을 적용합니다. headline = document.add_paragraph( "분기별 요약", section=section, style_id_ref=1, char_pr_id_ref=6, ) headline.text = "분기별 실적 요약" # 2x3 표를 생성하고 헤더 행을 병합합니다. table = document.add_table( rows=2, cols=3, section=section, border_fill_id_ref="3", ) table.merge_cells(0, 0, 0, 2) # 병합된 헤더 행은 논리 좌표를 기준으로 편집할 수 있습니다. table.set_cell_text(0, 0, "Quarter", logical=True) table.set_cell_text(0, 1, "Actual", logical=True) table.set_cell_text(0, 2, "Forecast", logical=True) # iter_grid()/get_cell_map()으로 병합 구조를 확인하거나, 필요 시 병합을 해제할 수 있습니다. header_map = table.get_cell_map()[0] for entry in header_map: print(f"({entry.row}, {entry.column}) -> anchor={entry.anchor}, span={entry.span}") # table.split_merged_cell(0, 1) # 병합 해제가 필요하다면 사용 # 본문 행을 채우고 셀 크기를 조정합니다. q1_label = table.cell(1, 0) q1_label.text = "Q1" actual_cell = table.cell(1, 1) actual_cell.text = "42,000" actual_cell.set_size(width=3600) forecast_cell = table.cell(1, 2) forecast_cell.text = "44,500" # 강조 도형을 문단으로 추가합니다. 전용 헬퍼가 한컴이 요구하는 하위 요소까지 채웁니다. shape = document.add_rectangle(9000, 3500, fill_color="#FFF2CC", section=section) shape.resize(9600, 3500) # add_control은 저수준 탈출구입니다 — 필수 하위 요소를 만들지 않아 UserWarning이 # 나고, 호출자가 직접 채우지 않으면 한컴이 열지 못하는 문서가 됩니다. document.add_control( section=section, control_type="LINE", attributes={"id": "guideline-1", "type": "LINE"}, ) document.save_to_path("examples/FormattingShowcase-updated.hwpx")
from hwpx import HwpxDocument document = HwpxDocument.open("examples/FormattingShowcase.hwpx") section = document.sections[0] # 빈 단락 제거 for para in list(section.paragraphs): if not para.text.strip() and len(section.paragraphs) > 1: para.remove() # 새 섹션 추가 후 내용 작성 new_sec = document.add_section() new_sec.add_paragraph("부록 A") new_sec.add_paragraph("추가 데이터가 여기에 들어갑니다.") print("섹션 수:", len(document.sections)) # 필요 없는 섹션 삭제 if len(document.sections) > 1: document.remove_section(len(document.sections) - 1) document.save_to_path("examples/cleaned.hwpx")
from hwpx.tools.text_extractor import AnnotationOptions, TextExtractor template = "* {section}:{index} — {text}" options = AnnotationOptions( highlight="markers", footnote="inline", endnote="inline", hyperlink="target", control="placeholder", control_placeholder="[CTRL:{name}]", ) with TextExtractor("examples/FormattingShowcase.hwpx") as extractor: for paragraph in extractor.iter_document_paragraphs(): text = paragraph.text(annotations=options) if not text.strip(): continue print( template.format( section=paragraph.section.index, index=paragraph.index, text=text.replace("\n", " "), ) )
AnnotationOptions를 활용하면 하이라이트 구간이 [HIGHLIGHT color=#ffff00]텍스트[/HIGHLIGHT] 형태로 출력되고, 각주와 미주 내용은 인라인으로 삽입됩니다. 하이퍼링크는 실제 URL을 포함하며, 컨트롤은 control_placeholder 형식에 따라 자리표시자로 치환됩니다.
from hwpx.tools.object_finder import ObjectFinder finder = ObjectFinder("examples/FormattingShowcase.hwpx") # 문서 내 모든 각주 요소를 찾습니다. notes = finder.find_all(tag="hp:footNote") print("Found", len(notes), "footnotes") # 책갈피 ID로 시작하는 문단만 가져옵니다. bookmarked = finder.find_all( tag="hp:p", attrs={"id": lambda value: value.startswith("bookmark")}, ) for element in bookmarked: print(element.section.name, element.path)
ObjectFinder는 XPath 표현식, 태그/속성 매칭, 주석 전용 이터레이터(iter_annotations)를 모두 지원하므로 문서 내부 구조를 탐색하거나 특정 개체만 선별하는 자동화 스크립트를 쉽게 작성할 수 있습니다.
선언형 document plan, 운영계획서 품질 프로필, 승인 양식 분석·적용·검증은
장르 판단과 실행 정책을 포함하므로 5.0부터 python-hwpx-automation이
소유합니다. 이 core 예제집에는 해당 응용 API의 실행 예제를 중복해서
싣지 않습니다.
설치, 최신 API, document-plan 및 form-fill의 end-to-end 예제는
python-hwpx-automation 사용 사례를
참고하세요. 4.x python-hwpx 호출을 옮기는 경우에는
5.0 마이그레이션 가이드에서 대응 경로를 먼저 확인하세요.