jQuery 如何使用 Jspdf 将 Html Tables 数据导出为 PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19807870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:37:58  来源:igfitidea点击:

How to export the Html Tables data into PDF using Jspdf

jqueryhtmljspdf

提问by Navyah

How do I export the tables in HTML page to PDF. I have done some sample data but I am unable to load the HTML table list into PDF, Please can any one help me in loading the Tables into PDF.

如何将 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/

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

回答by Oscar Acevedo

A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Hereis a demo.

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

enter image description here

在此处输入图片说明

回答by Nelli.Prashanth kumar

There is a tablePlugin for jspdfit expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.

jspdf有一个tablePlugin它需要对象数组并将该数据显示为表格。您可以对代码进行少量更改来设置文本和标题的样式。它是开源的,并且还有一些示例供您入门。

回答by Alimon Karim

Here is an example I think that will help you

这是我认为可以帮助您的示例

<!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>

Here the output

这里的输出

enter image description here

在此处输入图片说明

回答by pavell

Unfortunately it is not possible to do it.

不幸的是,这是不可能的。

jsPDF does not support exporting images and tables in fromHTMLmethod. in jsPDF v0.9.0 rc2

jsPDF 不支持在fromHTML方法中导出图像和表格。在 jsPDF v0.9.0 rc2

回答by Arunkumar Papena

Just follow these steps i can assure pdf file will be generated

只需按照这些步骤,我可以保证生成 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>

Output:

输出:

Html file output: html output

html文件输出: html 输出

Pdf file output: pdf output

pdf文件输出: pdf输出

回答by lando

"How to properly use jsPDF library" might give you a little more of what you need. The table won't render correctly (no css, per this answer), but you could do some parsing of the html table with jquery and manually style it yourself.

如何正确使用 jsPDF 库”可能会给你更多你需要的东西。该表将无法正确呈现(没有 css,根据此答案),但您可以使用 jquery 对 html 表进行一些解析并自己手动设置样式。

Another option would be to use screenshots of the HTML with HTML2Canvasor Casper.js.

另一种选择是使用HTML2CanvasCasper.js的 HTML 屏幕截图。

EDIT

编辑

Here's a basic example using the jspdf cell plugin. It uses jquery and the tableToJson()function from HTML Table to JSON.

这是一个使用 jspdf 单元插件的基本示例。它使用 jquery 和tableToJson()HTML Table 到 JSON的功能。

Be sure to include the Deflate lib (two js files) and jspdf.plugin.cell.js.

确保包含 Deflate 库(两个 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()

回答by Nikhil

Try to put

试着放

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

instead of

代替

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

回答by Aditya

I Used Datatable JS pluginfor my purpose of exporting an html table data into various formats. With my experience it was very quick, easy to use and configure with minimal coding.

我使用Datatable JS 插件来将 html 表格数据导出为各种格式。根据我的经验,它非常快速、易于使用和配置,只需最少的编码。

Below is a sample jquery call using datatable plugin, #exampleis your table id

下面是使用数据#example表插件的示例 jquery 调用,是您的表 ID

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

Please find the complete example in below datatable reference link :

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

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

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

This is how it looks after configuration( from reference site) : enter image description here

这是配置后的样子(来自参考站点): 在此处输入图片说明

You need to have following library references in your html ( some can be found in the above reference link)

您需要在 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