如何使用Javascript打印表格?

Pau*_*aul 13 javascript html-table

我发现这个代码用Javascript打印.

function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}
Run Code Online (Sandbox Code Playgroud)

元素ID"printTable"是我想要打印的表的ID,但不幸的是它只打印出表的内容而不是表的样式.我只想在它上面有边框,以便更容易阅读.谁能帮我?

dim*_*hik 27

这是jsfiddle示例中的代码.我测试了它,它看起来很好.

http://jsfiddle.net/dimshik/9DbEP/4/

我使用了一个简单的表,也许你在新页面上遗漏了一些用JavaScript创建的CSS.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>
Run Code Online (Sandbox Code Playgroud)

  • 我总是尊重添加jiffdle链接的人 (3认同)

Shi*_*med 5

你也可以使用jQuery插件来做到这一点

jQuery PrintPage插件

演示

  • 没关系.它只是一个额外的选择 (6认同)
  • OP清楚地说:`使用javascript打印表?` (3认同)

Roy*_*M J 5

一种厚脸皮的解决方案:

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }
Run Code Online (Sandbox Code Playgroud)

HTML:

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
Run Code Online (Sandbox Code Playgroud)


小智 5

我的同胞们,

2019年1月我使用了之前制作的代码:

 <script type="text/javascript">   
    function imprimir() {
        var divToPrint=document.getElementById("ConsutaBPM");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }
</script>
Run Code Online (Sandbox Code Playgroud)

理解:ConsutaBPM 是一个包含内部短语和表格的 DIV。我想打印所有内容、标题、表格和其他内容。问题是当尝试打印表格时......

该表可以用 BORDER 和 CELLPADDING 定义:

<table border='1' cellpadding='1' id='Tablbpm1' >
Run Code Online (Sandbox Code Playgroud)

效果很好!