Skip to main content

Build quick report on nodejs server side with EJS template and ChartJS

· 3 min read
Niko
Software Engineer @ Naver

Build quick report on nodejs server side with EJS template and ChartJS

Concepts:

  1. Define report template like as HTML view by EJS syntax
  2. Draw chart by ChartJS into HTML view template
  3. Using EJS engine to render HTML view from HTML template
  4. Create new Chromium instance as headless browser using Puppeteer to render HTML template
  5. Create PDF from headless browser view
  6. Create report blob and free resources.

Install

nodejs-pdf-report

npm install --save nodejs-pdf-report

Supports

  • Base html template with EJS engine.
  • Embeded Chart.js v2.9.3.
  • Server side without browser.

Examples

  • Import from package
   import { HtmlReport, ReportOptions } from "nodejs-pdf-report";
  • Define configures
const reportOptions: ReportOptions = {
title: "Test report with chartjs",
useChartJs: true,
pdfOptions: {
margin: {
top: "100px",
bottom: "200px",
right: "30px",
left: "30px",
},
},
template: "template.ejs",
headerTemplate: "header-template.ejs",
footerTemplate: "footer-template.ejs",
styles: [
"styles.css"
],
scripts: [
"utils.js",
"index.js",
],
data: {
users: [
{
name: "Luong Phung",
},
{
name: "Jasmine",
},
],
title: "Test report with chartjs",
author: "Luong Phung",
time: "2020",
},
};
  • Create pdf file as buffer
  const htmlReport = new HtmlReport();
const reportPdf = await htmlReport.createPdf(reportOptions);
const savePath = path.resolve("./chartjs_report.pdf");
fs.writeFileSync(savePath, reportPdf, "binary");
  • Check you report file "chartjs_report.pdf"

Screens shot

output1.png

API references

PdfOptions

NametypedefaultDescription
scalenumber1Scale of the webpage rendering
printBackgroundbooleanfalsePrint background graphics.
landscapebooleanfalsePaper orientation
formatstring"A4"Page format as : "Letter" "A0" ... "A4" ...
margin{top, bottom, left, right}0Page margin as number of pixels

ReportOptions

NametypedefaultDescription
titlestringnullPdf report title
useChartJsbooleanfalseUse chartjs as default
pdfOptionsPdfOptionsnullany
templatestringnullTemplate path
footerTemplatestringnullFooter template path
headerTemplatestringnullHeader template path
stylesstring[][]Style paths
scriptsstring[][]Scripts paths
dataobjectReport data

4. References