在有些需求中,需要把当前某部分的内容打印出来,在不需要后端配合的情况下,可以使用window.print()函数导出,window.print函数默认打印整个页面,如果想要设置打印的内容和样式,@media print{}就派上用场了,在html里设置添加不需要打印的class的样式为 display:none,然后在设置需要打印class的样式。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>导出html页面</title>
<style>
@media print {
.noprint {
display: none
}
}
</style>
<script type="text/javascript">
function printDoc() {
window.print();
}
</script>
</head>
<body>
<div id="topMenu" style="height: 50px;border: 1px solid black;" class="noprint">顶部菜单
<button onclick="printDoc()"> 打印</button>
</div>
<div style="height:600px;">
<div style="float: left;width: 400px;height: 100%;border: 1px solid black;" class="noprint">左侧菜单</div>
<div style="float: left;width: calc(100% - 404px);height: 100%;border: 1px solid white;">
<table style="width: 600px;margin: 20px auto;">
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>
</div>
</div>
</body>
</html>
html和pdf对比: