我要求HTML页面需要转换为PDF文件并发送PDF作为对节点中api调用的响应。为此,我使用wkhtmltopdf包将HTML转换为PDF。
app.js
var express = require("express");
var http= require("http");
var app = express();
var wkhtmltopdf = require('wkhtmltopdf');
var fs = require('fs');
var res1 = fs.createWriteStream('out2.pdf');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.get('/getPDF',function(req, res){
wkhtmltopdf('<h1>Test</h1><p>Hello world</p>').pipe(res1);
res.setHeader('content-type', 'application/pdf');
res.send(res1);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
但它正在项目文件夹中创建out2.pdf。但是我无法在浏览器中将out2.pdf作为可下载文件而不是错误
错误
Example app listening on port 3000!
events.js:163
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (_stream_writable.js:191:12)
at WriteStream.Writable.write (_stream_writable.js:238:5)
at Socket.ondata (_stream_readable.js:555:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at Pipe.onread (net.js:563:20)
任何想法如何实现我的要求
答案 0 :(得分:1)
尝试,
addView
将app.get('/getPDF',function(req, res){
res.setHeader('content-type', 'application/pdf');
wkhtmltopdf('<h1>Test</h1><p>Hello world</p>').pipe(res1).pipe(res);
});
的结果传输到wkhtmltopdf
流。