use*_*892 5 html jquery princexml
我们正在使用 PrinceXML pdf 转换器包从 html 文件创建一个 pdf 文件。为了创建 html 文件,数据由服务器提供。在使用 jquery 的浏览器中,为 pdf 创建创建输入字符串(html 代码)。从浏览器接收到输入字符串后,服务器会创建一个 html 文件,该文件是princexml pdf 转换器的输入,用于创建 pdf。
Example for the input string
var sample = "<html>text</html>";//browser side
sample.html converted to sample.pdf //server side
Run Code Online (Sandbox Code Playgroud)
是否可以在不借助浏览器的情况下在服务器端执行相同的操作?
我知道这是一个有点老的问题,但自从我发现了一个很棒的模块后,我想与大家分享它。
名为Puppeteer的模块可以让你在 Headless 模式下运行 Chrome,并通过 API 与其交互。因此,现在您可以创建一个模板并通过 POST 调用获取该模板的占位符的值,并在服务器中动态生成 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;
.......
Run Code Online (Sandbox Code Playgroud)
现在,这个缓冲区基本上是一个二进制数据,你必须使用 Node.js 的文件模块将其写入文件中。
如需进一步解释,请查看解释链接
您可以使用无头浏览器,例如http://phantomjs.org/。这允许从渲染的页面生成图像。另请参阅http://www.lelesys.com/en/media/technology/phantomjs-as-screen-capture-to-generate-image-pdf-files.html
这允许您使用 jquery 和其他一切 - 因为它使用实际渲染引擎。我猜你甚至不需要princexml。还有一个有关捕获的常见问题解答页面:http://phantomjs.org/screen-capture.html