如何将 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 访问表单,并将其存储在 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>
// 使用 html2pdf 从表单生成 pdf 的函数
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 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

