dataclear / json-to-pdf

Generates PDF documents using PDF-Make and a basic JSON templating system

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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);

API Documentation

Functions

functionifyHeaderFooter(node)DynamicContent | Content

Finds fixed formula value within object and replaces with a function that replaces the fixed value with a live function

getObjectValue(obj, path)*

Extracts a value from an object based on a string or array of paths Inflates a set of fixed formula names with processed values

getTemplateLiteral(val)string

Extracts a literal value by removing double curly braces

isArrayFunction(element)boolean

Takes a string template and replaces template literals with the corresponding value from the "data" object

nestedKeyValue(obj, key)*

Recursively iterates through object to find given key and returns value

inflateLiterals(template, data, settings)string

Takes a string template and replaces template literals with the corresponding value from the "data" object

processDataNode(val, data, settings)unknown

Recursively moves through an object or individual element to replace literals, inflate data and process functions

processFunction(functionKey, object, data, settings)unknown

Used to process array and logic functions, returns inflated data or undefined

renderPdfTemplate(docDefinition, data)stream

Inflates a json template into a PDFMake document definition, then renders the definition to a PDF file

functionifyHeaderFooter(node) ⇒ DynamicContent | Content

Finds fixed formula value within object and replaces with a function that replaces the fixed value with a live function

Kind: global function
Category: Helpers
Since: v0.0.1

Param Type Description
node DynamicContent | Content

The current object node

Example

processDataNode({test: '{{a}}'}, {a: 'b'}, {})    //=> {test: 'b'}

getObjectValue(obj, path) ⇒ *

Extracts a value from an object based on a string or array of paths Inflates a set of fixed formula names with processed values

Kind: global function
Category: Helpers
Since: v0.0.1

Param Type Description
obj object

The object to search

path string | Array.<string>

The path to traverse

Example

getObjectValue({a: {b: {c: 1}}}, 'a.b.c')    //=> 1
getObjectValue({a: {b: {c: 1}}}, 'a.b.c.d')  //=> undefined
getObjectValue({a: {b: {c: 1}}}, 'a..b..c')  //=> undefined
getObjectValue({a: {b: {c: 1}}}, 'c')        //=> undefined
getObjectValue({a: {b: {c: [1,2,3]}}}, 'a.b.c.1')        //=> 2
getObjectValue({a: {b: {c: 6}}}, 'a.b.c.toFixed(2)')        //=> '6.00'

getTemplateLiteral(val) ⇒ string

Extracts a literal value by removing double curly braces

Kind: global function
Category: Helpers
Since: v0.0.1

Param Type Description
val string

The string to process

Example

getTemplateLiteral('test')        //=> ''
getTemplateLiteral('{{test}}')    //=> 'test'
getTemplateLiteral('{{{test}}}')  //=> '{test}'
getTemplateLiteral('{{}}test')    //=> ''
getTemplateLiteral('{{}}')        //=> ''

isArrayFunction(element) ⇒ boolean

Takes a string template and replaces template literals with the corresponding value from the "data" object

Kind: global function
Category: Helpers
Since: v0.0.1

Param Type Description
element object

The object to look for array function key

Example

isArrayFunction({a: 1, '{{#each a:b}}': {b: 2}, c: 3})    //=> true
isArrayFunction({a: 1, b: 2, c: 3})    //=> false

nestedKeyValue(obj, key) ⇒ *

Recursively iterates through object to find given key and returns value

Kind: global function
Category: Helpers
Since: v0.0.1

Param Type Description
obj *

The object to search

key *

The key to find

Example

nestedKeyValue({a: {b: {c: 1}}}, 'c')  //=> 1
nestedKeyValue({a: {b: {c: 1}}}, 'd')  //=> undefined
nestedKeyValue({a: {b: {c: 1}}}, 'b')  //=> {c: 1}

inflateLiterals(template, data, settings) ⇒ string

Takes a string template and replaces template literals with the corresponding value from the "data" object

Kind: global function
Category: Main
Since: v0.0.1

Param Type Description
template string

The string to search and replace within

data object

The data to search for replacement values

settings Settings

Settings to control how they are

Example (Ignores plain text)

inflateLiterals('test', {}, {})    //=> 'test'

Example (Replaces one or more placeholders)

inflateLiterals('here is a {{val}}', {val: 'test'}, {})    //=> 'here is a test'
inflateLiterals('here is another {{val}}{{val}}', {val: 'test'}, {})    //=> 'here is a testtest'

Example (Can extract positional values from arrays)

inflateLiterals('here is a {{val.1}}', {val: ['test1', 'test2']}, {})    //=> 'here is a test2'

Example (Or will comma separate full arrays)

inflateLiterals('here is a {{val}}', {val: ['test1', 'test2]}, {})    //=> 'here is a test1, test2'

processDataNode(val, data, settings) ⇒ unknown

Recursively moves through an object or individual element to replace literals, inflate data and process functions

Kind: global function
Category: Main
Since: v0.0.1

Param Type Description
val unknown

The current object node

data object

The data to search for replacement values

settings Settings

Settings to control how they are

Example

processDataNode({test: '{{a}}'}, {a: 'b'}, {})    //=> {test: 'b'}

processFunction(functionKey, object, data, settings) ⇒ unknown

Used to process array and logic functions, returns inflated data or undefined

Kind: global function
Category: Main
Since: v0.0.1

Param Type Description
functionKey string

The function to perform

object object

The object to be inflated by the function

data object

The data used to inflate the object

settings Settings

Settings to control how items are processed

Example

processFunction('{{#each items:item}}', {text: '{{item}}'}, {items: ['a', 'b', 'c']}, {})    //=> '[{text: 'a'},{text: 'b'},{text: 'c'}]'

renderPdfTemplate(docDefinition, data) ⇒ stream

Inflates a json template into a PDFMake document definition, then renders the definition to a PDF file

Kind: global function
Category: Main
Since: v0.0.1

Param Type Description
docDefinition ExpandableDocDefinition

The JSON string or object definition to inflate

data object

The data to use for inflated values




© 2023 Dataclear Ltd
Documented by jsdoc-to-markdown.

About

Generates PDF documents using PDF-Make and a basic JSON templating system

License:Other


Languages

Language:TypeScript 93.9%Language:JavaScript 6.1%