DEV Community

Abdul Rehman
Abdul Rehman

Posted on • Edited on

2 1

Generating Custom HTML Invoices which also include Images and convert them to PDF

there are multiple scenarios when the developer needs to build custom pdf for different customers.

Let's start...

npm i html-pdf ejs

let ejs = require("ejs");
let pdf = require("html-pdf");
let path = require("path");
// let utility = require("./utility");
init()
function init() {
let basePath = path.join('file://' + __dirname, 'views', 'img')
let dbObject = {
headerImg: path.join(basePath, 'header.png').replace(/\\/g, '/'), // file://D:/ejs-to-pdf/views/img/header.png
houseNumber: " R-0001",
}
ejs.renderFile(path.join(__dirname, 'views/pages', "invoice.ejs"), {
dbObject // passing object for custom values
}, (err, data) => {
if (err) {
console.log(`err ${err}`)
} else {
var options = {
format: 'A4'
};
pdf.create(data, options).toFile("pdf/pdfFileName.pdf", function (err, data) { // PDF file save in PDF folder
if (err) {
console.log(`err :${err}`)
} else {
console.log(` file genrated successfullt ` , JSON.stringify(data))
}
});
/*
//================================= if you want to send email then use below code
pdf.create(data, options).toBuffer(function (err, buffer) { // PDF file save in PDF folder
if (err) {
console.log(`err :${err}`)
} else {
utility.SendEmailNotification('your@email', 'Monthly Bill Statement', 'your bill', buffer, 'Monthly_Bill_Statement.pdf').then((result) => {
console.log(` send successfully `)
}).catch((err) => {
console.log(`err `)
});
// console.log(` file buffer genrated successfullt `) // you can wrinte your email send code here
}
});
*/
}
})
}

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay