在调试这个问题的过程中,我发现了以下几点:
PDFKit 不需要从文件中读取信息。它还将接受一个Buffer
doc.image(myBuffer); // You don't have to use a path string
当将文件直接传递到响应中时,手动调用response.end()
如果文件已经关闭将会导致问题
doc.pipe(res); // Pipe document directly into the response
doc.end(); // When called, this ends the file and the response
// res.end(); <-- DON'T call res.end()
// The response was already closed by doc.end()
return;
Request是一个超级有用的NodeJS库,可以扁平化回调树
更新的代码:
var express = require('express'),
request = require('request'),
pdfDocument = require('pdfkit');
// Start Express
var app = express();
// Use JSON in POST body
app.use(express.json());
// Setup POST response
app.post('/post_pdf', function(req, res) {
// Create PDF
var doc = new pdfDocument();
// Write headers
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Access-Control-Allow-Origin': '*',
'Content-Disposition': 'attachment; filename=Untitled.pdf'
});
// Pipe generated PDF into response
doc.pipe(res);
// Process image
request({
url: 'http://dummyimage.com/640.jpeg',
encoding: null // Prevents Request from converting response to string
}, function(err, response, body) {
if (err) throw err;
// Inject image
doc.image(body); // `body` is a Buffer because we told Request
// to not make it a string
doc.end(); // Close document and, by extension, response
return;
});
});