table + list
This commit is contained in:
@@ -23,17 +23,26 @@ def _render_inline_tokens(p, tokens, doc, images_dir, style_reg):
|
||||
elif token["type"] == "strong":
|
||||
run = p.add_run()
|
||||
run.bold = True
|
||||
run.text = token["children"][0]["raw"] if token["children"] else ""
|
||||
# Обрабатываем children внутри этого же run
|
||||
for child in token["children"]:
|
||||
if child["type"] == "text":
|
||||
run.text += child["raw"]
|
||||
elif token["type"] == "emphasis":
|
||||
run = p.add_run()
|
||||
run.italic = True
|
||||
run.text = token["children"][0]["raw"] if token["children"] else ""
|
||||
for child in token["children"]:
|
||||
if child["type"] == "text":
|
||||
run.text += child["raw"]
|
||||
elif token["type"] == "link":
|
||||
run = p.add_run()
|
||||
run.text = token["children"][0]["raw"] if token["children"] else ""
|
||||
run.font.color.rgb = style_reg.get_color("LinkColor")
|
||||
elif token["type"] == "softbreak" or token["type"] == "linebreak":
|
||||
p.add_run().add_break()
|
||||
elif token["type"] == "html":
|
||||
if "<br" in token["raw"]:
|
||||
p.add_run().add_break()
|
||||
elif token["type"] == "image":
|
||||
# Если image внутри параграфа — вызываем обработчик
|
||||
handle_image(token, doc, images_dir, style_reg)
|
||||
|
||||
@register_handler("paragraph")
|
||||
@@ -48,37 +57,58 @@ def handle_image(node: dict, doc, images_dir: Path, style_reg):
|
||||
alt = node.get("alt", "")
|
||||
img_path = images_dir / src
|
||||
if img_path.exists():
|
||||
logger.debug(f"Обработка изображения: {img_path}, exists: {img_path.exists()}")
|
||||
p = doc.add_paragraph()
|
||||
run = p.add_run()
|
||||
logger.debug(f"Добавлен параграф: {len(doc.paragraphs)} до add_picture")
|
||||
try:
|
||||
run.add_picture(str(img_path), width=Inches(5))
|
||||
logger.debug("add_picture успешно выполнен")
|
||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при добавлении изображения {img_path}: {e}")
|
||||
doc.add_paragraph(f"[Изображение не загружено: {src}]")
|
||||
return
|
||||
|
||||
logger.debug(f"После add_picture: {len(doc.paragraphs)} параграфов")
|
||||
if alt:
|
||||
try:
|
||||
cap_p = doc.add_paragraph(alt, style="Caption")
|
||||
logger.debug(f"Добавлена подпись: {alt}, всего параграфов: {len(doc.paragraphs)}")
|
||||
except KeyError:
|
||||
cap_p = doc.add_paragraph(alt)
|
||||
style_reg.apply_style(cap_p.style, "Caption")
|
||||
logger.debug(f"Добавлена подпись без стиля: {alt}")
|
||||
else:
|
||||
doc.add_paragraph(f"[Изображение не найдено: {src}]")
|
||||
|
||||
logger.error(f"[Изображение не найдено: {src}]")
|
||||
|
||||
@register_handler("list")
|
||||
def handle_list(node: dict, doc, images_dir: Path, style_reg):
|
||||
ordered = node.get("ordered", False)
|
||||
for item in node["children"]:
|
||||
p = doc.add_paragraph(style="List Number" if ordered else "List Bullet")
|
||||
for child in item["children"]:
|
||||
if child["type"] == "text":
|
||||
p.add_run(child["raw"])
|
||||
_render_inline_tokens(p, item["children"], doc, images_dir, style_reg)
|
||||
|
||||
|
||||
@register_handler("table")
|
||||
def handle_table(node: dict, doc, images_dir: Path, style_reg):
|
||||
rows_data = node["children"] # [header_row, row1, row2...]
|
||||
if not rows_data:
|
||||
return
|
||||
|
||||
header_row = rows_data[0]["children"]
|
||||
body_rows = rows_data[1:]
|
||||
|
||||
num_cols = len(header_row)
|
||||
table = doc.add_table(rows=1, cols=num_cols)
|
||||
table.style = "Table Grid" # можно настроить в YAML
|
||||
|
||||
# Заполняем заголовок
|
||||
hdr_cells = table.rows[0].cells
|
||||
for i, cell_data in enumerate(header_row):
|
||||
if i < num_cols:
|
||||
cell = hdr_cells[i]
|
||||
_render_inline_tokens(cell.paragraphs[0], cell_data["children"], doc, images_dir, style_reg)
|
||||
|
||||
# Заполняем тело
|
||||
for row_data in body_rows:
|
||||
cells = table.add_row().cells
|
||||
for i, cell_data in enumerate(row_data["children"]):
|
||||
if i < num_cols:
|
||||
cell = cells[i]
|
||||
_render_inline_tokens(cell.paragraphs[0], cell_data["children"], doc, images_dir, style_reg)
|
||||
|
||||
Reference in New Issue
Block a user