Skip to content

Latest commit

 

History

History
180 lines (147 loc) · 2.96 KB

README_HEAD.md

File metadata and controls

180 lines (147 loc) · 2.96 KB

json-to-pdf

Generates PDF documents using PDF-Make and a basic JSON templating system similar to handlebars.

Usage

JSON templates are used which match the format of PDFMake document definition objects:

{
  "pageSize":"A4",
  "pageOrientation":"portrait",
  "pageMargins":[25, 25, 25, 25],
  "content":[
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Confectum ponit legam, perferendis nomine miserum, animi. Moveat nesciunt triari naturam.",
    {
      "text":"This text should appear on the second page",
      "pageBreak":"before"
    }
  ]
}

These templates can be expanded using data to create rich documents:

Template:

{
  "pageSize":"A4",
  "pageOrientation":"portrait",
  "pageMargins":[25, 25, 25, 25],
  "content":[
    "{{loremipsum}}",
    {
      "text":"{{page2.text}}",
      "pageBreak":"before"
    }
  ]
}

Data:

const data = {
  loremipsum: 'Lorem ipsum...naturam.',
  page2: {
    text: 'This text should appear on the second page'
  }
}

Code:

import * as jsonToPdf from 'json-to-pdf';

const pdfStream = jsonToPdf.renderPdfTemplate(template, data);
const fileStream = createWriteStream('./example.pdf');
pdfStream.pipe(fileStream);
pdfStream.end();

There are several helpers available to expand the JSON templates.

each

Repeats for each item in a supplied array

[
  "{{#each lines:line}}": {
    "text": "{{line}}"
  }
]

With data = ['a','b'] will inflate to:

[
  {
    "text": "a"
  },
  {
    "text": "b"
  }
]

if

Only includes value if supplied variable is truthy:

{
  "{{#if test}}": {
    "text": "{{text}}"
  }
}

With data = {test: true, text: 'show me'} will inflate to:

{
  "text": "show me"
}

unless

Like if, but will include value if the supplied variable is falsy:

{
  "{{#unless test}}": {
    "text": "{{text}}"
  }
}

With data = {test: true, text: 'don\'t show me'} will inflate to:

{}

equal

Only includes value if first supplied value equals the second:

{
  "{{#equal 6:{{test}}}}": {
    "text": "{{text}}"
  }
}

With data = {test: 6, text: 'show me'} will inflate to:

{
  "text": "show me"
}

notequal

Only includes value if first supplied value equals the second:

{
  "{{#notequal 6:{{test}}}}": {
    "text": "{{text}}"
  }
}

With data = {test: 6, text: 'don\'tshow me'} will inflate to:

{}

Fonts

As standard, the fonts available are:

  • Courier
  • Helvetica
  • Times
  • Symbol
  • ZapfDingbats

To use custom fonts, you can use the third argument of the renderPdfTemplate method to supply a font object:

const customFonts = {
  Roboto: {
    normal: './path/to/font/Roboto-Regular.ttf',
    bold: './path/to/font/Roboto-Medium.ttf',
    italics: './path/to/font/Roboto-Italic.ttf',
    bolditalics: './path/to/font/Roboto-MediumItalic.ttf'
  }
}

const pdfDoc = renderPdfTemplate(template, data, customFonts);