如何调整jspdf的表宽度

时间:2014-10-06 04:50:36

标签: jquery html pdf jspdf

我这里有一个简单的表格,我希望使用jspdf以pdf格式导出。它是一个20列表,其中有隐藏列,也将以pdf格式导出。我这里有一个问题的例子:jsfiddle.net/riichan/1f8pbpg8/5/

这是我在导出为pdf时使用的代码:

function demoFromHTML() {
    $("td:hidden,th:hidden","#tab_customers").show();
    var pdf = new jsPDF('p', 'pt', 'letter');
    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#customers')[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: 40,
        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('Test.pdf');
    }, margins);
}

正如你在输出中看到的那样,这是一团糟。

修改

我已尝试过下面的代码,但它仅适用于表格中的固定值,因为您需要手动调整列宽,并且只能编辑一个列宽。

function demoFromHTML() {
        $("td:hidden,th:hidden","#tab_customers").show();
    var pdf = new jsPDF('l', 'pt', 'a4');
     pdf.cellInitialize();
    pdf.setFontSize(10);
    $.each( $('#tab_customers tr'), function (i, row){
        $.each( $(row).find("td, th"), function(j, cell){
             var txt = $(cell).text().trim().split(" ").join("\n") || " ";
             var width = (j==0) ? 70 : 45; //make with column smaller
             //var height = (i==0) ? 40 : 30;
             pdf.cell(10, 50, width, 50, txt, i);
        });
    });
        pdf.save('Test.pdf');

}

这是示例:jsfiddle

0 个答案:

没有答案