我知道这是一个有点老的问题,但是因为我找到了一个很棒的模块,所以我想与大家分享它。
名为Puppeteer的模块,可以让你在 Headless 模式下运行 Chrome并通过 API 与之交互。因此,现在您可以创建一个模板并通过 POST 调用获取该模板的占位符的值,并在 server 中动态生成 PDF。
我创建了一个小型 POC,这里是它的链接:Demo-Puppeteer
让我在这里做一点解释:
...........
const content = await compile(templateName, data);
/***
* Launched the headless chrome in memory.
*/
const browser = await puppeteer.launch();
/***
* Created a new page(tab)
*/
const page = await browser.newPage();
/***
* Set the content of the new page
*/
await page.setContent(content, { waitUntil: 'networkidle0' });
/***
* Telling chrome to emulate screen i.e how the page looks if
* it would have been rendered in the normal browser.
*/
await page.emulateMedia('screen');
const byteArray = await page.pdf({
format: "A4",
landscape: true,
scale: 1.29,
printBackground: true
});
const buffer = Buffer.from(byteArray, 'binary');
/**
* We don't need the acknowledgement of this call that is the
* reason we are not waiting for this call to return.
*/
browser.close();
return buffer;
.......
现在,这个缓冲区基本上是一个二进制数据,你必须使用 Node.js 的文件模块将它写入一个文件中。
如需进一步解释,请查看Exlpanation Link