使用浏览器自带的打印来打印网页的内容,但是往往打印效果都是默认的,如何通过样式自定义打印内容的样式?
选取打印区域
- 建立一个id为
print-area
的区域
<div
id="print-area"
style={{
display: 'none',
}}
>
<div
style={{
width: '195px',
border: '1px dashed #333',
fontWeight: 'bold',
display: 'flex',
flexDirection: 'column',
}}
>
<div style={{ paddingBottom: '20px' }}>
<div>
<span style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<img
src="http://weber.pub/usr/uploads/2020/08/2171937504.png"
alt={'logo'}
style={{ width: '35px', height: '35px' }}
/>
</span>
</div>
<div style={{ display: 'flex', paddingTop: '15px' }}>
编号:<span style={{ fontSize: '12px' }}>12fhahfd1111</span>
</div>
<div style={{ display: 'flex', paddingTop: '5px' }}>
<div style={{ width: '70%' }}>
金额:<span style={{ fontSize: '12px' }}>$ 100.00</span>
</div>
<div style={{ width: '30%', fontSize: '13px' }}>
<span>未结账</span>
</div>
</div>
</div>
</div>
</div>
- 打印事件
const doPrint = () => {
//判断iframe是否存在,不存在则创建iframe
let iframe = document.getElementById('print-iframe');
iframe ? document.body.removeChild(iframe) : null;
let el = document.getElementById('print-area');
iframe = document.createElement('IFRAME');
let doc = null;
// 选取打印区域
iframe.setAttribute('id', 'print-iframe');
// 设置iframe位置,不显示到前台
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
// 把iframe添加到dom中
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 这里可以自定义样式
// @page 可以设置打印区域到边框的距离
doc.write(
'<style>body{margin:0}p{margin: 0}div{orphans: 23;widows: 23; page-break-after: avoid}@page{margin: 10px 0 0 20px;}</style>',
);
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf('MSIE') > 0) {
document.body.removeChild(iframe);
}
};
注意
- 样式只能是行内样式,才能带到打印预览
- 图片只能是网络地址图片,不可用本地图
- 打印边距也可通过更多设置-边距-自定义设置