2017-08-07 72 views
0

我有要求HTML頁面需要轉換爲PDF文件併發送PDF作爲對節點中的api調用的響應。爲此,我使用wkhtmltopdf軟件包將HTML轉換爲PDF。如何發送一個文件作爲節點js中的響應下載

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

嘗試,

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的結果寫入response流。