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.

Community
  • 1
  • 1
Skywalker
  • 4,984
  • 16
  • 57
  • 122
  • 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. – Reporter Jul 04 '17 at 11:21
  • @reporter can you give an example? Would the browser side automatically handle it or do I need some code client side? – Skywalker Jul 04 '17 at 11:22
  • Maybe https://stackoverflow.com/questions/11971918/how-do-i-set-a-mime-type-before-sending-a-file-in-node-js answers your question. – Reporter Jul 04 '17 at 11:25
  • Check this too => https://stackoverflow.com/questions/31264629/download-generated-pdf-using-node-html-pdf-module – David R Jul 04 '17 at 11:26

1 Answers1

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

Reporter
  • 3,897
  • 5
  • 33
  • 47
Syed Ayesha Bebe
  • 1,797
  • 1
  • 15
  • 26
  • A question for better understanding: Where is the object `response` declared. Maybe there is a mistake and you meant `res` instead of `response`. – Reporter Jul 05 '17 at 09:00