带有 EJS 模板的 HTML-PDF

html-pdf with ejs template

本文关键字:HTML-PDF EJS 带有      更新时间:2023-09-26

在我的应用程序中,当用户通过测试时,将自动生成一个文凭(pdf)。这是我通过使用 html-pdf node-module 来完成的,它检索 html 文件并将其制作成 pdf。

var fs = require('fs'),
    pdf = require('html-pdf'),
    path = require('path'),
    ejs = require('ejs');

var html = fs.readFileSync('./phantomScripts/certificate.html', 'utf8');
var options = { filename: 'businesscard.pdf', format: 'A4', orientation: 'portrait', directory: './phantomScripts/',type: "pdf" };
pdf.create(html, options).toFile(function(err, res) {
    if (err) return console.log(err);
         console.log(res);
    });

这种转换,从htmlpdf,效果很好,看起来非常好。现在我想要的是使template更加动态,这意味着根据用户的不同,他们的名字会出现在pdf中。

我曾经与ejs合作过生成电子邮件模板,所以我认为我的问题可以用它来解决,但如前所述,我没有在ejs上做太多工作,也无法弄清楚如何将data发送到我的ejs文件中?

ejs.renderFile('./path/to/template-file.ejs', {data : {firstname: 'Tom', lastname: 'Hanks'}, function(err, result) {
    // render on success
    if (result) {
       html = result;
    }
    // render or error
    else {
       res.end('An error occurred');
       console.log(err);
    }
});

我用上面的代码替换了我的var html = fs.readFileSync('./phantomScripts/certificate.html', 'utf8');代码,它按照我想要的方式工作。