obj2pdf v1.5.0
obj2pdf
A server-side npm package to convert a JSON object to a PDF.
Table of contents
- Dependencies
- Installation
- Usage
- How to use the base64 PDF data string
- Generated PDF Sample
- Generated PDF Specs
Dependencies
This package is dependent on the pdfmake package.
Installation
npm install obj2pdf --saveor
yarn add obj2pdfUsage
- Import the package
Typescript:
import * as obj2pdf from 'obj2pdf';or
Javascript:
const obj2pdf = require('obj2pdf');- Now, simply use the exposed
.generatePDFfunction which takes in a valid JSON object as the parameter. It returns a base64 encoded string containing the PDF data.
Provide a heading property if needed to generate a heading for the PDF which would be center aligned(see sample image below).
Each property(except heading) in the JSON corresponds a "Section" in the generated PDF (for eg. Employee Details, Employer Details in the below JSON example).
The value of each property(Section) in the JSON can be one of object, string or number.
An object value would specify sub-sections within a section(works atmost with 1 level nesting).
A string/number value prints it as-is below the Section(no sub-sections).
const inputJSON = {
"heading": "PDF Heading",
"Employee Details": {
"First name": "John",
"Last name": "Doe",
"Gender": "Male"
},
"Employer Details": {
"Name": "Google",
"Location": "London"
},
"Currency": "£",
"Amount": 10
};
obj2pdf.generatePDF(inputJSON)
.then((pdfData) => {
// do something with pdfData
})
.catch((err) => {
console.log(`error caught : ${err}`);
});How to use the base64 PDF data string
The base64 encoded string response should look something like
data:application/pdf;base64,JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwogIC9Q...This can then be used on client-side as the value to a href attribute of a HTML anchor element.
<a href="data:application/pdf;base64,JVBERi0xLjc…">
Open PDF
</a>Generated PDF Sample
If you used the JSON above, the generated PDF data upon viewing should look like
Generated PDF Specs
- Fonts being used are Roboto regular/bold
- PDF heading is 15px, center aligned, bold.
- Section heading is 12px, bold.
- Sub-section heading is 10px, bold.
- Section/Sub-section value is 8px.