DEV Community

Chizobam Favour
Chizobam Favour

Posted on

Text to pdf using jsPDF

jsPDF is a popular JavaScript library for dynamically generating PDF files in client-side web applications. It allows developers to create PDF documents from scratch or modify existing ones.

Creating a text-to-PDF converter in a React app using jsPDF involves building a simple web application where users can input text into a text area, and then convert that text into a PDF document.

Here's an overview of the key features and capabilities of jsPDF:

  • Image Support: Developers can embed images (JPEG, PNG, or GIF) into PDF documents using jsPDF. Images can be resized, rotated, and positioned on the page.
  • PDF Generation: jsPDF enables developers to create PDF documents directly in the browser without the need for server-side processing. This makes it suitable for web applications where generating PDF files on the client side is necessary.
  • HTML to PDF Conversion: jsPDF includes plugins that allow developers to convert HTML elements into PDF content. This feature enables the conversion of HTML pages, including CSS styles, into PDF documents.
  • Open Source: jsPDF is an open-source project distributed under the MIT License, which means developers can use, modify, and distribute it freely in their projects.

Setting Up the React App
To set up a new React project and install the required dependencies including jsPDF, you can follow these steps:

  • Initialize a new React project: You can initialize a new React project using create-react-app, which is a popular tool for bootstrapping React applications.


npx create-react-app my-pdf-generator


Enter fullscreen mode Exit fullscreen mode
  • Install jsPDF: Now, you need to install jsPDF and any other dependencies required for your project. You can do this using npm or yarn.

Before we can start using jsPDF in our projects, we need to first install it. jsPDF can be installed via various methods, depending on your project's setup and preferences.

Using npm:
Using npm (Node Package Manager), you can install jsPDF by running the following command in your terminal:



npm i jspdf


Enter fullscreen mode Exit fullscreen mode

This will download and install the latest version of jsPDF from the npm registry and add it to your project's node_modules directory.

Using yarn:



yarn add jspdf


Enter fullscreen mode Exit fullscreen mode

Alternatively, You can load it directly in your HTML file using a Content Delivery Network (CDN). For example, you can include the following script tag in your HTML:



<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>


Enter fullscreen mode Exit fullscreen mode

Implementing Text Input Component

Now let's get started with building the project.

Creating a TextInput component



<div className="cont">
  <form>
    <textarea className="txt" name="txt" placeholder="Write a comment..." />
    <button className="btn">Generate</button>
  </form>
</div>


Enter fullscreen mode Exit fullscreen mode

Styling the text input for a better user experience



.cont{
  margin: 2rem;
  margin-left: 5rem;
  margin-right: 5rem;
}

.txt{
  width: 100%;
  height: 150px;
  padding: 12px 20px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
  background-color: #f8f8f8;
  font-size: 16px;
  resize: none;
}


.btn{
  border-radius: 0.5rem; 
  text-align: center; 
  color: #ffffff; 
  background-color: #1D4ED8; 
  width: 5rem;
  height: 3rem;
}

.btn:hover {
  background-color: #1E40AF; 
  }


Enter fullscreen mode Exit fullscreen mode

Integrating jsPDF into the React App

Importing jsPDF library



import React from "react";
import { jsPDF } from "jspdf";


Enter fullscreen mode Exit fullscreen mode

Here, we are importing React and the jsPDF class from the jspdflibrary. React is needed for creating React components, and jsPDFis used for generating PDFs dynamically

Setting up PDF generation functionality

This function, handleSubmit, is triggered when the user submits the form. It extracts the text entered by the user from the textarea and uses it to generate a PDF document. Here's what each part does:



const handleSubmit = (e) => {
  e.preventDefault();
  const val = e.target.txt.value;

  // Create a new instance of jsPDF
  const jspdf = new jsPDF("p", "pt", "letter");

  // Define margin using an object
  const margin = { top: 30, right: 30, bottom: 30, left: 30 };

  // Add text to the PDF with specified margin
  jspdf.text(val, margin.left, margin.top, { align: "left", maxWidth: 500 });

  // Save the PDF with a filename
  jspdf.save("demo.pdf");

  // Clear textarea after generating PDF
  e.target.txt.value = '';
};



Enter fullscreen mode Exit fullscreen mode
  • const jspdf = new jsPDF("p", "pt", "letter"): Creates a new instance of jsPDF, configuring the PDF to be generated in portrait orientation, using points as units, and with the page size set to "letter".
  • const margin = { top: 30, right: 30, bottom: 30, left: 30 }: Defines margins for the PDF document.
  • const val = e.target.txt.value: Extracts the text entered by the user from the textarea.
  • const jspdf = new jsPDF("p", "pt", "letter"): Creates a new instance of jsPDF, configuring the PDF to be generated in portrait orientation, using points as units, and with the page size set to "letter".
  • const margin = { top: 30, right: 30, bottom: 30, left: 30 }: Defines margins for the PDF document.
  • jspdf.text(val, margin.left, margin.top, { align: "left", maxWidth: 500 }): Adds the user-entered text to the PDF document with the specified margins, alignment, and maximum width.
  • jspdf.save("demo.pdf"): Saves the PDF document with the filename "demo.pdf".
  • e.target.txt.value = '': Clears the textarea after generating the PDF.

Implementing a PDFGenerator component
The PdfGen component renders a form with a textarea and a button. This is where the user interacts with the application to input text and trigger PDF generation. The form's submission is handled by the handleSubmit function.



function PdfGen() {
  return (
    <div className="cont">
      <form onSubmit={handleSubmit}>
        <textarea className="txt" name="txt" placeholder="Write a comment..." />
        <button type="submit" className="btn">
          Generate
        </button>
      </form>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

PDF generation is triggered when the form is submitted. Upon clicking the "Generate" button, the handleSubmit function is called, which handles the PDF generation process.

Code



import React from "react";
import { jsPDF } from "jspdf";

function PdfGen() {
  const handleSubmit = (e) => {
    e.preventDefault();
    const val = e.target.txt.value;

    // Create a new instance of jsPDF
    const jspdf = new jsPDF("p", "pt", "letter");

    // Define margin using an object
    const margin = { top: 30, right: 30, bottom: 30, left: 30 };

    // Add text to the PDF with specified margin
    jspdf.text(val, margin.left, margin.top, { align: "left", maxWidth: 500 });

    // Save the PDF with a filename
    jspdf.save("demo.pdf");

    // Clear textarea after generating PDF
    e.target.txt.value = "";
  };

  return (
    <div className="cont">
      <form onSubmit={handleSubmit}>
        <textarea className="txt" name="txt" placeholder="Write a comment..." />
        <button type="submit" className="btn">
          Generate
        </button>
      </form>
    </div>
  );
}

export default PdfGen;


Enter fullscreen mode Exit fullscreen mode

Output
bandicam2024-04-2421-07-13-087-ezgif.com-video-to-gif-converter

Conclusion
With jsPDF, developers have access to a powerful tool for generating PDFs directly in the browser, without relying on server-side processing. This makes it ideal for web applications where client-side PDF generation is required, offering flexibility and efficiency in document creation.

Top comments (3)

Collapse
 
marvelken profile image
marvelken

Great article πŸ‘

Collapse
 
webjoe profile image
Joel

Nice

Collapse
 
victorytuduo profile image
Victory Tuduo

Article just saved me some time scouring the web. Implementation works good for me πŸŽ‰