2

I have requirement that the HTML page needs to converted to PDF file and sending PDF as response to the api call in node. For that i am using wkhtmltopdf package to convert HTML to 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!') }); 

But it is creating out2.pdf in the project folder. but i am unable to get the out2.pdf as downloadable file in the browser instead i am getting below error

Error

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) 

any idea how to achieve my requirement

1 Answer 1

2

Try,

app.get('/getPDF',function(req, res){ res.setHeader('content-type', 'application/pdf'); wkhtmltopdf('<h1>Test</h1><p>Hello world</p>').pipe(res1).pipe(res); }); 

Pipe the result of wkhtmltopdf to response stream.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.