mgm
Version:
My generic modules
147 lines (121 loc) • 3.78 kB
JavaScript
const puppeteer = require('puppeteer');
const BaseValidator = require('../validator/BaseValidator');
const baseValidator = new BaseValidator();
let _title = '';
class ReportPdf {
constructor(pathToPdf, rs = [], generateHtmlVersion = false) {
this.html = [];
this.setData(rs);
this.pathToPdf = pathToPdf;
this.listField = [];
this.generateHtmlVersion = generateHtmlVersion;
}
get title() {
return _title;
}
set title(title) {
_title = title;
}
setData(rs = []) {
this.rs = rs;
baseValidator.checkRule(this.rs.length === 0, 'as dados informados não retornaram dados para geração do relatório');
baseValidator.verifyRules();
}
setListField(listField) {
this.listField = listField;
}
async createReport(callBack) {
this.html.push('<!DOCTYPE html>');
this.html.push('<html>');
this.html.push('<head>');
this.html.push('<meta charset="UTF-8">');
this.html.push('<meta name="viewport" content="width=device-width, initial-scale=1">');
this.html.push(`
<style>
table {
border-collapse: collapse;
width: 100%;
}
thead tr th,
tfoot tr td {
background: lightgray;
}
caption {
border: solid 1px gray;
background: darkgray;
font-weight: bold;
font-size: 20px;
}
td[colspan]{
text-align: right;
font-weight: bold;
}
.center, .left, .right {
vertical-align: middle !important;
}
.center {
text-align: center !important;
}
.left {
text-align: left !important;
}
.right {
text-align: right !important;
}
</style>
`);
this.html.push('</head>');
this.html.push('<body>');
this.html.push('<table border=\'1\'>');
this.html.push(`<caption>${this.title}</caption>`);
prepareHeader.call(this);
prepareBody.call(this, callBack);
prepareFooter.call(this);
this.html.push('</table>');
this.html.push('</body>');
this.html.push('</html>');
await create.call(this);
}
}
function prepareHeader() {
this.html.push('<thead>');
this.html.push('<tr>');
Object.keys(this.rs[0]).forEach((key, index) => {
this.html.push(`<th>${this.listField[index][key]}</th>`);
});
this.html.push('</tr>');
this.html.push('</thead>');
}
function prepareBody(callBack) {
this.html.push('<tbody>');
callBack(this.rs, this.html)
this.html.push('</tbody>');
}
function prepareFooter() {
this.html.push(`<tfoot><tr><td colspan='${this.listField.length}'><strong>${this.rs.length}</strong> registro(s) listado(s)</td></tr></tfoot>`);
}
async function create() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(this.html.join(''));
await page.pdf({
path: this.pathToPdf,
format: 'A4',
landscape: true,
printBackground: true,
margin: {
top: 0,
left: 0,
right: 0,
bottom: 0
}
});
await browser.close();
if (this.generateHtmlVersion) {
await writeToFile.call(this);
}
}
async function writeToFile() {
await require('fs').writeFileSync(`${this.pathToPdf.replace(/\.pdf/g, '.html')}`, this.html.join(''));
}
module.exports = ReportPdf;