通过JavaScript / jQuery打印html

问题描述 投票:1回答:3

我希望通过传递自定义HTML代码来打印文档。

我写的非工作代码:

function Clickheretoprint()
{
  var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
      disp_setting+="scrollbars=yes,width=780, height=780, left=100, top=25"; 
  var content_vlue = document.getElementById("result_tbl").innerHTML; 

  var docprint=window.open("","",disp_setting); 
  docprint.document.open(); 
  docprint.document.write('<html><head><title>Ashley Mattresses</title>'); 
  docprint.document.write('</head><body onLoad="self.print()"><center>');          
  docprint.document.write('<TABLE width="100%" cellpadding=10 align=center  valign="top"><TR valign="top"><TD width = "33%" valign="top">col1</TD><TD width = "33%" valign="top">col2</TD><TD width = "33%" valign="top">col3</TD></TR></TABLE>');     
  docprint.document.write('</center></body></html>'); 
  docprint.document.close(); 
  docprint.focus(); 
  docprint.close();
}

这是我调用锚标记的href的方法,但没有完成工作:

<a href="javascript:Clickheretoprint()">

我是JavaScript / jQuery编码的初学者。

javascript jquery html html5 jquery-ui
3个回答
7
投票

你走在正确的轨道上。假设result_tbl是你想要按原样打印的元素的ID,首先用<div>标签包装元素,例如:

<div>
    <table id="result_tbl">
        .....
    </table>
</div>

然后有这样的代码:

var docprint=window.open("about:blank", "_blank", disp_setting); 
var oTable = document.getElementById("result_tbl");
docprint.document.open(); 
docprint.document.write('<html><head><title>Ashley Mattresses</title>'); 
docprint.document.write('</head><body><center>');
docprint.document.write(oTable.parentNode.innerHTML);
docprint.document.write('</center></body></html>'); 
docprint.document.close(); 
docprint.print();
docprint.close();

Live test case

在Chrome 18下工作正常


1
投票

结帐:http://jsfiddle.net/5Wfqr/3/

对我来说,唯一的麻烦来源是:

var content_vlue = document.getElementById("result_tbl").innerHTML; 

您的HTML中是否包含ID为“result_tbl”的元素?


0
投票

这段代码对我来说很好

<body>
        <script type="text/javascript">
            function printPage() {

                var docprint = window.open("about:blank", "_blank"`enter code here`, "channelmode");    
                var oTable = document.getElementById("tbl");
                docprint.document.open(); 
                docprint.document.write('<html><head><title>your title</title>'); 
                docprint.document.write('</head><body><center>');
                docprint.document.write(oTable.innerHTML);
                docprint.document.write('</center></body></html>'); 
                docprint.document.close(); 
                docprint.print();
                docprint.close();
            }
        </script>
        <table id="tbl">
            <tr>
                <td> content1 </td>
                <td> content2 </td>
            </tr>
        </table>
        <input type="button" value ="print" id="printButton" onclick="javascript:printPage()"/>
    </body>
© www.soinside.com 2019 - 2024. All rights reserved.