Most used approach to generate a PDF report (JavaScript, node.js)?

Erica Xu picture Erica Xu · Jun 26, 2013 · Viewed 41k times · Source

Can anyone who worked on something like this describe the general process? I'm very confused right now. By report I mean a visually appealing document with logo, tables, headers and footers, and the data will be retrieved dynamically.

The approaches I looked at are:

  1. Use a server side library (node.js module) that generates the PDF. Send the string representation as response with Content-Type: application/pdf. Problem: I chose PDFKit, but it doesn't work and no content shows up at all. It uses PDF 1.3, which is old.

  2. Generate PDF on client side. Problem: Most popular library seems to be jsPDF, but it's not very capable of producing sophisticated-looking documents.

  3. Write template in PDF source code and fill in the data on server side. Problem: The encoding is weird, for example if I just do doc.text("1"), a lot of unrecognizable characters appear for just the string "1". I'm very confused about this.

Finally, it'll be super helpful if anyone provides a link that can help me understand the encoding! It's super confusing to me.

Any experience with similar tasks is much appreciated!

Answer

Peter Lyons picture Peter Lyons · Jun 26, 2013

I haven't personally done this, but the first thing I would try would be:

  1. On the server side dynamically build the appropriate HTML document and CSS
  2. Use phantomJS to render that document
  3. Tell phantomJS to convert that document to PDF, saved in a temp file
  4. Send the PDF back as the HTTP response by writing the temp PDF file to the response body
  5. Delete the temp file

If you are struggling with content-type, content-disposition, etc, you shouldn't have to worry about that if you have a valid pdf file on disk and just write that data to the HTTP response. With the right headers, you should be able to ask the browser to either display the PDF or treat it as a file to be saved as a download.