Skywalker
Skywalker

Reputation: 5194

Download a PDF automatically once its generated (Node, Express)

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.

Upvotes: 1

Views: 1357

Answers (1)

Syed Ayesha Bebe
Syed Ayesha Bebe

Reputation: 1448

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

Upvotes: 1

Related Questions