In order to convert the HTML form data into pdf, the main approach is to use the html2pdf() function from the html2pdf library.
Approach: First, create a form with encryption type as text and add some input fields. After that, we need to use the html2pdf(element) function from the html2pdf library. Provide an onclick() functionality on the Submit button in the form. The html2pdf(element) function takes an input which is the id of the tag or form that needs to be converted to pdf format.
Example: This example shows the use of the above-explained approach.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width,initial-scale=1.0" > <!-- CSS only --> < link href = integrity = "sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin = "anonymous" rel = "stylesheet" > <!-- Html2Pdf --> < script src = integrity = "sha512vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin = "anonymous" > </ script > < style > .heading{ text-align: center; color: #2F8D46; } </ style > </ head > < body > < h2 class = "heading" > GeeksForGeeks </ h2 > <!-- Form encrypted as text --> < form id = "form-print" enctype = "text/plain" class = "form-control" > < label for = "name" > < strong >Name: </ strong > </ label > < input class = "form-control" type = "text" id = "name" name = "Name" placeholder = "Enter Name" > < br > < label for = "age" > < strong >Enter Age: </ strong > </ label > < input class = "form-control" type = "text" id = "age" name = "Age" placeholder = "Enter Age" > < br > < label for = "subject" > < strong >Select Subject: </ strong > </ label > < select class = "form-control" id = "subject" name = "subject" > < option value = "Web" > Web development </ option > < option value = "App" > App development </ option > < option value = "Others" > Others </ option > </ select > < br > < label for = "message" > < strong >Enter Message </ strong > </ label > < textarea class = "form-control" id = "message" name = "message" placeholder = "Enter you message" style = "height:100px" > </ textarea > < br > < input type = "button" class = "btn btn-primary" onclick = "GeneratePdf();" value = "GeneratePdf" > </ form > < script > // Function to GeneratePdf function GeneratePdf() { var element = document.getElementById('form-print'); html2pdf(element); } </ script > < script src = integrity = "sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin = "anonymous" > </ script > </ body > </ html > |
Output:
There is much functionality of the html2pdf library that you can explore in order to change the filename(of Pdf), its ratio, and much more. To explore more refer to the documentation of the html2pdf library.