如何将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中。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP