0

I am using node, express and ejs to build a web app and I would like to convert a page to a pdf on button click.

The route definition for the request created for the button is as follows:

const gp = require('./generatePDF');

app.get('/pdf', gp.generatePDF)

The function is handled like so:

const generatePDF = (request, response) => {
   /* do some stuff to generate content on the ejs page */
   response.render('pages/pagetoconverttoPDF');

}

module.exports = {
  generatePDF,
}

What would be the best way to download / view this page as a pdf?

NicLovin
  • 317
  • 3
  • 20

2 Answers2

0

If you want to embed a pdf in html, you can either use the <embed> tag or <iframe> tag. More about that here: How to display PDF file in HTML?

However, if you are looking to serve the pdf standalone, you can static serve the pdf and browsers will render it, along with options to download and print.

Kenneth Lew
  • 217
  • 3
  • 7
0

I figured out how to accomplish this (generating a pdf from html) using ejs.renderFile as follows:

const generatePDF = (request, response) => {
  var dataToDisplay = request.body;
  ejs.renderFile('./views/pages/admin/employeedatapdf.ejs', {d: dataToDisplay}, (err, data) => {
        if (err) {
          console.log(err);
          response.send(err);
        } else {
          let options = {
            "height": "11.25in",
            "width": "8.5in",
            "header": {
                "height": "20mm"
            },
            "footer": {
                "height": "20mm",
            },
          };
          let filename = "generatedpdf.pdf";
          pdf.create(data).toFile(filename, function (err, data) {
            let fileloc = 'full path' + filename;
            if (err) {
              response.send(err);
              console.log("error occured")
            } else {
              fs.readFile(fileloc, function (err, data) {
                console.log("generating pdf");
                response.contentType("application/pdf");
                response.send(data);
              });
            }
          })
        }
      });
}
NicLovin
  • 317
  • 3
  • 20