
html2pdf 是一個 JavaScript 包,允許開發(fā)人員將 html 轉換為 canvas、pdf、映像等。它將 html 作為參數(shù)並將其添加到 pdf 或所需文件中。此外,它還允許用戶在添加 html 內容後下載該文件。
在這裡,我們將存取表單並使用html2pdf npm套件將其新增至pdf。我們將看到不同的範例,以向pdf添加表單資料。
文法
使用者可以按照以下語法將 html 表單資料作為文字並將其發(fā)送到 html2pdf。
var element = document.getElementById('form');
html2pdf().from(element).save();
在上面的語法中,我們使用 id 存取表單並使用 html2pdf() 方法將其新增至 pdf 。
範例1(將整個表單加入pdf)
在下面的範例中,我們建立了表單並指定「from」作為 id。此外,我們還在表單中加入了一些輸入元素。在 JavaScript 中,我們使用表單的 id 存取表單並將其儲存在「element」變數(shù)中。
之後,我們使用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 。
以上是如何將HTML表單資料作為文字並傳送到html2pdf?的詳細內容。更多資訊請關注PHP中文網其他相關文章!