Sunday, March 19, 2023
HomeJavascriptThe right way to create PDF with JavaScript and jsPDF

The right way to create PDF with JavaScript and jsPDF

Creating dynamic PDF recordsdata instantly within the browser is feasible because of the jsPDF JavaScript library.

Within the final a part of this text we have now ready a sensible tutorial the place I present you how one can implement the library. Under you’ll be able to see the finished train.

The shopper facet is gaining floor over the server facet

The JsPDF library is an instance of this. By means of its API, PDF recordsdata will be generated on demand, instantly within the browser. That is good for creating tickets, reviews or certificates in actual time.

Actually, this library helps each entrance finish and again finish improvement. Its JavaScript API will be applied within the browser and in NodeJs environments alike. Nonetheless, on this event, we’ll give attention to the entrance finish implementation.

JsPDF is a device created by the digital company Parallax. Its repository is actively maintained by a crew of 191 individuals. And on the time of writing, it boasts greater than 25K stars in its Github repository.

The “packaged” model occupies about 350Kb. Round right here, we’re used to see lighter libraries. However contemplating the issue it solves, it is comprehensible that it takes up that a lot.

In fact, you’ll be able to set up it utilizing the command “npm set up jspdf -save”, and combine it comfortably into your challenge.

Creating PDF is straightforward with JavaScript and jsPDF

Its API exposes a lot of strategies, properties and modules. The presentation web page of the library provides a wonderfully ordered documentation. Even so, it’s advisable to go to the “dwell demo” part. On this part, you’ll be able to see a number of examples of software of the library.

In any case, it’s important to start out by instantiating an object of the jsPDF class. This object, by conference, we name it “doc”, referring to the PDF doc it represents.

As ordinary, instantiating the category, you’ll be able to move an object with elective configuration parameters. Properties reminiscent of web page formatting and orientation will be determined. The models of measurement and doc comprehension. Even encryption, in case you need the file to be password protected.

The “doc” object is reminiscent in some respects of the “CanvasRenderingContext2D” of the canvas tags. By means of strategies reminiscent of rect(), lineTo(), ellipse(), stroke() or fill(), vector graphics will be drawn. Additionally, via the textual content() methodology, textual content will be included at sure factors of the pages. On one other event, we noticed one other library whose API was additionally similar to that of Canvas.

Creating artwork with JavaScript and P5.js

However jsPDF goes additional. As well as, it exposes features to create extra advanced parts, or PDF recordsdata themselves. For instance, via the desk() methodology, you’ll be able to create information tables with rows and columns. Or via the createAnnotation() methodology, you’ll be able to even embody feedback to the file.

The choice to incorporate extra pages within the doc is out there via the addPage() methodology.

As soon as the doc is about up and prepared, jsPDF solves the entire downloading course of by calling the save() perform.

Subsequent, we’ll see how one can create PDF recordsdata dynamically with JavaScript and JsPDF.

Create a PDF file dynamically with JavaScript

To create a PDF file dynamically with JavaScript, we’ll begin by programming a easy net software. On this software, the consumer will have the ability to create and export a faux character profile. Ranging from a template, we are able to enter information such because the title, the kind of character or the talents. And later, obtain a PDF with this data.

We’ll begin by getting ready the consumer interface. The interface will probably be composed, on the one hand, of an HTML kind with completely different fields. And then again, an iframe tag, which can assist us to preview the pdf, earlier than downloading it.

Within the kind we’ll embody the next fields: title, nickname, description, sort, power, magic and velocity. Then we may also embody a component to show error messages when vital, and a few buttons. The buttons will enable the consumer to view the file and obtain it.

Then we embody an empty iframe tag. Utilizing the Tailwind css fashion library, we’ll embody CSS courses to all the weather to fashion them. You will need to embody “id” attributes within the kind, error message, and iframe tags. Later, these ids will probably be used for the Js script.

It needs to be famous that within the checklist of character sort choices, a particular data-image-url attribute has been included.

It will serve to incorporate a selected picture for every sort.


<physique 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">
        <kind id="form-character-profile" class="w-full">
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
            <enter sort="textual content" title="title" placeholder="Identify" worth="Mario" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded" />
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
            <enter sort="textual content" title="surname" placeholder="Final Identify" worth="Mario" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded" />
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">Description </label>
              class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded"
            >Mario is a balanced character when it comes to weight and velocity. His cape can be utilized as a counterattack, repelling any projectile or method. His leaping motion has the attribute that if he touches an enemy he can get hold of cash and, on the identical time, ship him out of the display screen.
          <div class="mb-5">
            <label for="" class="block text-sky-900 font-bold">
            <choose title="sort" class="block w-full p-3 border-2 border-sky-700 bg-sky-50 rounded">
              >Participant 1</choice>
                worth="enemy 2"
              >Ememy 2</choice>
                worth="participant 2"
              >Participant 2</choice>
                worth="participant 3"
              >Participant 3</choice>
              >Enemy 3</choice>
              <label class="block text-sky-900 font-bold">Power:</label>
              <label class="block text-sky-900 font-bold">Power:</label>
              <enter sort="vary" title="power" class="w-full" worth="90" />
              <label class="block text-sky-900 font-bold">Pace:</label>
          <div id="error-message-container" class="hidden text-red-500 bg-red-100 p-4 rounded mt-3">
            *Error message
          <hr class="my-5">
          <div class="mt-3">
            <button sort="button" class="bg-sky-500 text-white px-3 py-2 rounded preview-pdf-btn">Preview PDF</button>
            <button sort="submit" class="bg-sky-500 text-white px-3 py-2 rounded">Obtain PDF</button>


Within the SCSS file, we’ll embody the fundamental Tailwind sources, and add a couple of traces of further CSS.


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


With the interface construction and types prepared, we are able to begin programming the script. First, we import the JsPDF library and types.


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


Subsequent, we retailer in variables, references to parts of the DOM. These parts would be the kind, the preview button, the error message container, and the iframe.


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


Earlier than producing the pdf with the JsPDF library, you will need to extract and validate the shape information. To do that, we declare the perform handleOnSubmitForm. This perform will probably be in control of going via all of the fields of the shape with attribute “title”. For each, it’ll attempt to save within the variable “characterData” the property and the worth. In case a worth will not be outlined, it’ll throw an error and replace the interface to indicate that error.


  const handleOnSubmitForm = (e) =>
    const characterProperties = Array.from(e.goal.querySelectorAll("[name]"));
    const characterData =};
    for (let i = 0, j = characterProperties.size; i < j; i++)
      const area = characterProperties[i];
      const attribute = area.getAttribute("title");
      const worth = area.worth;
      if (!area.worth)
        throw new Error(`Empty ${attribute} area!`);
      characterData[attribute] = worth;
      if (attribute === "sort")
        const choice = area.querySelector(`[value=${value}]`);
        characterData[attribute] =
          title: choice.innerHTML,
          picture: choice.dataset.imageUrl,
    generatePDF(characterData, e.isPreview);
  } catch (err)
    errorMessageContainer.innerHTML = err.message;
    errorMessageContainer.classList.take away("hidden");


On the finish of the perform, if the whole lot is right, it’ll name generatePDF().

GeneratePDF is the perform that can create the PDF file dynamically. It can obtain two arguments. The primary one is the thing that describes the properties of the character. And the second is a boolean, to determine whether or not to preview or obtain.

At the start of this perform we instantiate the jsPDF class. Though we might move a configuration object, we’ll depart the predefined values. Via the thing “doc” we place all of the texts and pictures. To do that, we use the strategies textual content() and addImage().

Moreover, we are able to fashion these texts with strategies reminiscent of setFont() and setFontSize(). In addition to including some separator traces, with the line() methodology.

As soon as the content material is “laid out” within the doc, we generate the PDF. If the “preview” variable is “true, we replace the iframe property, calling the “output(“bloburl”)” methodology. In case it’s false, we are able to instantly name the save() methodology. This final methodology will create and obtain the file for us with the title indicated.


  const generatePDF = (characterData, preview) => {
  const doc = new jsPDF();
  doc.setFont("helvetica", "daring");
  doc.textual content(characterData.title, 60, 30);
  doc.setFont("helvetica", "regular");
  doc.textual content(characterData.surname, 60, 42);
  doc.addImage(characterData.sort.picture, "PNG", 5, 0, 50, 50);
  const docWidth = doc.inside.pageSize.getWidth();
  const docHeight = doc.inside.pageSize.getHeight();
  doc.line(0, 60, docWidth, 60);
  doc.setFont("helvetica", "italic");
  const splitDescription = doc.splitTextToSize(
    docWidth - 20
  doc.textual content(splitDescription, 10, 80);
  doc.setFont("helvetica", "daring");
  doc.textual content(characterData.sort.title, docWidth - 20, 45, { align: "proper" });
  doc.line(0, docHeight - 60, docWidth, docHeight - 60);
  doc.textual content(`Fuerza: `, 10, docHeight - 40);
  doc.textual content(`Magia: `, 10, docHeight - 30);
  doc.textual content(`Velocidad: `, 10, docHeight - 20);
  doc.setFont("helvetica", "regular");
  doc.textual content(`${characterData.power}`, 50, docHeight - 40);
  doc.textual content(`${characterData.magic}`, 50, docHeight - 30);
  doc.textual content(`${characterData.velocity}`, 50, docHeight - 20);
  if (preview) {
    body.src = doc.output("bloburl");


Lastly, the one factor left to do is to hearken to the shape submission occasions, and click on on the preview button. When submitting the shape, we’ll name the perform handleOnSubmitForm. And when clicking on the button, we may also set off a submission. Nonetheless, in that case, we’ll develop the occasion, with the “isPreview” boolean set to “true.


previewBtn.addEventListener("click on", () => {    
   const occasion = new Occasion("submit");    
   occasion.isPreview = true;    
formCharacterProfile.addEventListener("submit", handleOnSubmitForm);


With this straightforward train, we have now seen how one can simply create PDF recordsdata with JavaScript and JsPDF.

Connecting the net and offline world

The communication energy of a PDF file shouldn’t be underestimated. Regardless of being one thing seemingly easy, it may be the proper bridge that connects the net and offline world.

A transparent instance of this assertion is that in the present day, many individuals nonetheless print tickets and airline tickets. And a dynamically generated QR seems on them, proving their authenticity.






We use our personal and third-party cookies to enhance our providers, compile statistical data and analyze your looking habits. This permits us to personalize the content material we provide and to indicate you ads associated to your preferences. By clicking “Settle for all” you conform to the storage of cookies in your machine to enhance web site navigation, analyse site visitors and help our advertising actions. It’s also possible to choose “System Cookies Solely” to simply accept solely the cookies required for the web site to perform, or you’ll be able to choose the cookies you want to activate by clicking on “settings”.

Settle for All

Solely sistem cookies



Most Popular

Recent Comments