
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 中。
立即学习“前端免费学习笔记(深入)”;
在下面的示例中,我们创建了表单并指定“from”作为 id。此外,我们还在表单中添加了一些输入元素。在 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>
在下面的示例中,我们将把表单的内容添加到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中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号