📦 Trailpack to generate PDF from routes or templates for Trails.js project
This Trailpack is based on phantomjs and phantomjs-node to generate PDF.
It can also generate page into image (png, jpeg) instead of PDF.
With yo :
npm install -g yo generator-trails
yo trails:trailpack trailpack-pdf
With npm (you will have to create config file manually) :
npm install --save trailpack-pdf
Load the trailpack to the main config
// config/main.js
module.exports = {
packs: [
// ... other trailpacks
require('trailpack-pdf')
]
}
// config/pdf.js
module.exports = {
/**
* Phantom launch options, default to empty
*/
options: ['--ignore-ssl-errors=yes', '--load-images=no'],
/**
* Global page settings, default to empty
* Example : javascriptEnabled to enable/disable javascript support on the page, userAgent...
*/
pageSettings: {javascriptEnabled:true},
/**
* Global page properties, default to empty
* Example : page size, header, footer...
*/
pageProperties: {
paperSize: (phantom) => {
return {
format: 'A4',
header: {
height: '1.5cm',
contents: phantom.callback(function (pageNum, numPages) {
return '<h1>Header <span style=\'float:right\'>' + pageNum + ' / ' + numPages + '</span></h1>'
})
},
footer: {
height: '1.5cm',
contents: phantom.callback(function (pageNum, numPages) {
return '<h1>Footer <span style=\'float:right\'>' + pageNum + ' / ' + numPages + '</span></h1>'
})
}
}
}
}
}
This Trailpack expose a service to generate PDF, you can call it like this under controller/services/policies :
/**
* Generate PDF from a Trails route, or route path
* You can override global page settings and properties, these params are optional
**/
this.app.services.PdfService.generateFromRoute('/', '/path/to/my/file.pdf', {javascriptEnabled: true}, {pageSize: {format: 'A4'})
.then(() => {
//pdf generated
})
.catch(err => this.log.error(err))
/**
* Generate PDF from an URL
* You can override global page settings and properties, these params are optional
**/
this.app.services.PdfService.generateFromUrl('http://google.fr', '/path/to/my/file.pdf', {javascriptEnabled: true}, {pageSize: {format: 'A4'})
.then(() => {
//pdf generated
})
.catch(err => this.log.error(err))
const path = 'html.pdf'
const template = 'index.jade'
const fn = jade.compile(fs.readFileSync(template))
this.app.services.PdfService.generateFromHtml(fn(), path).then(status => {
//pdf generated
}).catch(err => done(err))
Use same code as above but change the extension to .png
or .jpeg
We love contributions! In order to be able to review your code efficiently, please keep the following in mind:
- Pull Requests (PRs) must include new and/or updated tests, and all tests must pass.
- Use
eslint
! See theeslintConfig
in package.json. - Please reference the relevant issue in your Pull Request.
Hey dude! Help me out for a couple of 🍻!