Created
March 26, 2021 16:02
-
-
Save mbenedettini/59d51076e813f5bbb14e42cae4895455 to your computer and use it in GitHub Desktop.
Generate invoice with barcode from html2pdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Invoice.prototype.getBarcode = function() { | |
const CUIT = this.tenant().cuit; | |
const baseCode = `${CUIT}\ | |
${(this.type + '').padStart(3, '0')}\ | |
${(this.salesPoint + '').padStart(5, '0')}\ | |
${this.cae}${moment(this.caeDueDate).format('YYYYMMDD')}`; | |
let oddSum = 0, | |
evenSum = 0; | |
baseCode.split('').forEach((digit, index) => { | |
digit = parseInt(digit); | |
if (index % 2) { | |
oddSum += digit; | |
} else { | |
evenSum += digit; | |
} | |
}); | |
const sum = oddSum * 3 + evenSum; | |
const verifier = 10 - (sum % 10); | |
const fullcode = baseCode + verifier; | |
return fullcode; | |
}; | |
Invoice.getHtml = async function(id) { | |
// ... | |
const data = { | |
invoice, | |
items, | |
tenant, | |
headers: { | |
left: tenant.invoiceHeaders.left.split(/\r?\n/), | |
right: tenant.invoiceHeaders.right.split(/\r?\n/) | |
}, | |
subtotal: invoice.getSubtotal(), | |
displaySubtotals: invoice.clientVatKind == 'respInsc', | |
displayDates: [Concepts.Services, Concepts.ProductsServices].includes( | |
invoice.concept | |
), | |
/* El barcode en el template html va con la fuente https://github.com/Holger-Will/2of5-font */ | |
barcode: invoice.getBarcode() | |
}; | |
const templatePath = path.resolve('common/models/html/invoice.html'); | |
const content = await Promise.promisify(fs.readFile)(templatePath, 'utf8'); | |
const template = handlebars.compile(content); | |
const html = template(data); | |
return html; | |
}; | |
Invoice.pdf = async function(id) { | |
try { | |
const html = await Invoice.getHtml(id); | |
const browser = await Puppeteer.launch({ | |
args: [ | |
'--headless', | |
'--no-sandbox', | |
'--disable-dev-shm-usage', | |
'--disable-setuid-sandbox', | |
'--disable-web-security', | |
'--disable-gpu' | |
], | |
/* eslint-disable indent */ | |
...(process.env.CHROMIUM_EXECUTABLE | |
? { | |
executablePath: process.env.CHROMIUM_EXECUTABLE | |
} | |
: null) | |
/* eslint-enable indent */ | |
}); | |
const page = await browser.newPage(); | |
//page.on('console', msg => logger.debug('PAGE LOG:', msg.text())); | |
await page.goto('data:text/html,' + html, { | |
waitUntil: 'networkidle0' | |
}); | |
const pdf = await page.pdf({ | |
format: 'A4' | |
}); | |
await browser.close(); | |
return [pdf, 'application/pdf']; | |
} catch (error) { | |
logger.error(error); | |
throw new Error('Cannot create invoice PDF.'); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment