const Docxtemplater = require('docxtemplater')
const JSZip = require('jszip')
const process = require('child_process')
注意: npm i jszip@2 (需要安装2.X版本的,不然会报错)
linux环境下:
linux下安装libreoffice:
yum install libreoffice
语法:
lilbreoffice --invisible --convert-to pdf model.docx --outdir 输出的目录(不需要带文件名)
条件判断语法:
let data = {
users: true
}
{#users}{内容}{/users}
{^users}{内容}{/users}
word/pdf生成过程代码:
let content=fs.readFileSync(path.join(__dirname,'/../../public/model/model.docx'),'binary')
let zip=newJSZip(content)
let doc=newDocxtemplater()
doc.loadZip(zip);
let data = {
'需要替换的字段名','替换的字段值'
}
doc.setData(data);
try{
doc.render();
} catch(error) {
var err={
message:error.message,
name:error.name,
stack:error.stack,
properties:error.properties,
}
console.log(JSON.stringify(err));
throw error;
}
let buf=doc.getZip().generate({type:'nodebuffer'});
const fileUrl='temporaryFile/'+uuid.v4()
fs.mkdir(path.join(__dirname,`/../../public/${fileUrl}`),async(err)=>{
console.log(err)
if(err) return
fs.writeFileSync(path.join(__dirname,`/../../public/${fileUrl}/${params.companyName}分析报告.docx`),buf);
let url={
fileUrl:path.join(__dirname,`/../../public/${fileUrl}/${params.companyName}分析报告.docx`),
savedUrl:`${fileUrl}/${params.companyName}分析报告.pdf`,
pdfUrl:path.join(__dirname,`/../../public/${fileUrl}`),
}
process.exec('libreoffice --invisible --convert-to pdf '+url.fileUrl+' --outdir '+url.pdfUrl, (error,stdout,stderr)=>{
if(error) {
console.error(`执行出错:${error}`);
return;
}
console.log(`stdout:${stdout}`);
console.log(`stderr:${stderr}`);
});
});