我刚刚通过 Heroku 上的 Node.js 完成了这项工作,并想发布,因为我必须克服几个小障碍。
// Spin up a new child_process to handle wkhtmltopdf.
var spawn = require('child_process').spawn;
// stdin/stdout, but see below for writing to tmp storage.
wkhtmltopdf = spawn('./path/to/wkhtmltopdf', ['-', '-']);
// Capture stdout (the generated PDF contents) and append it to the response.
wkhtmltopdf.stdout.on('data', function (data) {
res.write(data);
});
// On process exit, determine proper response depending on the code.
wkhtmltopdf.on('close', function (code) {
if (code === 0) {
res.end();
} else {
res.status(500).send('Super helpful explanation.');
}
});
res.header('Content-Type', 'application/octet-stream');
res.header('Content-Disposition', 'attachment; filename=some_file.pdf');
res.header('Expires', '0');
res.header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
// Write some markup to wkhtmltopdf and then end the process. The .on
// event above will be triggered and the response will get sent to the user.
wkhtmltopdf.stdin.write(some_markup);
wkhtmltopdf.stdin.end();
在 Heroku 的 Cedar-14 堆栈上,我无法让 wkhtmltopdf 写入标准输出。服务器总是以Unable to write to destination
. 诀窍是写入./.tmp
然后将写入的文件流式传输回用户 - 很简单:
wkhtmltopdf = spawn('./path/to/wkhtmltopdf', ['-', './.tmp/some_file.pdf']);
wkhtmltopdf.on('close', function (code) {
if (code === 0) {
// Stream the file.
fs.readFile('./.tmp/some_file.pdf', function(err, data) {
res.header('Content-Type', 'application/octet-stream');
res.header('Content-Disposition', 'attachment; filename=' + filename);
res.header('Expires', '0');
res.header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
res.send(data);
});
} else {
res.status(500).send('Super helpful explanation.');
}
});
res.header('Content-Type', 'application/octet-stream');
res.header('Content-Disposition', 'attachment; filename=' + filename);
res.header('Expires', '0');
res.header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');