如何使用Jspdf将HTML表格数据导出为PDF

22

如何将HTML页面中的表格导出为PDF?我已经编写了一些示例数据,但是我无法将HTML表格列表加载到PDF中,请问有人能帮助我将表格加载到PDF中吗?

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>html2canvas example</title>
        <script type="text/javascript" src="js/jquery/jquery-1.7.1.min.js"></script>    
        <script type="text/javascript" src="js/jspdf.js"></script>    
        <script type="text/javascript" src="libs/FileSaver.js/FileSaver.js"></script>
        <script type="text/javascript" src="js/jspdf.plugin.standard_fonts_metrics.js"></script>
        <script type="text/javascript" src="js/jspdf.plugin.split_text_to_size.js"></script>
        <script type="text/javascript" src="js/jspdf.plugin.from_html.js"></script>    

        <script type="text/javascript">
            $(document).ready(function() { 
                var specialElementHandlers = {
                    '#editor': function(element, renderer) { return true; }
                };

                $('#cmd').click(function() {
                    var doc = new jsPDF();

                    doc.fromHTML($('#target').html(), 15, 15, {
                        'width': 170,'elementHandlers': specialElementHandlers
                    });

                    doc.save('sample-file.pdf');
                });  
            });
        </script>
    </head>
    <body id="target">
        <div id="content">
            <h3>Hello, this is a H3 tag</h3>

            <a class="upload">Upload to Imgur</a>    
            <h2>this is <b>bold</b> <span style="color:red">red</span></h2>

            <table border="1">
                <tr>
                    <th>Header 1</th>
                    <th>Header 2</th>
                </tr>
                <tr>
                    <td>row 1, cell 1</td>
                    <td>row 1, cell 2</td>
                </tr>
                <tr>
                    <td>row 2, cell 1</td>
                    <td>row 2, cell 2</td>
                </tr>
            </table>
        </div>

        <button id="cmd">generate PDF</button>
    </body>
</html>

http://jsfiddle.net/y2b7Q/327/

8个回答

15
一个不错的选择是AutoTable(jsPDF的表格插件),它包含主题、rowspan、colspan、从html中提取数据,可以与json一起使用,您还可以个性化您的标题并使其水平。 这里有一个演示。

输入图像描述


7

有一个针对jspdf的tablePlugin,它期望一个对象数组,并将数据显示为表格。您可以通过少量代码更改来样式化文本和标题。它是开源的,并且还有示例供您开始使用。


6

很遗憾,这是不可能的。

jsPDF在v0.9.0 rc2版本中不支持从HTML导出图片和表格。


7
是的,答案是“正确的”,但回答这个问题并不恰当。 OP正在寻求帮助以导出为pdf,并已经展示了一些尝试。 - jbutler483

6

这里有一个我认为会对你有帮助的例子

<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
    $(function(){
         var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

   $('#cmd').click(function () {

        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p','pt', 'a4', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
            console.debug(row);
            $.each(row, function (j, cell){
                doc.cell(10, 50,120, 50, cell, i);  // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
            })
        })


        doc.save('sample-file.pdf');
    });
    function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }


    // go through cells
    for (var i=0; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
                <thead>
                    <tr>    
                        <th>Name</th>
                        <th>Email</th>
                        <th>Track</th>
                        <th>S.S.C Roll</th>
                        <th>S.S.C Division</th>
                        <th>H.S.C Roll</th>
                        <th>H.S.C Division</th>
                        <th>District</th>

                    </tr>
                </thead>
                <tbody>

                        <tr>
                            <td>alimon  </td>
                            <td>Email</td>
                            <td>1</td>
                            <td>2222</td>
                            <td>as</td>
                            <td>3333</td>
                            <td>dd</td>
                            <td>33</td>
                        </tr>               
                </tbody>
            </table>
<button id="cmd">Submit</button>
</body>
</html>

这里是输出结果。

在此输入图片描述


3
只需按照以下步骤,我可以保证生成PDF文件。
    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


    <script type="text/javascript">
        $(document).ready(function() {

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

输出:

HTML文件输出: html output

PDF文件输出: pdf output


3
"如何正确使用jsPDF库" 可能会给您更多所需的信息。表格不会正确呈现(没有css,根据此答案),但您可以使用jquery对html表格进行一些解析,并手动为其设置样式。
另一个选择是使用HTML的屏幕截图,使用 HTML2CanvasCasper.js编辑 这里有一个使用jspdf单元格插件的基本示例。它使用jquery和 HTML表格转JSON 中的 tableToJson() 函数。
请确保包含Deflate lib(两个js文件)和 jspdf.plugin.cell.js
var table = tableToJson($('#table-id').get(0))
var doc = new jsPDF('p', 'pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
  $.each(row, function (j, cell){
    doc.cell(10, 200, 100, 20, cell, i);
  })
})
doc.save()

2
尝试放置

标签

doc.fromHTML($('#target').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

替代

doc.fromHTML($('#target').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

0

我使用了Datatable JS插件来将HTML表格数据导出为各种格式。根据我的经验,这个插件非常快速、易于使用和配置,只需最少量的编码即可完成。

以下是一个使用Datatable插件的jQuery调用示例,其中#example是您的表格ID:

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
        ]
    } );
} );

请在下面的数据表参考链接中找到完整的示例:

https://datatables.net/extensions/buttons/examples/html5/simple.html

这是配置后的外观(来自参考网站): {{link1:enter image description here}}
您需要在html中引用以下库(有些可以在上面的参考链接中找到)。
jquery-1.12.3.js
jquery.dataTables.min.js
dataTables.buttons.min.js
jszip.min.js
pdfmake.min.js
vfs_fonts.js
buttons.html5.min.js

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接