Welcome folks today in this blog post we will be generating a pdf document from dynamic text present in the input field. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a index.html
file inside which we will be having a textarea widget inside that we will be providing the dynamic text and then we have a button to trigger the pdf file download as an attachment using the jspdf library.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> body { background: #ffdeaa; color: #3d3d3d; margin: 20px; } #imgCat { width: 25%; } </style> <body> <h1>jsPDF Demo</h1> <p>This is a sample of how to use <a href="https://parall.ax/products/jspdf">jsPDF</a>.</p> <p> Write some text and donwload a pdf file with your content</p> <textarea id="txtContent" cols="60" rows="15"></textarea> <br /> <button id="btnDownload"> Download PDF </button> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script> </html> |
And now we will write the javascript
code to generate the pdf document using the dynamic text coming from the textarea widget
script.js
1 2 3 4 5 6 7 8 9 10 11 12 |
var content = document.getElementById('txtContent'), button = document.getElementById('btnDownload'); function generatePDF(){ var doc = new jsPDF(); doc.setFontSize(14); doc.text(20, 20, content.value); doc.save('my.pdf'); } button.addEventListener('click', generatePDF); |
Now if you open the index.html
and if you hit the generate pdf button then a new pdf document will be created it will look something like this as shown below