https://github.com/navjotdhanawat/dynamic-html-pdf
Create dynamic PDF from HTML template using handlebars
https://github.com/navjotdhanawat/dynamic-html-pdf
content dynamic dynamic-html-pdf handlebar-template html pdf render
Last synced: 8 months ago
JSON representation
Create dynamic PDF from HTML template using handlebars
- Host: GitHub
- URL: https://github.com/navjotdhanawat/dynamic-html-pdf
- Owner: navjotdhanawat
- License: mit
- Created: 2017-08-02T09:17:50.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2021-05-16T05:11:40.000Z (about 5 years ago)
- Last Synced: 2025-10-05T14:05:38.065Z (9 months ago)
- Topics: content, dynamic, dynamic-html-pdf, handlebar-template, html, pdf, render
- Language: JavaScript
- Homepage:
- Size: 12.7 KB
- Stars: 36
- Watchers: 2
- Forks: 10
- Open Issues: 9
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## How to Setup: Dynamic handlebars html pdf to create dynamic content html to pdf.
#### Installation
```
npm install dynamic-html-pdf --save
```
#### Create template.html
```
Dynamic HTML to PDF
Hi {{users.0.name}}
template
{{#ifCond 'v1' 'v2'}}
{{v1}} is equals to {{v2}}
{{else}}
Variables are not similar
{{/ifCond}}
```
#### Feel free to use handlebar syntax: [Handlebar builtin helpers](http://handlebarsjs.com/builtin_helpers.html)
For example:
```
- Name: {{this.name}}
- Age: {{this.age}}
- DOB: {{this.dob}}
{{#each users}}
{{/each}}
```
#### [Custom handlebar helpers](https://handlebarsjs.com/block_helpers.html)
For example:
Register helper inside js file:
```
// Custom If condition inside handlebar(JS file)
var pdf = require('dynamic-html-pdf');
pdf.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
})
```
Utilize registered helper inside handlebar template:
```
{{#ifCond v1 v2}}
{{v1}} is equals to {{v2}}
{{else}}
Variables are not similar
{{/ifCond}}
```
#### How to use Dynamic HTML to PDF
```
var fs = require('fs');
var pdf = require('dynamic-html-pdf');
var html = fs.readFileSync('template.html', 'utf8');
// Custom handlebar helper
pdf.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
})
var options = {
format: "A3",
orientation: "portrait",
border: "10mm"
};
var users = [
{
name: 'aaa',
age: 24,
dob: '1/1/1991'
},
{
name: 'bbb',
age: 25,
dob: '1/1/1995'
},
{
name: 'ccc',
age: 24,
dob: '1/1/1994'
}
];
var document = {
type: 'buffer', // 'file' or 'buffer'
template: html,
context: {
users: users
},
path: "./output.pdf" // it is not required if type is buffer
};
pdf.create(document, options)
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
});
```