呈现具有可变数据的HTML并转换为PDF [英] Render HTML with variable data and convert to PDF

查看:39
本文介绍了呈现具有可变数据的HTML并转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html模板页面,我想通过EJS填写数据,然后将这个完整的页面传递给PDF创建者;最终结果是页面上填充了我的数据的漂亮PDF版本.

I have a html template page that I want to fill in data with via EJS, after which I want to pass this completed page to a PDF creator; the end result being a nice PDF version of my page filled with my data.

对于PDF创建者,我正在使用NPM html-pdf 进行转换.问题是,我不知道如何用数据呈现页面,自动保存页面,然后将完成的页面传递给PDF创建者,因为PDF创建者仅接受服务器路径到保存的网页.

For the PDF creator, I'm using the NPM html-pdf do the conversion. Problem is, I don't know of any way I can render the page with my data, save it automatically, then pass the finished page to the PDF creator, since the PDF creator only accepts server paths to saved webpages.

也许我正在以错误的方式进行处理,但是下面是我目前所拥有的,但公认的并不多.在正确方向上的任何帮助将不胜感激.

Maybe I'm approaching this the wrong way, but below is what I currently have which admittedly isn't a lot. Any help in the right direction would be appreciated.

var renderPDF = function() {
  var pdf = require('html-pdf');
  // pulls html page
  var html = fs.readFileSync('views/assets/html/render.ejs', 'utf8');
  var options = {};
  // creates views/test.pdf
  pdf.create(html, options).toFile('views/test.pdf', function(err, res) {
    if (err) return console.log(err);
    console.log(res);
  });
};
// this is how I usually render ejs files with data
response.render('assets/html/render.ejs', {myDataOject});
// start the conversion
renderPDF();

推荐答案

以下是解决方案.我们先阅读EJS的模板文件,然后将其编译为PDF格式.

Here is the solution. We read EJS's template file then compile it to PDF format.

index.js

var fs = require('fs');
var ejs = require('ejs');
var pdf = require('html-pdf')
var compiled = ejs.compile(fs.readFileSync(__dirname + '/template.html', 'utf8'));
var html = compiled({ title : 'EJS', text : 'Hello, World!' });

pdf.create(html).toFile('./result.pdf',() => {
    console.log('pdf done')
})

template.html

template.html

<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <p><%= text %></p>
</body>

这篇关于呈现具有可变数据的HTML并转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆