首页 > 解决方案 > jsPDF自动表格标题文本不起作用以及如何将html呈现到标题

问题描述

标头示例 在此处输入图像描述

使用许多在线示例我试图将标题文本打印到表格的顶部。我不能做的一件事是更新 jsPDF 和自动表格版本。这是由于代码最终出现的一些内部冲突。问题 1 是为什么标题没有呈现到顶部。第二个问题是如何将 html 呈现到标题的顶部,而不仅仅是文本。目前 doc.text 仅将字符串作为参数。

我想在头部呈现类似:“主标题小标题”的内容

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.60/jspdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.15/jspdf.plugin.autotable.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.15/jspdf.plugin.autotable.src.js"></script>
    </head>

<body>
    <button onclick="generatePdf()">Generate pdf</button>


    <script>
        function generatePdf(){

        var columns = [{
                title: "ID",
                dataKey: "id"
            },
            {
                title: "Name",
                dataKey: "name"
            },
            {
                title: "Country",
                dataKey: "country"
            },
        ];
        var rows = [{
                "id": 1,
                "name": "Shaw",
                "country": "Tanzania"
            },
            {
                "id": 2,
                "name": "Nelson",
                "country": "Kazakhstan"
            },
            {
                "id": 3,
                "name": "Garcia",
                "country": "Madagascar"
            },
        ];

        var doc = new jsPDF('p', 'pt');
        var headerTxt ="This is test header"
        var header = function (data) {
            doc.setFontSize(18);
            doc.setTextColor(40);
            doc.setFontStyle('normal');
            //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
            doc.text(headerTxt, data.settings.margin.left, 50);
        };
        var options = {
            beforePageContent: header,
            margin: {
                top: 80
            },
            startY: doc.autoTableEndPosY() + 20
        };
        doc.autoTable(columns, rows, options)

        doc.save('table.pdf'); 
    }
        </script>
        </body> 
        </html>

标签: javascriptjqueryjspdfjspdf-autotable

解决方案


不推荐使用 BeforePageContent .. 使用:

didDrawPage : header

作为替代。


推荐阅读