我有一个 Node 服务,可以从 API 获取 pdf 并提供该 pdf。
当我 curl 或直接打开 API 时,我确实看到了正确的 pdf。
但是当我从 Node 应用程序提供它时,我得到一个空的 pdf。
这是我的代码中执行 pdf 渲染的部分。
} else if (options.type === 'pdf') {
res.writeHead(200, {'content-type' : 'application/pdf', 'content-disposition': 'attachment; filename=invoice.pdf'});
res.end(data.invoice);
我已经console.log'ed data.invoice 知道它是正确的东西。
typeof(data.invoice) 给出字符串;但我也尝试过 res.end(new Buffer(data.invoice));这也不起作用。
这是我获取数据的代码部分
var http_options = {
method : options.method
, host : Config.API.host
, path : options.path
, port : Config.API.port
, headers : options.headers
};
var req = http.request(http_options, function (response) {
var raw_response = "";
response.on('data', function (response_data) {
raw_response += response_data.toString();
});
response.on('end', function () {
if (response.statusCode !== 200) {
cb(raw_response);
} else {
cb(false, raw_response);
}
});
});
req.setTimeout(timeout, function () {
req.abort();
cb("API connection timed out");
});
req.on('error', function (error) {
cb("API error while requesting for " + options.path + '\n' + error + '\n' + "http options: " + JSON.stringify(http_options)
});
req.end();
最佳答案
当您接收 PDF 时,toString()
和串联很可能会损坏它。尝试将 raw_response
写入文件(您可以使用 writeFileSync()
,因为这只是一次性测试)并与同一 PDF 进行逐字节比较使用curl 检索。
请注意,如果字符串转换过程已损坏它,则在发送之前尝试将其转换回缓冲区将无济于事。您必须从头到尾将整个事情保持为缓冲区。
关于Node.js:提供动态 pdf,结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12207840/