如何使用Node.js将jsreport渲染保存到文件?

7

我是新手,正在学习node.js和jsreport。我想要做的是使用node.js在内存中创建PDF文件,然后将其保存到磁盘上。由于它将作为AWS Lambda函数运行,所以需要它是独立的。

var fs = require('fs');
require("jsreport").render("<h1>Hi there!</h1>").then(function(out) {
    //pipe pdf with "Hi there!"
    fs.writeFile('C:\\helloworld.pdf', out, function (err) {
        if (err) return console.log(err);
        console.log('Hello World > helloworld.txt');
    });
fs.close();
    console.log("The End");
});

尽管这段代码可以运行,但生成的PDF文件无法在Adobe Reader中打开,因此我认为输出文件不是有效的PDF格式。
要实现这一功能,需要先安装npm包jsreport。

请注意,.writeFile 是异步的。 - Daniel A. White
1个回答

6

据我从jsreport网站上了解到(尽管我无法验证,因为他们网站上的所有示例都对我无效),out不是渲染(PDF)数据,而是包含流等内容的对象。

这让我相信这可能会奏效:

require("jsreport").render("<h1>Hi there!</h1>").then(function(out) {
  out.result.pipe(fs.createWriteStream('c:\\helloworld.pdf'));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接