一、引入依赖
在package.json的dependencies中加入"react-to-print": "2.14.7",然后执行yarn获取依赖
二、编写打印逻辑
/**
页面组件
*/
import React, { useRef, useEffect } from 'react';
import ReactToPrint from 'react-to-print'
import styles from './index.less'
const PdfView = (props) => {
const componentRef = useRef()
return (
<>
<ReactToPrint
trigger={() => <a href="#" style={{ fontSize: '13px' }}><Icon type="file_download_black-o" />下载</a>}
content={() => componentRef.current}
/>
<div ref={componentRef} id='pdfViewId' className={styles.pdfView}>
要打印的东西
</div>
</>
)
}
/**
index.less样式文件
*/
@media all {
.page-break {
display: none;
}
}
@media print {
html, body {
height: initial !important;
overflow: initial !important; // 如果出现无法分页加入此属性
-webkit-print-color-adjust: exact;
}
}
@media print {
.page-break {
margin-top: 1rem;
display: block;
page-break-before: auto;
}
}
@page {
size: auto;
margin: 16px 0; // 打印页样式
}