create pdf using javascript
Javascript Web Development

How to create PDF using Javascript

Today, we’ll talk about cool javascript library jsPDF that let you create PDF using javascript only. Yeah, that’s right, no server-side script needed. You can process a dynamic content and generate a PDF on the fly when user click the button (or whatever event that you want)

It’s very quick and easy to create PDF file with jsPDF. For example, if you want to create a simple PDF file with “Hello world!” text, just use the code below.

var doc = new jsPDF();
doc.text(10, 10, 'Hello world!');
doc.save('hello-world.pdf');

The first line, create a jsPDF object. This will represent your PDF document with a default size of A4 paper and portrait orientation. You can pass extra parameter for the constructor to change the file size and orientation here if you like. We’ll talk about that later.

The second line is to add a text string into a PDF page with specified position. The ‘Hello world!’ will be placed 10 millimeters from both top and left. Yes, millimeters, Not pixels! But you can also change the measurement unit to others like pixel or inch when you create the jsPDF object.

The last line is to save the document (Popup the Save As dialog box on the web browser) with specified file name.

See tutorial in video below or live demo in this jsFiddle 

Now back to the first part. If you want to change the PDF file size, orientation or measurement unit, you can pass the JSON to the constructor like this.

var doc = new jsPDF({
  orientation: 'landscape',
  unit: 'in',
  format: [6, 2]
})
//This will make your generated PDF in 6x2 inches landscape.

This is just a basic of what jsPDF is capable of. In the next article, I’m going to talk about using jsPDF to convert your HTML page to PDF file!

If you like this article, feel free to subscribe! Cheers 🙂

Red Stapler Channel: https://www.youtube.com/c/RedStapler_channel

3 comments

Leave a Reply

Your email address will not be published. Required fields are marked *