from pathlib import Path from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Cm, Pt, RGBColor from PIL import Image, ImageDraw out_dir = Path(__file__).resolve().parent img_path = out_dir / "demo-image.png" image = Image.new("RGB", (420, 160), "white") d = ImageDraw.Draw(image) d.rectangle([10, 10, 410, 150], outline="black", width=2) d.text((30, 60), "DOCX embedded image", fill="black") image.save(img_path) doc = Document() section = doc.sections[0] section.top_margin = Cm(2) section.bottom_margin = Cm(2) section.left_margin = Cm(2) section.right_margin = Cm(2) section.header.paragraphs[0].text = "页眉:Word/HTML 双向转换测试" section.footer.paragraphs[0].text = "页脚:保留页眉页脚测试" style = doc.styles["Normal"] style.font.name = "Microsoft YaHei" style.font.size = Pt(12) h = doc.add_heading("Word 转 HTML 测试文件", level=1) h.alignment = WD_ALIGN_PARAGRAPH.CENTER p = doc.add_paragraph() p.paragraph_format.first_line_indent = Cm(0.74) p.paragraph_format.line_spacing = 1.5 p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY r = p.add_run("这是一段测试文本:") r.font.size = Pt(12) r.font.color.rgb = RGBColor(0, 0, 0) r = p.add_run("加粗") r.bold = True r = p.add_run("、斜体") r.italic = True r = p.add_run("、下划线") r.underline = True r = p.add_run("、删除线") r.font.strike = True r = p.add_run("、红色文字。") r.font.color.rgb = RGBColor(192, 0, 0) for text in ["一级项目 1", "一级项目 2"]: doc.add_paragraph(text, style="List Bullet") for text in ["编号项目 1", "编号项目 2"]: doc.add_paragraph(text, style="List Number") table = doc.add_table(rows=3, cols=3) table.style = "Table Grid" for i, row in enumerate(table.rows): for j, cell in enumerate(row.cells): cell.text = f"R{i+1}C{j+1}" # Merge first row cells 1-2 merged = table.cell(0, 0).merge(table.cell(0, 1)) merged.text = "合并单元格" p = doc.add_paragraph("下方是一张嵌入图片:") p.alignment = WD_ALIGN_PARAGRAPH.LEFT doc.add_picture(str(img_path), width=Cm(8)) doc.add_page_break() doc.add_paragraph("第二页内容,用于测试分页。") doc.save(out_dir / "demo.docx") print(out_dir / "demo.docx")