y∩__∩y 归来
于 2022-06-10 15:16:43 发布
1366
收藏 7
分类专栏: JavaScript 文章标签: 前端 javascript typescript
版权
JavaScript
专栏收录该内容
6 篇文章0 订阅
订阅专栏
打印功能实现
效果预览
目录
打印功能实现
效果预览
一、html 写法
二、js或ts写法
总结
一、html 写法
<div id="exportableTable" style="display: none;">
<table border="1" style="border-collapse:collapse;width: 100%;text-align: center;">
<tr rowspan="2">
<!-- 表头 -->
<th colspan="7">经费账(科目:)</th>
</tr>
<tr cospan="7">
<!-- 表头 -->
<th rowspan="2">日期</th>
<th rowspan="1">凭证</th>
<th rowspan="2">摘要</th>
<th rowspan="2">收方</th>
<th rowspan="2">付方</th>
<th rowspan="2">收或付</th>
<th rowspan="2">余额</th>
</tr>
<tr cospan="7">
<!-- 表头 -->
<th rowspan="1">顺序号</th>
</tr>
<!-- 行 -->
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
</table>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
二、js或ts写法
代码如下(示例):
printFee () {
const printContent = document.getElementById("exportableTable");
// window.open() 弹出窗口
const WindowPrt = window.open('', '', 'left=500px,top=500px,width=900,height=900,toolbar=0,scrollbars=0,status=0');//弹出一个空的窗口(设置好宽高)
// write()方法用于写入文档内容,可以传多个参数,写入的字符串会按HTML解析
WindowPrt.document.write(printContent.innerHTML);
// 运行document.write(),运行完后,最好手动关闭文档写入document.close()
WindowPrt.document.close();
//方法将焦点设置到当前窗口,也就是将窗口显示在前(靠近屏幕)
WindowPrt.focus();
// 调用 print() 方法会产生一个打印预览弹框,让用户可以设置打印请求。
WindowPrt.print();
// window.close()关闭浏览器窗口
WindowPrt.close();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
总结
关键在于html要使用 id='exportableTable’ , js通过document.getElementById(“exportableTable”)将要打印的内容获取,
通过.write()写入文档内容到新弹出的窗口,
再调用 print() 方法产生一个打印预览弹框,即可实现打印
————————————————
版权声明:本文为CSDN博主「y∩__∩y 归来」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43730595/article/details/125221010
联系客服