Welcome folks today in this blog post we will be creating the pdf document and adding text with custom font and size in it using jspdf library in react.js using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project using the below commands as shown below
npx create-react-app samplepdf
cd samplepdf
Now you need to install the jspdf
library using the below npm command
npm i jspdf
After installing this you will see the below directory structure of the react.js project as shown below
Now you need to copy paste the below code inside the App.js
file of the react.js project as shown below
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React from "react"; import { jsPDF } from "jspdf"; import "./styles.css"; export default function App() { function generateSimplePDF() { const doc = new jsPDF(); doc.text("Hello World !!!", 10, 10); doc.setFont("courier") doc.setFontSize(50) doc.text("There is more text",10,50); doc.save("Document.pdf"); } return ( <div className="App"> <button onClick={generateSimplePDF}>Click me!</button> </div> ); } |
As you can see in the above code we have the simple button of Generate PDF and when we click the button we execute the function called generateSimplePDF()
and inside this function we are calling the constructor of jsPDF()
and inside it we are using the text()
method to add text at x and y coordinates and also we are setting the custom font and size of the text. And lastly we are saving the pdf as an attachment using the save()
method of jspdf.
Now if you run the project
inside the browser you will see the output as shown below