# -*- coding: utf-8 -*- """ HTML → HWP 변환기 v11 ✅ 이미지: sizeoption=0 (원본 크기) 또는 width/height 지정 ✅ 페이지번호: ctrl 코드 방식으로 수정 ✅ 나머지는 v10 유지 pip install pyhwpx beautifulsoup4 pillow """ from pyhwpx import Hwp from bs4 import BeautifulSoup, NavigableString import os, re # 스타일 그루핑 시스템 추가 from converters.style_analyzer import StyleAnalyzer, StyledElement from converters.hwp_style_mapping import HwpStyleMapper, DEFAULT_STYLES, ROLE_TO_STYLE_NAME from converters.hwpx_style_injector import HwpxStyleInjector, inject_styles_to_hwpx # PIL 선택적 import (이미지 크기 확인용) try: from PIL import Image HAS_PIL = True except ImportError: HAS_PIL = False print("[알림] PIL 없음 - 이미지 원본 크기로 삽입") class Config: MARGIN_LEFT, MARGIN_RIGHT, MARGIN_TOP, MARGIN_BOTTOM = 20, 20, 20, 15 HEADER_LEN, FOOTER_LEN = 10, 10 MAX_IMAGE_WIDTH = 150 # mm (최대 이미지 너비) ASSETS_PATH = r"D:\for python\geulbeot-light\geulbeot-light\output\assets" # 🆕 추가 class StyleParser: def __init__(self): self.style_map = {} # 스타일 매핑 (역할 → HwpStyle) self.sty_gen = None # 스타일 생성기 self.class_styles = { 'h1': {'font-size': '20pt', 'color': '#008000'}, 'h2': {'font-size': '16pt', 'color': '#03581d'}, 'h3': {'font-size': '13pt', 'color': '#228B22'}, 'p': {'font-size': '11pt', 'color': '#333333'}, 'li': {'font-size': '11pt', 'color': '#333333'}, 'th': {'font-size': '9pt', 'color': '#006400'}, 'td': {'font-size': '9.5pt', 'color': '#333333'}, 'toc-lvl-1': {'font-size': '13pt', 'font-weight': '900', 'color': '#006400'}, 'toc-lvl-2': {'font-size': '11pt', 'color': '#333333'}, 'toc-lvl-3': {'font-size': '10pt', 'color': '#666666'}, } def get_element_style(self, elem): style = {} tag = elem.name if hasattr(elem, 'name') else None if tag and tag in self.class_styles: style.update(self.class_styles[tag]) for cls in elem.get('class', []) if hasattr(elem, 'get') else []: if cls in self.class_styles: style.update(self.class_styles[cls]) return style def parse_size(self, s): m = re.search(r'([\d.]+)', str(s)) if s else None return float(m.group(1)) if m else 11 def parse_color(self, c): if not c: return '#000000' c = str(c).strip().lower() if re.match(r'^#[0-9a-fA-F]{6}$', c): return c.upper() m = re.search(r'rgb[a]?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)', c) return f'#{int(m.group(1)):02X}{int(m.group(2)):02X}{int(m.group(3)):02X}' if m else '#000000' def is_bold(self, style): return style.get('font-weight', '') in ['bold', '700', '800', '900'] # ═══════════════════════════════════════════════════════════════ # 번호 제거 유틸리티 # ═══════════════════════════════════════════════════════════════ NUMBERING_PATTERNS = { 'H1': re.compile(r'^(\d+)\.\s*'), # "1. " → "" 'H2': re.compile(r'^(\d+)\.(\d+)\s*'), # "1.1 " → "" 'H3': re.compile(r'^(\d+)\.(\d+)\.(\d+)\s*'), # "1.1.1 " → "" 'H4': re.compile(r'^[가-하]\.\s*'), # "가. " → "" 'H5': re.compile(r'^(\d+)\)\s*'), # "1) " → "" 'H6': re.compile(r'^\((\d+)\)\s*'), # "(1) " → "" 'H7': re.compile(r'^[①②③④⑤⑥⑦⑧⑨⑩]\s*'), # "① " → "" 'LIST_ITEM': re.compile(r'^[•\-○]\s*'), # "• " → "" } def strip_numbering(text: str, role: str) -> str: """ 역할에 따라 텍스트 앞의 번호/기호 제거 HWP 개요 기능이 번호를 자동 생성하므로 중복 방지 """ if not text: return text pattern = NUMBERING_PATTERNS.get(role) if pattern: return pattern.sub('', text).strip() return text.strip() # ═══════════════════════════════════════════════════════════════ # 표 너비 파싱 유틸리티 (🆕 추가) # ═══════════════════════════════════════════════════════════════ def _parse_width(width_str): """너비 문자열 파싱 → mm 값 반환""" if not width_str: return None width_str = str(width_str).strip().lower() # style 속성에서 width 추출 style_match = re.search(r'width\s*:\s*([^;]+)', width_str) if style_match: width_str = style_match.group(1).strip() # px → mm (96 DPI 기준) px_match = re.search(r'([\d.]+)\s*px', width_str) if px_match: return float(px_match.group(1)) * 25.4 / 96 # mm 그대로 mm_match = re.search(r'([\d.]+)\s*mm', width_str) if mm_match: return float(mm_match.group(1)) # % → 본문폭(170mm) 기준 계산 pct_match = re.search(r'([\d.]+)\s*%', width_str) if pct_match: return float(pct_match.group(1)) * 170 / 100 # 숫자만 있으면 px로 간주 num_match = re.search(r'^([\d.]+)$', width_str) if num_match: return float(num_match.group(1)) * 25.4 / 96 return None def _parse_align(cell): """셀의 정렬 속성 파싱""" align = cell.get('align', '').lower() if align in ['left', 'center', 'right']: return align style = cell.get('style', '') align_match = re.search(r'text-align\s*:\s*(\w+)', style) if align_match: return align_match.group(1).lower() return None def _parse_bg_color(cell): """셀의 배경색 파싱""" bgcolor = cell.get('bgcolor', '') if bgcolor: return bgcolor if bgcolor.startswith('#') else f'#{bgcolor}' style = cell.get('style', '') bg_match = re.search(r'background(?:-color)?\s*:\s*([^;]+)', style) if bg_match: color = bg_match.group(1).strip() if color.startswith('#'): return color rgb_match = re.search(r'rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)', color) if rgb_match: r, g, b = int(rgb_match.group(1)), int(rgb_match.group(2)), int(rgb_match.group(3)) return f'#{r:02X}{g:02X}{b:02X}' return None class HtmlToHwpConverter: def __init__(self, visible=True): self.hwp = Hwp(visible=visible) self.cfg = Config() self.sp = StyleParser() self.base_path = "" self.is_first_h1 = True self.image_count = 0 self.table_widths = [] # 🆕 표 열 너비 정보 저장용 self.style_map = {} # 역할 → 스타일 이름 매핑 self.sty_path = None # .sty 파일 경로 def _mm(self, mm): return self.hwp.MiliToHwpUnit(mm) def _pt(self, pt): return self.hwp.PointToHwpUnit(pt) def _rgb(self, c): c = c.lstrip('#') return self.hwp.RGBColor(int(c[0:2],16), int(c[2:4],16), int(c[4:6],16)) if len(c)>=6 else self.hwp.RGBColor(0,0,0) def _setup_page(self): try: self.hwp.HAction.GetDefault("PageSetup", self.hwp.HParameterSet.HSecDef.HSet) s = self.hwp.HParameterSet.HSecDef s.PageDef.LeftMargin = self._mm(self.cfg.MARGIN_LEFT) s.PageDef.RightMargin = self._mm(self.cfg.MARGIN_RIGHT) s.PageDef.TopMargin = self._mm(self.cfg.MARGIN_TOP) s.PageDef.BottomMargin = self._mm(self.cfg.MARGIN_BOTTOM) s.PageDef.HeaderLen = self._mm(self.cfg.HEADER_LEN) s.PageDef.FooterLen = self._mm(self.cfg.FOOTER_LEN) self.hwp.HAction.Execute("PageSetup", s.HSet) except: pass def _create_header(self, right_text=""): print(f" → 머리말 생성: {right_text if right_text else '(초기화)'}") try: self.hwp.HAction.GetDefault("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterStyle", 0) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterCtrlType", 0) self.hwp.HAction.Execute("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HAction.Run("ParagraphShapeAlignRight") self._set_font(9, False, '#333333') if right_text: self.hwp.insert_text(right_text) self.hwp.HAction.Run("CloseEx") except Exception as e: print(f" [경고] 머리말: {e}") # ═══════════════════════════════════════════════════════════════ # 꼬리말 - 페이지 번호 (수정) # ═══════════════════════════════════════════════════════════════ def _create_footer(self, left_text=""): print(f" → 꼬리말: {left_text}") # 1. 꼬리말 열기 self.hwp.HAction.GetDefault("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterStyle", 0) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterCtrlType", 1) self.hwp.HAction.Execute("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) # 2. 좌측 정렬 + 제목 8pt self.hwp.HAction.Run("ParagraphShapeAlignLeft") self._set_font(8, False, '#666666') self.hwp.insert_text(left_text) # 3. 꼬리말 닫기 self.hwp.HAction.Run("CloseEx") # 4. 쪽번호 (우측 하단) self.hwp.HAction.GetDefault("PageNumPos", self.hwp.HParameterSet.HPageNumPos.HSet) self.hwp.HParameterSet.HPageNumPos.DrawPos = self.hwp.PageNumPosition("BottomRight") self.hwp.HAction.Execute("PageNumPos", self.hwp.HParameterSet.HPageNumPos.HSet) def _new_section_with_header(self, header_text): """새 구역 생성 후 머리말 설정""" print(f" → 새 구역 머리말: {header_text}") try: self.hwp.HAction.Run("BreakSection") self.hwp.HAction.GetDefault("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterStyle", 0) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterCtrlType", 0) self.hwp.HAction.Execute("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HAction.Run("SelectAll") self.hwp.HAction.Run("Delete") self.hwp.HAction.Run("ParagraphShapeAlignRight") self._set_font(9, False, '#333333') self.hwp.insert_text(header_text) self.hwp.HAction.Run("CloseEx") except Exception as e: print(f" [경고] 구역 머리말: {e}") # 스타일 적용 관련 (🆕 NEW) def _load_style_template(self, sty_path: str): """ .sty 스타일 템플릿 로드 HWP에서 스타일 불러오기 기능 사용 """ if not os.path.exists(sty_path): print(f" [경고] 스타일 파일 없음: {sty_path}") return False try: # HWP 스타일 불러오기 self.hwp.HAction.GetDefault("StyleTemplate", self.hwp.HParameterSet.HStyleTemplate.HSet) self.hwp.HParameterSet.HStyleTemplate.filename = sty_path self.hwp.HAction.Execute("StyleTemplate", self.hwp.HParameterSet.HStyleTemplate.HSet) print(f" ✅ 스타일 템플릿 로드: {sty_path}") return True except Exception as e: print(f" [경고] 스타일 로드 실패: {e}") return False def _apply_style_by_name(self, style_name: str): """ 현재 문단에 스타일 이름으로 적용 텍스트 삽입 후 호출 """ try: # 현재 문단 선택 self.hwp.HAction.Run("MoveLineBegin") self.hwp.HAction.Run("MoveSelLineEnd") # 스타일 적용 self.hwp.HAction.GetDefault("Style", self.hwp.HParameterSet.HStyle.HSet) self.hwp.HParameterSet.HStyle.StyleName = style_name self.hwp.HAction.Execute("Style", self.hwp.HParameterSet.HStyle.HSet) # 커서 문단 끝으로 self.hwp.HAction.Run("MoveLineEnd") except Exception as e: print(f" [경고] 스타일 적용 실패 '{style_name}': {e}") def _build_dynamic_style_map(self, elements: list): """HTML 분석 결과 기반 동적 스타일 매핑 생성 (숫자)""" roles = set(elem.role for elem in elements) # 제목 역할 정렬 (H1, H2, H3...) title_roles = sorted([r for r in roles if r.startswith('H') and r[1:].isdigit()], key=lambda x: int(x[1:])) # 기타 역할 other_roles = [r for r in roles if r not in title_roles] # 순차 할당 (개요 1~10) self.style_map = {} style_num = 1 for role in title_roles: if style_num <= 10: self.style_map[role] = style_num style_num += 1 for role in other_roles: if style_num <= 10: self.style_map[role] = style_num style_num += 1 print(f" 📝 동적 스타일 매핑: {self.style_map}") return self.style_map def _set_font(self, size=11, bold=False, color='#000000'): self.hwp.set_font(FaceName='맑은 고딕', Height=size, Bold=bold, TextColor=self._rgb(color)) def _set_para(self, align='justify', lh=170, left=0, indent=0, before=0, after=0): acts = {'left':'ParagraphShapeAlignLeft','center':'ParagraphShapeAlignCenter', 'right':'ParagraphShapeAlignRight','justify':'ParagraphShapeAlignJustify'} if align in acts: self.hwp.HAction.Run(acts[align]) try: self.hwp.HAction.GetDefault("ParagraphShape", self.hwp.HParameterSet.HParaShape.HSet) p = self.hwp.HParameterSet.HParaShape p.LineSpaceType, p.LineSpacing = 0, lh p.LeftMargin = self._mm(left) p.IndentMargin = self._mm(indent) p.SpaceBeforePara = self._pt(before) p.SpaceAfterPara = self._pt(after) p.BreakNonLatinWord = 0 self.hwp.HAction.Execute("ParagraphShape", p.HSet) except: pass def _set_cell_bg(self, color): try: self.hwp.HAction.GetDefault("CellBorderFill", self.hwp.HParameterSet.HCellBorderFill.HSet) p = self.hwp.HParameterSet.HCellBorderFill p.FillAttr.type = self.hwp.BrushType("NullBrush|WinBrush") p.FillAttr.WinBrushFaceStyle = self.hwp.HatchStyle("None") p.FillAttr.WinBrushHatchColor = self._rgb('#000000') p.FillAttr.WinBrushFaceColor = self._rgb(color) p.FillAttr.WindowsBrush = 1 self.hwp.HAction.Execute("CellBorderFill", p.HSet) except: pass def _underline_box(self, text, size=14, color='#008000'): try: self.hwp.HAction.GetDefault("TableCreate", self.hwp.HParameterSet.HTableCreation.HSet) t = self.hwp.HParameterSet.HTableCreation t.Rows, t.Cols, t.WidthType, t.HeightType = 1, 1, 0, 0 t.WidthValue, t.HeightValue = self._mm(168), self._mm(10) self.hwp.HAction.Execute("TableCreate", t.HSet) self.hwp.HAction.GetDefault("InsertText", self.hwp.HParameterSet.HInsertText.HSet) self.hwp.HParameterSet.HInsertText.Text = text self.hwp.HAction.Execute("InsertText", self.hwp.HParameterSet.HInsertText.HSet) self.hwp.HAction.Run("TableCellBlock") self.hwp.HAction.GetDefault("CharShape", self.hwp.HParameterSet.HCharShape.HSet) self.hwp.HParameterSet.HCharShape.Height = self._pt(size) self.hwp.HParameterSet.HCharShape.TextColor = self._rgb(color) self.hwp.HAction.Execute("CharShape", self.hwp.HParameterSet.HCharShape.HSet) self.hwp.HAction.GetDefault("CellBorder", self.hwp.HParameterSet.HCellBorderFill.HSet) c = self.hwp.HParameterSet.HCellBorderFill c.BorderTypeTop = self.hwp.HwpLineType("None") c.BorderTypeRight = self.hwp.HwpLineType("None") c.BorderTypeLeft = self.hwp.HwpLineType("None") self.hwp.HAction.Execute("CellBorder", c.HSet) self.hwp.HAction.GetDefault("CellBorder", self.hwp.HParameterSet.HCellBorderFill.HSet) c = self.hwp.HParameterSet.HCellBorderFill c.BorderColorBottom = self._rgb(color) c.BorderWidthBottom = self.hwp.HwpLineWidth("0.4mm") self.hwp.HAction.Execute("CellBorder", c.HSet) self.hwp.HAction.Run("Cancel") self.hwp.HAction.Run("CloseEx") self.hwp.HAction.Run("MoveDocEnd") except: self._set_font(size, True, color) self.hwp.insert_text(text) self.hwp.BreakPara() def _update_header(self, new_title): """머리말 텍스트 업데이트""" try: # 기존 머리말 편집 모드로 진입 self.hwp.HAction.GetDefault("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterStyle", 2) # 편집 모드 self.hwp.HParameterSet.HHeaderFooter.HSet.SetItem("HeaderFooterCtrlType", 0) self.hwp.HAction.Execute("HeaderFooter", self.hwp.HParameterSet.HHeaderFooter.HSet) # 기존 내용 삭제 self.hwp.HAction.Run("SelectAll") self.hwp.HAction.Run("Delete") # 새 내용 삽입 self.hwp.HAction.Run("ParagraphShapeAlignRight") self._set_font(9, False, '#333333') self.hwp.insert_text(new_title) self.hwp.HAction.Run("CloseEx") except Exception as e: print(f" [경고] 머리말 업데이트: {e}") def _insert_heading(self, elem): lv = int(elem.name[1]) if elem.name in ['h1','h2','h3'] else 1 txt = elem.get_text(strip=True) st = self.sp.get_element_style(elem) sz = self.sp.parse_size(st.get('font-size','14pt')) cl = self.sp.parse_color(st.get('color','#008000')) if lv == 1: if self.is_first_h1: self._create_header(txt) self.is_first_h1 = False else: self._new_section_with_header(txt) self._set_para('left', 130, before=0, after=0) self._underline_box(txt, sz, cl) self.hwp.BreakPara() self._set_para('left', 130, before=0, after=15) self.hwp.BreakPara() elif lv == 2: self._set_para('left', 150, before=20, after=8) self._set_font(sz, True, cl) self.hwp.insert_text("■ " + txt) self.hwp.BreakPara() elif lv == 3: self._set_para('left', 140, left=3, before=12, after=5) self._set_font(sz, True, cl) self.hwp.insert_text("▸ " + txt) self.hwp.BreakPara() def _insert_paragraph(self, elem): txt = elem.get_text(strip=True) if not txt: return st = self.sp.get_element_style(elem) sz = self.sp.parse_size(st.get('font-size','11pt')) cl = self.sp.parse_color(st.get('color','#333333')) self._set_para('justify', 170, left=0, indent=3, before=0, after=3) if elem.find(['b','strong']): for ch in elem.children: if isinstance(ch, NavigableString): if str(ch).strip(): self._set_font(sz,False,cl); self.hwp.insert_text(str(ch)) elif ch.name in ['b','strong']: if ch.get_text(): self._set_font(sz,True,cl); self.hwp.insert_text(ch.get_text()) else: self._set_font(sz, self.sp.is_bold(st), cl) self.hwp.insert_text(txt) self.hwp.BreakPara() def _insert_list(self, elem): lt = elem.name for i, li in enumerate(elem.find_all('li', recursive=False)): st = self.sp.get_element_style(li) cls = li.get('class', []) txt = li.get_text(strip=True) is_toc = any('toc-' in c for c in cls) if 'toc-lvl-1' in cls: left, bef = 0, 8 elif 'toc-lvl-2' in cls: left, bef = 7, 3 elif 'toc-lvl-3' in cls: left, bef = 14, 1 else: left, bef = 4, 2 pf = f"{i+1}. " if lt == 'ol' else "• " sz = self.sp.parse_size(st.get('font-size','11pt')) cl = self.sp.parse_color(st.get('color','#333333')) bd = self.sp.is_bold(st) if is_toc: self._set_para('left', 170, left=left, indent=0, before=bef, after=1) self._set_font(sz, bd, cl) self.hwp.insert_text(pf + txt) self.hwp.BreakPara() else: self._set_para('justify', 170, left=left, indent=0, before=bef, after=1) self._set_font(sz, bd, cl) self.hwp.insert_text(pf) self.hwp.HAction.Run("ParagraphShapeIndentAtCaret") self.hwp.insert_text(txt) self.hwp.BreakPara() def _insert_table(self, table_elem): """HTML 테이블 → HWP 표 변환 (내용 기반 열 너비 계산 + HWPX 후처리용 저장)""" # ═══ 1. 테이블 구조 분석 ═══ rows_data = [] cell_styles = {} occupied = {} max_cols = 0 col_widths = [] # 열 너비 (mm) - HTML에서 지정된 값 #