猿问

尝试将 html 表打印为 pdf 时出错

我正在尝试将 html 表打印为 pdf。在 javascript 中打印表格的代码如下所示:


function createPDF(){

    var table = document.getElementById('mytable');


    var style = "<style>";

    style = style + "table {width: 100%;font: 17px Calibri;}";

    style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";

    style = style + "padding: 2px 3px;text-align: center;}";

    style = style + "</style>";


    // CREATE A WINDOW OBJECT.

    var win = window.open('', '', 'height=700,width=700');


    win.document.write('<html><head>');

    win.document.write('<title>Profile</title>');   // <title> FOR PDF HEADER.

    win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.

    win.document.write('</head>');

    win.document.write('<body>');

    win.document.write(table);         // THE TABLE CONTENTS INSIDE THE BODY TAG.

    win.document.write('</body></html>');


    win.document.close();   // CLOSE THE CURRENT WINDOW.


    win.print();    // PRINT THE CONTENTS.

}

该表如果用 javascript 动态填充,不知道这是否重要。无论如何,每当我尝试打印 html 表格时,我都会在我的 pdf 文档中得到 [object HTML TableElement]。有人知道问题出在哪里吗?


LEATH
浏览 123回答 1
1回答

幕布斯6054654

您需要从表中获取 HTML - 您只获取对象 - 而不是执行var table = document.getElementById('mytable').outerHTML&nbsp;或将表对象附加到 win.document 但无论如何你真的应该只写一次function createPDF(){&nbsp; &nbsp; const table = document.getElementById('mytable').outerHTML;&nbsp; &nbsp; const style = `<style>&nbsp; &nbsp; &nbsp;table {width: 100%;font: 17px Calibri;}&nbsp;&nbsp; &nbsp; &nbsp;table, th, td {border: solid 1px #DDD; border-collapse: collapse;&nbsp;&nbsp; &nbsp; &nbsp;padding: 2px 3px;text-align: center;}&nbsp;&nbsp; &nbsp; &nbsp;</style>`;&nbsp; &nbsp; // CREATE A WINDOW OBJECT.&nbsp; &nbsp; const win = window.open('', '', 'height=700,width=700');&nbsp; &nbsp; const html = `<title>Profile</title>&nbsp; &nbsp; ${style}&nbsp; &nbsp; ${table}`;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; win.document.write(html);&nbsp; &nbsp; win.document.close();&nbsp; &nbsp;&nbsp; &nbsp; win.print();&nbsp; &nbsp;&nbsp;}使用对象(未测试):function createPDF(){&nbsp; &nbsp; const table = document.getElementById('mytable');&nbsp; &nbsp; const style = document.createElement("style");&nbsp; &nbsp; style.textContent = `table {width: 100%;font: 17px Calibri;}&nbsp;&nbsp; &nbsp; &nbsp;table, th, td {border: solid 1px #DDD; border-collapse: collapse;&nbsp;&nbsp; &nbsp; &nbsp;padding: 2px 3px;text-align: center;}`&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; // CREATE A WINDOW OBJECT.&nbsp; &nbsp; const win = window.open('', '', 'height=700,width=700');&nbsp; &nbsp; const doc = win.document;&nbsp; &nbsp; const title = document.createElement("title");&nbsp; &nbsp; title.textContent = "Profile"&nbsp; &nbsp; doc.body.append(title);&nbsp; &nbsp; doc.body.append(style);&nbsp; &nbsp; doc.body.append(table);&nbsp; &nbsp; win.print();&nbsp; &nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答