1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| from docxtpl import DocxTemplate, InlineImage from docx.shared import Pt import os# 数据准备 context = { 'title': '项目报告', 'user': { 'name': '张三', 'email': 'zhangsan@example.com' }, 'tasks': [ {'description': '需求分析', 'deadline': '2023-12-31'}, {'description': '代码开发', 'deadline': '2024-01-15'} ], 'special_note': '请尽快完成初稿评审', 'name': '项目经理', 'date': '2025-08-04', 'employees': [ {'name': '张三', 'department': '研发部', 'hire_date': '2020-01-15', 'salary': 15000}, {'name': '李四', 'department': '市场部', 'hire_date': '2019-05-20', 'salary': 12000}, {'name': '王五', 'department': '财务部', 'hire_date': '2021-03-10', 'salary': 18000}, ], "node_config": { "ip1": { "check_hostnamectl": { "hostname": "node01", "operating_system": "Tencent tlinux 2.6", "kernel": "Linux 5.4.119-1-tlinux4-0010", "architecture": "x86-64" }, "check_cpu_metrics": { "cpu_num": "4C", "model_name": "Intel(R) Xeon(R) CPU E5-2670 v3 @ 2.30GHz" }, "check_physical_cpu": { "physical_cpu": "4C" }, "check_physical_mem": { "physical_mem": "8G" }, "check_nvme": { "nvme_size": "1.80TB*4" } }, "ip2": { "check_hostnamectl": { "hostname": "node02", "operating_system": "Tencent tlinux 2.6", "kernel": "Linux 5.4.119-1-tlinux4-0010", "architecture": "x86-64" }, "check_cpu_metrics": { "cpu_num": "4C", "model_name": "Intel(R) Xeon(R) CPU E5-2670 v3 @ 2.30GHz" }, "check_physical_cpu": { "physical_cpu": "4C" }, "check_physical_mem": { "physical_mem": "8G" }, "check_nvme": { "nvme_size": "1.80TB*4" } }, "ip3": { "check_hostnamectl": { "hostname": "node03", "operating_system": "Tencent tlinux 2.6", "kernel": "Linux 5.4.119-1-tlinux4-0010", "architecture": "x86-64" }, "check_cpu_metrics": { "cpu_num": "4C", "model_name": "Intel(R) Xeon(R) CPU E5-2670 v3 @ 2.30GHz" }, "check_physical_cpu": { "physical_cpu": "4C" }, "check_physical_mem": { "physical_mem": "8G" }, "check_nvme": { "nvme_size": "1.80TB*4" } } }, "test_vm": "AAA" } # 加载模板 doc = DocxTemplate("template.docx") # 创建InlineImage对象并添加到context context['my_image'] = InlineImage(doc, 'test.png', width=Pt(100)) # Pt(100) 表示一个 100 磅 的长度。 # 在排版和印刷领域,1 磅 (Pt) = 1/72 英寸 ≈ 0.0353 厘米 ≈ 0.3527 毫米 1 英寸 = 2.54 厘米 context['my_image_2'] = InlineImage(doc, 'test.png', width=Pt(300)) # 渲染Word文档 doc.render(context) output_docx = "output.docx" doc.save(output_docx) # 转换为PDF def convert_to_pdf(docx_path): pdf_path = docx_path.replace('.docx', '.pdf') cmd = f"libreoffice --headless --convert-to pdf {docx_path} --outdir ." os.system(cmd) return pdf_path pdf_output = convert_to_pdf(output_docx) print(f"PDF生成成功: {pdf_output}")
|