Welcome folks today in this blog post we will be adding the dynamic form
input image in pdf document using jspdf
and html2canvas
in pdf document using 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 copy paste the following code
index.html
1 2 3 4 5 6 |
<input type="file" id="file" required> <canvas id="canvas" width="400" height="400"></canvas> <button onclick="downloadPDF()">Export to PDF</button> </div> <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> |
As you can see we are including the jspdf
and html2canvas library cdn and also we are having the input form field where we allow the user to select the image and then we have the canvas where we will be drawing the selected image by the user. And then we have the button to export the image to pdf document. And now we need to include the javascript
code as shown below
script.js
1 2 3 |
let image = document.getElementById('file') let canvas = document.getElementById('canvas') let ctx = canvas.getContext('2d') |
As you can see we have declared three variables where we are targeting the input
file dom element. And then we are targeting the canvas
dom element. And then we are also creating the 2d
context.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
document.getElementById('file').addEventListener('change',(e) => { let reader = new FileReader() reader.onload = function(event){ let image = new Image() image.onload = function(){ canvas.width = image.width canvas.height = image.height ctx.drawImage(image,0,0) } image.src = event.target.result } reader.readAsDataURL(e.target.files[0]) }) |
As you can see in the above code when the input file is changed we are reading the file using the filereader api. And after that we are drawing the image on the canvas using the image width and height.
1 2 3 4 5 6 7 8 9 10 |
function downloadPDF(){ html2canvas(canvas).then((canvas) => { var imgData = canvas.toDataURL('image/png') let doc = new jsPDF() doc.addImage(imgData,'PNG',0,0) doc.save("output.pdf") }) } |
And now we are defining the downloadPDF()
function where we are taking the screenshot of the selected image file by the user and then we are converting the canvas image to base64 string url. And then we are adding the base64 image inside the pdf document using the addImage()
method. And then we are saving the pdf document using the save()
method.