Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML and CSS to PDF in JavaScript

I know there are a bunch of libraries out there but none seem to exactly match my scenario. So I'm hoping to get some advice here...

technologies: I'm using Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support is IE8 and up, chrome, FF, and other modern browsers.

What I need to do is: have a "to pdf" button for the user to click, which would then convert a chunk of the DOM to pdf. This chunk of DOM's html is generated dynamically when the back-end makes API calls to another app. The CSS is static.

Other than these, I have a lot of freedom to do whatever I want, as long as I don't have to send clear text data to third parties and etc.

Any recommended ways to do it?


Update: looking into wkhtmltopdf

like image 792
Max Avatar asked Jul 27 '12 19:07

Max


People also ask

How do I export my HTML page as PDF using JavaScript?

Generate PDF using JavaScript The following example shows how to use the jsPDF library to generate PDF file using JavaScript. Specify the content in text() method of jsPDF object. Use the addPage() method to add new page to PDF. Use the save() method to generate and download PDF file.

Can you create a PDF in JavaScript?

We can start by introducing jsPDF, jsPDF is an open-source library for generating pdf using only JavaScript. It simply creates a pdf page and applies your formatting to the page. Note that we can change the presentation of the data inside the downloaded PDF file by editing the orientation and format.


1 Answers

Basically, this is what I ended up doing

console.log("before");
fs.writeFile(html_filename, html, function (err) {
  if (err) {res.writeHead(400); res.end("" + err); return;}

  console.log("wrote html fine; now converting");
  exec('wkhtmltopdf ' + html_filename + ' ' + pdf_filename, function (err, stdout, stderr) {
    if (err) {res.writeHead(400); res.end("" + err); return;}

    console.log("converted; now reading");
    fs.readFile(pdf_filename, function (err, data) {
      if (err) {res.writeHead(400); res.end("" + err); return;}

      console.log("read fine; now serving");
      res.writeHead(200, {"content-type" : "application/pdf"});
      res.end(data);
    });
  });
});

IMO it's a bit ugly as it requires making a file, then converting it, and then serving it, and finally delete the two. I suspect scalability problems here. Also wkhtmltopdf seems to not play nice with osx. There's no such problem on linux though.

like image 177
Max Avatar answered Oct 05 '22 13:10

Max