How to create PDF with JavaScript and jsPDF

by Janeth Kent Date: 04-12-2022 javascript


Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library.

In the last part of this article we have prepared a practical tutorial where I show you how to implement the library. Below you can see the completed exercise.

The client side is gaining ground over the server side

The JsPDF library is an example of this. Through its API, PDF files can be generated on demand, directly in the browser. This is perfect for creating tickets, reports or certificates in real time.

In fact, this library supports both front end and back end development. Its JavaScript API can be implemented in the browser and in NodeJs environments alike. However, on this occasion, we will focus on the front end implementation.

JsPDF is a tool created by the digital agency Parallax. Its repository is actively maintained by a team of 191 people. And at the time of writing, it boasts more than 25K stars in its Github repository.

The "packaged" version occupies about 350Kb. Around here, we are used to see lighter libraries. But considering the problem it solves, it's understandable that it takes up that much.

Of course, you can install it using the command "npm install jspdf -save", and integrate it comfortably into your project.

Creating PDF is easy with JavaScript and jsPDF

Its API exposes a large number of methods, properties and modules. The presentation page of the library offers a perfectly ordered documentation. Even so, it is advisable to visit the "live demo" section. In this section, you can see several examples of application of the library.

In any case, it is essential to start by instantiating an object of the jsPDF class. This object, by convention, we call it "doc", referring to the PDF document it represents.

As usual, instantiating the class, you can pass an object with optional configuration parameters. Properties such as page formatting and orientation can be decided. The units of measurement and document comprehension. Even encryption, in case you want the file to be password protected.

The "doc" object is reminiscent in some respects of the "CanvasRenderingContext2D" of the canvas tags. Through methods such as rect(), lineTo(), ellipse(), stroke() or fill(), vector graphics can be drawn. Also, through the text() method, text can be included at certain points of the pages. On another occasion, we saw another library whose API was also very similar to that of Canvas.

Creating art with JavaScript and P5.js

But jsPDF goes further. In addition, it exposes functions to create more complex elements, or PDF files themselves. For example, through the table() method, you can create data tables with rows and columns. Or through the createAnnotation() method, you can even include comments to the file.

The option to include more pages in the document is available through the addPage() method.

Once the document is set up and ready, jsPDF solves the whole downloading process by calling the save() function.

Next, we will see how to create PDF files dynamically with JavaScript and JsPDF.

Create a PDF file dynamically with JavaScript


To create a PDF file dynamically with JavaScript, we will start by programming a simple web application. In this application, the user will be able to create and export a fake character profile. Starting from a template, we can enter data such as the name, the type of character or the skills. And later, download a PDF with this information.

We will start by preparing the user interface. The interface will be composed, on the one hand, of an HTML form with different fields. And on the other hand, an iframe tag, which will help us to preview the pdf, before downloading it.

In the form we will include the following fields: name, nickname, description, type, strength, magic and speed. Then we will also include an element to display error messages when necessary, and a couple of buttons. The buttons will allow the user to view the file and download it.

Then we include an empty iframe tag. Using the Tailwind css style library, we will include CSS classes to all the elements to style them. It is important to include "id" attributes in the form, error message, and iframe tags. Later, these ids will be used for the Js script.

It should be noted that in the list of character type options, a special data-image-url attribute has been included.

This will serve to include a specific image for each type.

 
<body class="h-screen flex flex-col items-center bg-slate-50">
    <div class="block md:flex main-layout w-screen">
      <div class="flex justify-center items-center p-5">
        <form id="form-character-profile" class="w-full">
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
              Name: 
            </label>
            <input type="text" name="name" placeholder="Name" value="Mario" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded" />
          </div>
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
              Sobrenombre: 
            </label>
            <input type="text" name="surname" placeholder="Last Name" value="Mario" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded" />
          </div>
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">Description </label>
            <textarea
              name="description"
              cols="30"
              rows="5"
              class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded"
              placeholder="Descripción"
            >Mario is a balanced character in terms of weight and speed. His cape can be used as a counterattack, repelling any projectile or approach. His jumping movement has the characteristic that if he touches an enemy he can obtain coins and, at the same time, send him out of the screen.
.</textarea>
          </div>
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
              Tipo:
            </label>
            <select name="type" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded">
              <option
                value="player"
                data-image-url="imgs/Mario_Bross.png"
              >Player 1</option>
              <option
                value="enemy"
                data-image-url="imgs/goomba.png"
              >Enemy</option>
              <option
                value="enemy 2"
                data-image-url="imgs/koopa.png"
              >Ememy 2</option>
              <option
                value="player 2"
                data-image-url="imgs/luigi.png"
              >Player 2</option>
              <option
                value="player 3"
                data-image-url="imgs/toad.png"
              >Player 3</option>
              <option
                value="enemy-3"
                data-image-url="imgs/Wario.png"
              >Enemy 3</option>
            </select>
          </div>
          <div>
            <div>
              <label class="block text-sky-900 font-bold">Strength:</label>
              <input
                type="range"
                name="strength"
                value="40"
                class="w-full"
              
              /></div>
            <div>
              <label class="block text-sky-900 font-bold">Strength:</label>
              <input type="range" name="strength" class="w-full" value="90" />
            </div>
            <div>
              <label class="block text-sky-900 font-bold">Speed:</label>
              <input
                type="range"
                value="60"
                name="velocity"
                class="w-full"
              
              /></div>
          </div>
          <div id="error-message-container" class="hidden text-red-500 bg-red-100 p-4 rounded mt-3">
            *Error message
          </div>
          <hr class="my-5">
          <div class="mt-3">
            <button type="button" class="bg-sky-500 text-white px-3 py-2 rounded preview-pdf-btn">Preview PDF</button>
            <button type="submit" class="bg-sky-500 text-white px-3 py-2 rounded">Download PDF</button>
          </div>
        </form>
      </div>
      <div>
        <iframe
          id="frame"
          src=""
          frameborder="0">
        </iframe>
      </div>
    </div>
  </body>
 

In the SCSS file, we will include the basic Tailwind resources, and add a few lines of additional CSS.

 
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
 margin: 0;
 padding: 0;
}
.main-layout {
  & > div {
   width: 100%;
    iframe {
     width: 100%;
     min-height: 500px;
     height: 100%;
     max-height: 800px;
    }
  }
}
 

With the interface structure and styles ready, we can start programming the script. First, we import the JsPDF library and styles.

 
import { jsPDF } from "jspdf"; 
import "./SCSS/index.scss";
 

Next, we store in variables, references to elements of the DOM. These elements will be the form, the preview button, the error message container, and the iframe.

 
const formCharacterProfile = document.querySelector("#form-character-profile");  
const previewBtn = formCharacterProfile.querySelector(".preview-pdf-btn");  
const errorMessageContainer = document.querySelector("#error-message-container");  
const frame = document.querySelector("#frame");
 

Before generating the pdf with the JsPDF library, it is important to extract and validate the form data. To do this, we declare the function handleOnSubmitForm. This function will be in charge of going through all the fields of the form with attribute "name". For each one, it will try to save in the variable "characterData" the property and the value. In case a value is not defined, it will throw an error and update the interface to show that error.

 
  const handleOnSubmitForm = (e) =>
  e.preventDefault();
  try
    const characterProperties = Array.from(e.target.querySelectorAll("[name]"));
    const characterData =};
    errorMessageContainer.classList.add("hidden");
    for (let i = 0, j = characterProperties.length; i < j; i++)
      const field = characterProperties[i];
      const attribute = field.getAttribute("name");
      const value = field.value;
      if (!field.value)
        throw new Error(`Empty ${attribute} field!`);
      }
      characterData[attribute] = value;
      if (attribute === "type")
        const option = field.querySelector(`[value=${value}]`);
        characterData[attribute] =
          name: option.innerHTML,
          image: option.dataset.imageUrl,
        };
      }
    }
    generatePDF(characterData, e.isPreview);
  } catch (err)
    errorMessageContainer.innerHTML = err.message;
    errorMessageContainer.classList.remove("hidden");
  }
};
 

At the end of the function, if everything is correct, it will call generatePDF().

GeneratePDF is the function that will create the PDF file dynamically. It will receive two arguments. The first one is the object that describes the properties of the character. And the second is a boolean, to decide whether to preview or download.

At the beginning of this function we instantiate the jsPDF class. Although we could pass a configuration object, we will leave the predefined values. By means of the object "doc" we position all the texts and images. To do this, we use the methods text() and addImage().

Additionally, we can style those texts with methods such as setFont() and setFontSize(). As well as adding some separator lines, with the line() method.

Once the content is "laid out" in the document, we generate the PDF. If the "preview" variable is "true, we update the iframe property, calling the "output("bloburl")" method. In case it is false, we can directly call the save() method. This last method will create and download the file for us with the name indicated.

 
  const generatePDF = (characterData, preview) => {
  const doc = new jsPDF();
  doc.setFontSize(40);
  doc.setFont("helvetica", "bold");
  doc.text(characterData.name, 60, 30);
  doc.setFont("helvetica", "normal");
  doc.text(characterData.surname, 60, 42);
  doc.addImage(characterData.type.image, "PNG", 5, 0, 50, 50);
  doc.setFontSize(20);
  const docWidth = doc.internal.pageSize.getWidth();
  const docHeight = doc.internal.pageSize.getHeight();
  doc.line(0, 60, docWidth, 60);
  doc.setFont("helvetica", "italic");
  const splitDescription = doc.splitTextToSize(
    characterData.description,
    docWidth - 20
  );
  doc.text(splitDescription, 10, 80);
  doc.setFontSize(20);
  doc.setFont("helvetica", "bold");
  doc.text(characterData.type.name, docWidth - 20, 45, { align: "right" });
  doc.line(0, docHeight - 60, docWidth, docHeight - 60);
  doc.text(`Fuerza: `, 10, docHeight - 40);
  doc.text(`Magia: `, 10, docHeight - 30);
  doc.text(`Velocidad: `, 10, docHeight - 20);
  doc.setFont("helvetica", "normal");
  doc.text(`${characterData.strength}`, 50, docHeight - 40);
  doc.text(`${characterData.magic}`, 50, docHeight - 30);
  doc.text(`${characterData.velocity}`, 50, docHeight - 20);
  if (preview) {
    frame.src = doc.output("bloburl");
    return;
  }
  doc.save(`${characterData.name}-${characterData.surname}`);
};
 

Finally, the only thing left to do is to listen to the form submission events, and click on the preview button. When submitting the form, we will call the function handleOnSubmitForm. And when clicking on the button, we will also trigger a submission. However, in that case, we will expand the event, with the "isPreview" boolean set to "true.

 
previewBtn.addEventListener("click", () => {    
   const event = new Event("submit");    
   event.isPreview = true;    
   formCharacterProfile.dispatchEvent(event);   
   });  
formCharacterProfile.addEventListener("submit", handleOnSubmitForm);
 

With this simple exercise, we have seen how to easily create PDF files with JavaScript and JsPDF.

Connecting the online and offline world

The communication power of a PDF file should not be underestimated. Despite being something seemingly simple, it can be the perfect bridge that connects the online and offline world.

A clear example of this statement is that today, many people still print tickets and airline tickets. And a dynamically generated QR appears on them, proving their authenticity.

 
by Janeth Kent Date: 04-12-2022 javascript hits : 10117  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration