使用 javascript 将 HTML 表格转换为 pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26100014/
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-10-28 05:30:28  来源:igfitidea点击:

HTML table to pdf using javascript

javascripthtmlangularjspdfjspdf

提问by Alex Man

I have created an appliction for downloading a html table to pdf using javascript i used jsPDFplugin. The application is working fine but the problem is that the table is not proper. The width of the table as well as the header is not properly alligned. I am using angularjs for creating the table.

我创建了一个应用程序,用于使用jsPDF插件使用 javascript 将 html 表下载到 pdf 。应用程序工作正常,但问题是表格不正确。表格和标题的宽度未正确对齐。我正在使用 angularjs 创建表格。

Can anyone please give me some suggestion for this problem

任何人都可以就这个问题给我一些建议

JSFiddle

JSFiddle

function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'letter');
    source = $('#customers')[0];
    specialElementHandlers = {
        '#bypassme': function (element, renderer) {
            return true
        }
    };
    margins = {
        top: 4,
        bottom: 4,
        left: 4,
        width: 522
    };
    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) {
        pdf.save('Test.pdf');
    }, margins);
}

回答by mb21

I guess you currently have to do that manually (fiddle):

我猜您目前必须手动执行此操作(小提琴):

function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'letter');

    pdf.cellInitialize();
    pdf.setFontSize(10);
    $.each( $('#customers tr'), function (i, row){
        $.each( $(row).find("td, th"), function(j, cell){
            var txt = $(cell).text().trim() || " ";
            var width = (j==4) ? 40 : 70; //make 4th column smaller
            pdf.cell(10, 50, width, 30, txt, i);
        });
    });

    pdf.save('sample-file.pdf');
}