Text to pdf using jsPDF
Chizobam Favour
Posted on April 26, 2024
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
- 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
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
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>
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>
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;
}
Integrating jsPDF into the React App
Importing jsPDF library
import React from "react";
import { jsPDF } from "jspdf";
Here, we are importing React
and the jsPDF
class from the jspdf
library. React is needed for creating React components, and jsPDF
is 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 = '';
};
-
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 ofjsPDF
, 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>
);
}
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;
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.
Posted on April 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.