微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正文中的HTML JSPDF AUTOTABLE

如何解决正文中的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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?