node.js - jsreportonline - 如何保存为 pdf 文件

标签 node.js request jsreport

我终于得到了 jsreportonline 至少生成了文件。这是我的代码:

request.post({
  url: 'https://xxxx.jsreportonline.net/api/report',
  json: true,
  headers: {
    "Content-Type": "application/json",
    "Authorization" : "Basic "+new Buffer(username:pwd).toString('base64')
  },
  body: {
    "template" : {'shortid" : xxxxx},
    "data" : xxxx,
  }
}, function(err, res, body) {
  **** HERE IS THE PROBLEM ****
});

我不知道如何将变量“body”中存储的 pdf 输出写入文件。我试过:

var pbs = fs.createWriteStream('./report.pdf');
pbs.write(body);
pbs.end();

我已经尝试过:

var pbs = fs.createWriteStream('./report.pdf', {defaultEncoding: 'binary'});

...但 PDF 文件始终无法正确显示。我知道代码有效,因为我可以在调用中设置一个选项:

"options" : {
  "reports" : {"save" : true}
}

...报告已保存到我的 jsreportonline 帐户并呈现良好。

感谢您的帮助。

最佳答案

您不应该使用回调,而应该直接通过管道传送从 request.post 返回的流。请参阅文档 here 。示例:

var request = require('request')
var fs = require('fs')

request.post({
  url: 'https://xxx.jsreportonline.net/api/report',
  json: true,
  headers: {
    'Content-Type': 'application/json',
    'Authorization' : 'Basic '+new Buffer('xxx:yyy').toString('base64')
  },
  body: {
    'template' : {'shortid" : xxxxx},
    'data' : xxxx,
 }
}).on('error', function (err) {
  console.log(err)
}).pipe(fs.createWriteStream('report.pdf'))  

关于node.js - jsreportonline - 如何保存为 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39406297/

相关文章:

html - Bootstrap 网格格式 - 不同的设备

javascript - 我无法使用 multer 和express 上传图像

javascript - 使用 nodejs 阻止 API 调用

ios - AFNetworking 自定义 API 管理器

post - Retrofit 2.0 无法将请求正文转换为 JSON

node.js - Node Jsreport 语法错误 : Identifier 'err' has already been declared

node.js - 如何向除发布者之外的所有订阅者发送消息,发布者也是同一 rabbitMQ 队列上的监听器

postgresql - 改进 postgresql select 请求执行时间

node.js - AspNetCore NodeServices 抛出 NodeInitationException

javascript - 是否可以将 Handlebars 表达式值传递给子表达式?