Looking for a way to create a design-heavy, data-driven, beautifully styled PDF report—server-side with similar tools to what you are already using on the front-end? Stop your Google search. You’ve come to the right place. I was in the same boat as you a few months ago while helping a client with this exact problem. In order to accomplish this feat, I developed a four-step solution using Puppeteer, D3, and handlebars. In this post, I’ll give you step by step instructions on creating server-side pdf reports. Let’s dive in.
An example of a PDF page generated using this method.
In this post, we’ll cover:
Because we’re using a template framework to access standard web technologies along with Puppeteer to manage the PDF, we’ll need to think about these things during development:
For this example, let’s assume we already have the base of our project up and running Node/Express, and some type of ORM and DB solutions. We’re all set to feed our sweet, sweet data into a report.
HTML templating framework from the Mustache family. This allows for Partial templating (fancy talk for components) and custom and built-in helper functionality to expand on our logic.
npm install handlebars
Example using partials and built-in blocks
{{#each poleComparison as |page|}}
<div class="page">
{{#each page.pairs as |polePair|}}
{{> comparison-header polePair=polePair }}
<div class="comparison-tables">
{{> comparison-body polePair=polePair }}
</div>
{{/each}}
{{> footer @root }}
</div>
{{/each}}
A node library that will provide us access to a chrome headless instance for generating the PDF based on our compiled Handlebars templates.
npm install puppeteer
A list of use cases:
D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.
<script src="https://d3js.org/d3.v5.min.js"></script>
#javascript #server-side #d3.js #js #handlebars #puppeteer #server-side development