1

I am using following node module html-pdf to convert html to pdf. I have successfully converted html to pdf but I am having trouble downloading the file once it has been created.

Code to generate PDF:

var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html', 'utf8'); var options = { format: 'Letter' }; pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) { if (err) return console.log(err); console.log(res); // { filename: '/app/businesscard.pdf' } }); 

How can I either open the PDF within the browser for the user to see or automatically download the pdf within the browser without the user having to go through another step.

4
  • 1
    The response -which will send back to the browser- must be contain the pdf document itself and header the mime type application/pdf. When browsers detects this mime type they starts the configured action for this datatype. Commented Jul 4, 2017 at 11:21
  • @reporter can you give an example? Would the browser side automatically handle it or do I need some code client side? Commented Jul 4, 2017 at 11:22
  • Maybe stackoverflow.com/questions/11971918/… answers your question. Commented Jul 4, 2017 at 11:25
  • Check this too => stackoverflow.com/questions/31264629/… Commented Jul 4, 2017 at 11:26

1 Answer 1

1

I just made some changes to your code.In this code I create a route. Whenever you made a request with this route it converts HTML file to PDF and creating a pdf file into your directory from where you are executing. And at the sametime it displays the html file in browser with downloading option also. Hope this helps for you. And here is my code.

var express=require('express'); var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('C:/Users/nodejs/tasks/file.html', 'utf8'); var options = { format: 'Letter' }; var app=express(); app.get('/file',function(request,response) { pdf.create(html, options).toFile('./businesscaw.pdf', function(err, res) { if (err) return console.log(err); console.log(res); var file= 'C:/Users/nodejs/tasks/businesscaw.pdf'; fs.readFile(file,function(err,data){ response.contentType("application/pdf"); response.send(data); }); }); }); app.listen(3000,function(){ console.log("Server listening on port http://loalhost:3000"); }); 

Output: See the output in browser like : localhost:3000/file

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

1 Comment

A question for better understanding: Where is the object response declared. Maybe there is a mistake and you meant res instead of response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.