如何將HTML表單資料作為文字獲取併發送到html2pdf?
html2pdf是一個JavaScript包,允許開發人員將html轉換為canvas、pdf、影像等。它將html作為引數,並將其新增到pdf或所需文件中。此外,它還允許使用者在將html內容新增到文件後下載該文件。
在這裡,我們將訪問表單並使用html2pdf npm包將其新增到pdf。我們將看到將表單資料新增到pdf的不同示例。
語法
使用者可以按照以下語法將HTML表單資料作為文字獲取併發送到html2pdf。
var element = document.getElementById('form'); html2pdf().from(element).save();
在上述語法中,我們使用id訪問了表單,並使用html2pdf()方法將其新增到pdf。
示例1(將整個表單新增到pdf)
在下面的示例中,我們建立了表單並將其id設定為“from”。此外,我們在表單中添加了一些輸入元素。在JavaScript中,我們使用其id訪問了表單,並將其儲存在“element”變數中。
之後,我們使用html2pdf()方法將表單新增到pdf。在輸出中,使用者可以觀察到,當他們單擊提交按鈕時,它會下載包含表單輸入標籤和值的pdf。
<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"> </script> </head> <body> <h3> Using the <i> html2pdf </i> to create a pdf using the content of the form </h3> <!-- creating a sample form with 3 to 4 input fields with labels --> <form id = "form"> <label for = "name"> Name: </label> <input type = "text" id = "name" name = "name"> <br> <br> <label for = "email"> Email: </label> <input type = "email" id = "email" name = "email"> <br> <br> <input type = "button" value = "Submit" onclick = "generatePDF()"> </form> <script> // function to generate a pdf from the form using html2pdf function generatePDF() { // get the form element var element = document.getElementById('form'); // create a new pdf using the form element html2pdf().from(element).save(); } </script> </body> </html>
示例2(僅將表單內容新增到pdf)
在下面的示例中,我們將表單的內容新增到pdf中,而不是整個表單。我們建立了表單並添加了一些輸入欄位,就像我們在第一個示例中所做的那樣。
在JavaScript中,我們使用其id訪問每個輸入的值。之後,我們使用JavaScript建立“div”元素,並使用“innerHTML”屬性將表單內容新增到div元素的HTML中。
接下來,我們使用div元素的內容建立pdf。
<html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"> </script> </head> <body> <h3> Using the <i> html2pdf </i> to create a pdf using the content of the form </h3> <!-- creating a sample form with 3 to 4 input fields with labels --> <form id = "form"> <label for = "name"> Name: </label> <input type = "text" id = "name" name = "name"> <br> <br> <label for = "comment"> Comment: </label> <input type = "comment" id = "comment" name = "comment"> <br> <br> <input type = "button" value = "Submit" onclick = "getContentInPDF()"> </form> <script> function getContentInPDF() { // access form elements one by one var name = document.getElementById('name').value; var comment = document.getElementById('comment').value; // create a single html element by adding form data var element = document.createElement('div'); element.innerHTML = '<h1>Form Data</h1>' + '<p>Name: ' + name + '</p>' + '<p>Comment: ' + comment + '</p>'; // create a new pdf using the form element html2pdf().from(element).save(); } </script> </body> </html>
使用者學習瞭如何使用html2pdf將表單資料新增到pdf中。我們只需要呼叫html2pdf()方法,它將處理所有事情。在第一個示例中,我們將整個表單和輸入值新增到pdf中,在第二個示例中,我們提取了表單資料並將其新增到pdf中。
廣告