실전 예제
다음 예제는 python-hwpx의 주요 API를 조합해 실제 시나리오를 해결하는 방법을 보여 줍니다. examples/ 디렉터리에 포함된 샘플 HWPX 파일(FormattingShowcase.hwpx)을 기준으로 작성되었으며, 해당 파일은 저장소를 직접 클론했을 때만 사용할 수 있습니다. PyPI로 설치했다면 보유 중인 HWPX 문서를 사용하거나, hwpx.templates.blank_document_bytes()로 임시 문서를 생성해 실습하세요.
Python 블록 판정: 실행 분류 ledger가 이 current manual의 모든 Python 블록을 동결합니다. 독립 실행 예제 표시가 없는 블록은 기존 입력 파일이나 앞 문맥이 필요한 조각입니다.
0. 빈 문서를 생성해 실습 환경 만들기
독립 실행 예제 — 내장 템플릿 바이트만 사용합니다.
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("playground.hwpx")
1. 보고서 템플릿에 표와 개체 추가하기
from hwpx import HwpxDocument
document = HwpxDocument.open("examples/FormattingShowcase.hwpx")
section = document.sections[-1]
# 머리글 문단을 추가하고 강조 스타일을 적용합니다.
headline = document.add_paragraph(
"분기별 요약",
section=section,
style=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()/cell_map으로 병합 구조를 확인하거나, 필요 시 병합을 해제할 수 있습니다.
header_map = table.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.shapes.add_rectangle(9000, 3500, fill_color="#FFF2CC", section=section)
shape.resize(9600, 3500)
# 컨트롤도 전용 헬퍼로 넣습니다. 저수준 doc.shapes.add_control은 필수 하위 요소를
# 만들지 않아, 호출자가 채우지 않으면 저장이 거부되거나 한컴이 열지 못하는 문서가 됩니다.
document.refs.add_bookmark("quarterly-summary", paragraph=headline)
document.save("examples/FormattingShowcase-updated.hwpx")
2. 단락 삭제와 섹션 관리
from hwpx import HwpxDocument
document = HwpxDocument.open("examples/FormattingShowcase.hwpx")
section = document.sections[0]
# 빈 단락 제거. 구역의 첫 문단은 구역 설정(용지·여백·단)을 담고 있으므로 남깁니다.
# 글이 없어도 표나 개체가 든 문단은 빈 문단이 아닙니다.
for para in list(section.paragraphs)[1:]:
if not para.text.strip() and not para.tables and not para.shapes:
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("examples/cleaned.hwpx")
3. 하이라이트와 주석을 포함한 텍스트 보고서 생성하기
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 형식에 따라 자리표시자로 치환됩니다.
4. 특정 태그를 검색해 요약 정보 만들기
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)를 모두 지원하므로 문서 내부 구조를 탐색하거나 특정 개체만 선별하는 자동화 스크립트를 쉽게 작성할 수 있습니다.
5. 선언형 document plan과 양식 워크플로
선언형 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 마이그레이션 가이드에서 대응 경로를 먼저 확인하세요.
6. 언어마다 다른 글꼴을 쓰는 글자 모양 만들기
doc.styles.ensure_run(font_by_lang=...)은 한글·영문처럼 언어마다 다른 글꼴을 쓰는 글자 모양을 만듭니다. 글꼴 id는 언어 블록마다 따로 매겨지므로, 각 글꼴을 그 언어 블록에 등록하고 그 블록의 id로 참조합니다. 이름을 대지 않은 언어와 크기·색 같은 다른 값은 기준 글자 모양을 따르고, 기준 글자 모양 자체는 바뀌지 않습니다. 저장 뒤에 ZIP 안의 header.xml을 고칠 필요가 없습니다.
독립 실행 예제 — 빈 문서만 사용합니다.
from hwpx import HwpxDocument
document = HwpxDocument.new()
# 한글은 함초롬바탕, 영문은 Arial. 나머지 언어는 기준 글자 모양의 글꼴 그대로다.
mixed = document.styles.ensure_run(
size=11,
font_by_lang={"HANGUL": "함초롬바탕", "LATIN": "Arial"},
)
document.add_paragraph("").add_run("2026년 사업 Report", char_pr_id_ref=mixed)
# 같은 요청은 같은 글자 모양을 다시 쓴다.
again = document.styles.ensure_run(size=11, font_by_lang={"HANGUL": "함초롬바탕", "LATIN": "Arial"})
assert again == mixed
print(document.styles.font_face(mixed, "HANGUL"), document.styles.font_face(mixed, "LATIN"))
document.save("mixed-fonts.hwpx")
font와 함께 주면 font를 모든 언어에 먼저 적용하고 font_by_lang이 댄 언어만 바꿉니다. 언어 이름은 HANGUL·LATIN·HANJA·JAPANESE·OTHER·SYMBOL·USER(대소문자 무시)이고, 그 밖의 이름이나 빈 글꼴 이름은 아무 글꼴도 등록하기 전에 HwpxValueError로 거부합니다.