import fs from "fs"; import PizZip from "pizzip"; import Docxtemplater from "docxtemplater"; import ImageModule from "docxtemplater-image-module-free"; import { HEALTH_IMAGE_MARKERS, patchTemplateXml, } from "../src/server/reportService/docxReportBuilder.js"; const zip = new PizZip(fs.readFileSync("templates/health-report-template.docx")); let xml = zip.file("word/document.xml").asText(); console.log( "p open/close", (xml.match(/)/g) || []).length, (xml.match(/<\/w:p>/g) || []).length, ); const wt = []; xml.replace(/]*)?>([\s\S]*?)<\/w:t>/g, (_, t) => { wt.push(t); return _; }); const bad = wt.filter( (t) => (t.match(/{/g) || []).length !== (t.match(/}/g) || []).length, ); console.log("unbalanced w:t", bad.length); bad.slice(0, 10).forEach((t) => console.log(JSON.stringify(t.slice(0, 120)))); xml = patchTemplateXml(xml, HEALTH_IMAGE_MARKERS); zip.file("word/document.xml", xml); const empty = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64", ); const imageModule = new ImageModule({ centered: true, getImage: () => empty, getSize: () => [100, 60], }); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, modules: [imageModule], nullGetter: () => "", }); doc.render({ farm_name: "测试", field_id: "F1", create_time: "t", source_datetime: "d", turbine_count: "1", valid_turbine_count: "1", turbine_types: "x", overall_score: "80", system_score: "70", component_score: "70", "structure_score/未评估": "70", excellent_count: "1", good_count: "0", fair_count: "0", poor_count: "0", overall_level_text: "良", main_level: "良", level_distribution_text: "x", overall_summary_text: "x", focus_engine_list: "A", chart_fig1: "a", chart_fig2: "b", turbine_rows: [ { index: 1, engine_name: "A1", machine_type: "T", overall: "80", level: "良", system: "70", component: "70", structure: "70", yaw: "1", pitch: "1", mcs: "1", hpu: "1", generator: "1", converter: "1", gearbox: "1", shaft: "1", rotor: "1", tower: "1", }, ], focus_rows: [ { index: 1, engine_name: "A1", machine_type: "T", overall: "80", level: "中", system: "70", component: "70", structure: "70", low_item: "系统健康", }, ], turbine_trends: [ { engine_title: "A1 趋势", charts: [ { chart_title: "综合健康评分趋势图", trend_image: "a" }, { chart_title: "结构健康趋势图", trend_image: "a" }, ], }, ], }); console.log("docxtemplater compile+render ok");