Generate PDF Invoices with Javascript
Let’s say you wrote a shopping cart. You’re almost finished with the shopping cart, but there is one thing missing. Sending out the purchase invoice! In most cases the invoices are sent out in Portable Document Format (PDF).
Why PDF? I like your curious mind —Here’s a rather simple answer — PDF is easy to use and almost any device can read them! Let’s go!
Assuming you know very very basics of Javascript, let’s start by making our little project directory. Open your terminal and write this command.
$ mkdir js-to-pdf && cd js-to-pdf
Pretty self explanatory. We make the project and navigate into the project folder.
Next up, lets make our index.html
file.
$ touch index.html
With the help of jsPDF
package we can generate PDFs from the client side. Grab the jsPDF CDN from here.
jsPDF — A library to generate PDFs in client-side JavaScript.
Side-note: In a real world scenario we use NPM
to install our dependencies. This is a lesson focused on the jsPDF library.
Okay, Let’s write some code. Not to worry, I will explain everything!
We add a <button></button>
so we have ‘get receipt’ button.
- We
new
up the library so we could use and reference it. - Then we select the
button
- Next up we add the
'click'
event listener for thebutton
and pass theprintPDF
callback. The reason why it’sprintPDF
and notprintPDF()
is because we don’t want to actually immediately fire the callback on page load. We want to fire theprintPDF
function once some clicks the button! - And finally we add a function called
printPDF
— this is where the actual PDF options lay. - Oh and add these styles to the
<head>
<style>
button {
padding: 12px 50px;
border: none;
background-color: rgb(91,234,208);
color: #333;
cursor: pointer;
display: inline-block;
}
</style>
Let’s open our index.html
with our favourite browsers. Yes, all of them!
JS-to-PDF Time!
So how does this work? Well turns out it’s simple!
Let’s take our beloved printPDF
function and wrap some real simple extra functions inside.
I added explained in comments to save up space.
Okay, let’s test it! Let’s click on our button!
Wow! It was that simple! Nothing to be afraid of! We have our first PDF file!
Currently our PDF is very static. It has no interactivity and it’s always going to be the same. Let’s add some interactivity!
- Add the
input
where can place our values. - Select the
input
with Javascript - Spit out the
input
value inside thetext()
method.
Okay, let’s test it!
It works! Cool, cool! If you would like to learn more about formatting the PDF, head over to the docs, they’re quite good!
As always, thanks for your valuable time, stay awesome!
Indrek