簡體   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