先去官网下载 printJs 文件
https://codeleading.com/article/82084960757/#google_vignette // window.print()原生 打印背景色失效问题
https://printjs.crabbly.com/ // 官网文档
https://blog.csdn.net/weixin_39602178/article/details/133761418 // 字体大小无效问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.header-wrap,
.body-wrap {
list-style: none;
display: flex;
margin: 0;
padding: 0;
}
.header-wrap li,
.body-wrap li {
width: 100px;
/* border-bottom: 1px solid #ccc;
border-right: 1px solid #ccc; */
text-align: center;
}
.header-wrap {
background-color: rgba(99, 110, 122);
color: #fff;
}
.body-wrap:nth-child(odd) {
background-color: rgb(239, 239, 239);
}
.body-wrap {
font-size: 16px;
padding: 2px;
}
.content-wrap {
width: 300px;
margin: 0 auto;
}
</style>
<style type="text/css" media="print,screen">
div {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
color-adjust: exact;
}
</style>
<body>
<div style="display: none;">
<div class="content-wrap" id="printHtml">
<ul class="header-wrap">
<li class="header">序号</li>
<li class="header">商品名称</li>
<li class="header">价格</li>
<li class="header">数量</li>
</ul>
<ul class="body-wrap">
<li class="header">1</li>
<li class="header">苹果</li>
<li class="header">12</li>
<li class="header">5</li>
</ul>
<ul class="body-wrap">
<li class="header">2</li>
<li class="header">香蕉</li>
<li class="header">9</li>
<li class="header">4</li>
</ul>
<ul class="body-wrap">
<li class="header">3</li>
<li class="header">橘子</li>
<li class="header">13</li>
<li class="header">7</li>
</ul>
<ul class="body-wrap">
<li class="header">4</li>
<li class="header">火龙果</li>
<li class="header">16</li>
<li class="header">1</li>
</ul>
</div>
</div>
</body>
</html>
<script src="./print.js"></script>
<script>
setTimeout(() => {
printJS({
printable: "printHtml",
type: "html",
targetStyles: '*',
// 默认800,设置1000是因为我窗口宽度是1000,而导致页面靠近左边,设置1000就正常居中了。
})
}, 1000);
</script>