我试图让jsreport写入可写流,如果我在可写流中打印缓冲区,我会得到一个pdf desciption,但如果我保存到pdf文件,我会收到pdf文件已损坏的错误。
function streamtoPdf(template, callback) {
var ws = new stream;
ws.writable = true;
ws.bytes = 0;
var decoder = new StringDecoder('utf8');
ws.write = function (buf) {
ws.bytes += buf.length;
console.log(buf);
ws.pdf += decoder.write(buf);
}
ws.end = function (buf) {
if (arguments.length) ws.write(buf);
ws.writable = false;
// console.log(ws.pdf)
callback(ws.pdf);
}
renderPDF(template, ws);
}
//create a pdf from a template.
function renderPDF(template, writableStream) {
jsreport.render("<h1>Hello world</h1>").then(function (out) {
out.result.pipe(writableStream);
}).catch(function (e) {
res.end(e.message);
});
}
如果我将jsreport与out.result.pipe(res)
一起使用,我会使用 hello world 获得pdf,但是使用我的方法时出现错误。有人看到我做错了什么吗?
答案 0 :(得分:1)
试试这个!
var jsreport = require('jsreport'),
fs = require('fs'),
Stream = require('stream');
function streamtoPdf(template, callback) {
var ws = new Stream.Writable;
var bufs = []
ws.write = function(buf) {
bufs.push(buf);
}
ws.end = function(buf) {
if (arguments.length) {
bufs.push(buf)
}
ws.pdf = Buffer.concat(bufs);
ws.writable = false;
callback(ws.pdf);
}
renderPDF(template, ws);
}
//create a pdf from a template.
function renderPDF(template, writableStream) {
jsreport.render("<h1>Hello world</h1>").then(function(out) {
out.result.pipe(writableStream);
}).catch(function(e) {
res.end(e.message);
});
}
streamtoPdf('', function(wStream) {
//console.log(wStream)
fs.writeFile('myPdf', wStream, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
第一个问题是“ws.pdf”最初是未定义的,因此导致pdf中出现意外的“未定义”字并导致损坏! 无论如何,真正的问题是你在回调中有一个缓冲区并且你编码为utf8所以即使pdf被创建它也是空白的!