一、代碼生成Word文檔的新星
Docxtemplater,是一款純JS生成Word文檔的開源工具,它可以通過簡單的代碼,生成格式不亂的文檔,解決了手動生成文檔的煩惱。其技術框架是Node.js和AngularJS,經過對IO和AngularJS的慢性能進行分析,並在代碼調整後進行測試,能夠完美地解決模板克隆、圖像插入、表格綁定、流程模板錄入等諸多問題。
二、使用方法
1、首先下載:
npm install docxtemplater // 安裝 const Docxtemplater = require('docxtemplater'); const fs = require('fs'); const path = require('path'); const PizZip = require('pizzip'); // ⚠️注意:需要安裝 pizzip-utils,否則會出現「PizZip is not defined」的問題 const pizzipUtil = require('pizzip/utils'); const templateStr = fs.readFileSync(path.resolve(__dirname, './test.docx'), 'binary'); const template = new Docxtemplater(new PizZip(templateStr)); const body = { name: '李**', age: 24, address: '深圳市南山區xx路xx號' } template.setData(body); template.render(); const result = template.getZip().generate({type: 'nodebuffer'}); fs.writeFileSync(path.resolve(__dirname, './result.docx'), result);
2、代碼解析:
上面這段代碼中,我們下載了docxtemplater,同時還需要把模板(test.docx)讀成二進制文件。如:const templateStr = fs.readFileSync(path.resolve(\_\_dirname, './test.docx'), 'binary')
。接着將模板放入docxtemplater中:const template = new Docxtemplater(new PizZip(templateStr));
。如果有數據需要更改,可通過template.setData(body)
方法來更改,最後執行渲染方法template.render()
,並通過getZip().generate({type: 'nodebuffer'})
來獲取二進制文件。當數據及Word模板輸入完成後,保存文件即可。
三、常見問題
1、中文亂碼問題:
npm -g install mammoth const mammoth = require('mammoth'); const html = fs.readFileSync('index.html', 'utf8'); mammoth.convertToHtml({ text: html }, {prettyPrint: true}) .then((result) => { // 讀取 Docx 模板並賦值以替換 {{ variable }} 代碼塊。不同的代碼塊用 {{# array }}...{{/ array }} 包裹 const docx = fs.readFileSync('./template.docx', 'binary'); template = new Docxtemplater(); template.loadZip(new PizZip(docx)); // 關鍵步驟:將 HTML 轉換後的結果賦值給模板中的一個變量。此處注意:千萬不要將如test
這種包裹在唯一的 標籤內 template.setData({ VARIABLE_NAME: result.value }); // 對應模板中包含類似這樣的 {{ VARIABLE_NAME }} 代碼塊,將其替換為上面所請求的數據 const buff = template.getZip().generate({ type: 'nodebuffer' }); fs.writeFileSync('test.docx', buff); }) .done();
2、將圖片插入到Word中:
const imageBuf = fs.readFileSync('test.png'); // 將圖片二進制讀入 Node.js 環境 const base64Img = `data:image/png;base64,${Buffer.from(imageBuf).toString('base64')}`; // 將圖片的結果轉換為Base64 doc.setData({ logo: base64Img }); // 將圖片編碼為base64並插入到文檔中
3、使用SVGs
// 1. 轉換 SVG 到 PNG const Rsvg = require('librsvg').Rsvg; const rsvg = new Rsvg(svgbuf); const pngbuf = rsvg.render({ format: 'png', width: dimensions.width, height: dimensions.height, }).data; // 2. 通過 Base64 數據插入到報告中 pngurl = 'data:image/png;base64,' + Buffer.from(pngbuf).toString('base64'); doc.setData({ logo: pngurl, });
四、結論
Docxtemplater給我們帶來了更多的文檔自動化生成可能性,同時還是一個完全開源的工具。現在使用Docxtemplater,您可以使用更加完整、自我定製的文檔,而不需要耗費大量工作時間。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/246245.html