繁体   English   中英

如何使用Javascript打印表格?

[英]How to print table using Javascript?

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

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

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

这是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>

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

jQuery PrintPage插件

演示

一个厚脸皮的解决方案:

  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;

    }

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>

我的伙伴们,

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

要解决:ConsutaBPM是一个包含内部短语和表格的DIV。 我想打印ALL,标题,表格等。 问题是当TRIED打印TABLE时......

表mas用BORDER和CELLPADDING定义:

<table border='1' cellpadding='1' id='Tablbpm1' >

它工作得很好!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM