如何解决正文中的HTML JSPDF AUTOTABLE
您好,我正在尝试设置我的pdf文档。 我直接使用Javascript来构建它。
doc.autoTable({
head: [['Name','Email','Country']],body: [
['${MyVariable1}','${MyVariable2}','${MyVariable3}'],],})
但是现在我的变量之一具有HTML内容...我如何将其添加到正文并以HTML形式读取?
有可能吗?
预先感谢
解决方法
不可能用jspdf autotable
lib来实现。但是我创建了另一个可能的解决方案,可以解决您的问题。
首先,您需要构建表。我使用了jQuery,但是可以使用vanilla js:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
<footer>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var response = [
{
"Name":"test","Email":"test@example.com","Country":"Canada"
},{
"Name":"test2","Email":"test2@example.com","Country":"<div style='color: red'>USA</div>"
}
];
$(function() {
var $table = $('<table>');
var $tbody = $('<tbody>');
var $thead = $('<thead>');
$.each(['Name','Email','Country'],function(i,item) {
$thead.append(
$('<th>').html(item),)
});
$table.append($thead);
$.each(response,item) {
$('<tr>').append(
$('<td>').html(item.Name),$('<td>').html(item.Email),$('<td>').html(item.Country)
).appendTo($tbody);
});
$table.append($tbody)
$.ajax({
type: "POST",url: 'http://localhost:3000/convert',data: {
htmlBody: $table.prop('outerHTML')
},complete: function (status) {
window.open('http://localhost:3000/download')
},dataType: 'json'
});
});
</script>
</footer>
</html>
之后,您可以创建简单的节点js服务器,将其html代码转换为pdf:
var express = require('express');
var cors = require('cors');
var app = express();
var port = 3000
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
var pdf = require('html-pdf');
var fs = require('fs');
app.post('/convert',function(req,res,next) {
pdf.create(req.body.htmlBody).toStream(function(err,stream){
stream.pipe(fs.createWriteStream('./test.pdf'));
res.send(200)
});
});
app.get("/download",function (req,res) {
res.download("./test.pdf");
});
app.listen(port,() => {
console.log(`Example app listening at http://localhost:${port}`)
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。