Welcome folks today in this blog post we will be inserting dynamic text with font size in pdf document using the input field in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and first of all you need to copy paste the cdn
library of jspdf as shown below
1 2 3 4 5 6 7 8 |
<!DOCTYPE html> <html lang="en"> <head> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> </html> |
And after that you need to have the input field where we will be getting the user input of text to export to pdf document in html as shown below
1 2 3 4 5 |
<form id="form"> <input type="text" id="text" required placeholder="Enter the text"> <input type="number" id="fontsize" value="15"/> <button onclick="generatePDF()">Generate PDF</button> </form> |
As you can we see we have the html5 form in which we have two input fields in which we have the text field where we will enter the text to insert in the pdf document and then we have the input number field to set the font size of the pdf document. And we have also provided the default font size which is 15 and then we have the button to generate pdf. And we have added onclick
event listener where we put the method which is generatePDF()
method in javascript.
And now we will be writing the function which is called generatePDF()
method when the button was clicked. So we will be writing this function as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function generatePDF(){ let text = document.getElementById('text').value let fontSize = document.getElementById('fontsize').value let doc = new jsPDF() doc.setFontSize(fontSize) doc.text(text,10,10) doc.save("output.pdf") } |
As you can see in this method we are getting all the values from the input fields which is the actual text to be inserted in the pdf document and the font size to be set for the text in pdf document. For setting the font size we are using the setFontSize()
method and also for adding the text we are using the text()
method in which we are inserting the text at x
and y
coordinates. And then we will be saving the pdf document using the save()
method and inside it we are providing the custom name. Now so now if you open the web app you will see the below pdf file created.