如何使用 Docxtemplater 将生成的 Word 文档转换为 PDF?

Tea*_*ete 5 pdf ms-word node.js typescript angular

大家好,我目前正在使用 Angular.js 开发一个网站,我想根据用户的输入生成一个 Word 文档,效果很好!

问题是我想让用户预览并将 Word 文档下载为 PDF 文档因此我尝试更改 MIME 类型并更改 SaveAs 格式,但它不起作用

我也尝试过使用包将单词更改为 PDF,但到目前为止没有运气

这是保存生成的word文档的代码

this.loadFile("/assets/document/Template.docx", function(
  error,
  content
) {
  if (error) {
   console.log("Load file error: ",error) ;
  }
  var zip = new PizZip(content);
  var doc = new Docxtemplater().loadZip(zip);
doc.setData({
  tag: "Hello"
});
try {
   
        doc.render();
      } catch (error) {
       console.log(error)
      }
       var out = doc.getZip().generate({
        type: "blob",
        mimeType:
        //"application/pdf;charset=utf-8"
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      }); //Output the document using Data-URI

     saveAs(out, "GeneratedDocx.docx");
    });
  }

Run Code Online (Sandbox Code Playgroud)

我仍然无法使用 out 变量使用 docxConverter 或任何其他包进行转换

小智 0

我在使用 docxtemplater 时在项目中遇到了类似的问题。以下事情对我有用。我使用 docx-pdf npm 包将其转换为 pdf。 https://www.npmjs.com/package/docx-pdf

    var doc = new Docxtemplater()
    .attachModule(imageModule)
    .loadZip(zip)
    .setData(finalData)
    .render();

  var buffer = await doc.getZip().generate({ type: "nodebuffer" });

  fs.writeFile(outputPath, buffer, function (err, result) {
    if (err) {
      return next(new ErrorHandler(err.response, 401));
    }
  });
  
  docxConverter(outputPath,'./output.pdf',function(err,result){
    if(err){
      console.log(err);
    }
    console.log('result'+result);
  });
Run Code Online (Sandbox Code Playgroud)

转换不是那么准确,但它在很多情况下对我有用。还有一些可用的 API,但它们免费提供的次数有限。