react实现模板打印
React 实现模板打印的方法
使用 react-to-print 库
安装 react-to-print 库:
npm install react-to-print
创建一个可打印的组件:
import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
const PrintableComponent = React.forwardRef((props, ref) => {
return (
<div ref={ref}>
<h1>打印内容标题</h1>
<p>这是要打印的内容</p>
</div>
);
});
const PrintButton = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<PrintableComponent ref={componentRef} />
<button onClick={handlePrint}>打印</button>
</div>
);
};
使用 window.print() 方法
直接调用浏览器打印功能:

const PrintComponent = () => {
const printContent = () => {
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<html>
<head>
<title>打印页面</title>
<style>
@media print {
body { font-family: Arial; }
.no-print { display: none; }
}
</style>
</head>
<body>
<h1>打印内容</h1>
<p>这是要打印的正文</p>
</body>
</html>
`);
printWindow.document.close();
printWindow.print();
};
return <button onClick={printContent}>打印</button>;
};
使用 CSS 控制打印样式
添加打印专用样式:
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
body {
font-size: 12pt;
color: #000;
}
}
在组件中应用:

<div>
<div className="no-print">屏幕显示但不打印的内容</div>
<div className="print-only">仅打印时显示的内容</div>
<button onClick={() => window.print()}>打印</button>
</div>
处理复杂打印布局
对于需要特殊布局的打印内容:
const ComplexPrintLayout = () => {
const printRef = useRef();
const handlePrint = () => {
const content = printRef.current.innerHTML;
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<html>
<head>
<title>复杂打印布局</title>
<style>
@page {
size: A4 landscape;
margin: 1cm;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
</head>
<body>
${content}
</body>
</html>
`);
printWindow.document.close();
printWindow.print();
};
return (
<div>
<div ref={printRef}>
<table>
<thead>
<tr>
<th>列1</th>
<th>列2</th>
</tr>
</thead>
<tbody>
<tr>
<td>数据1</td>
<td>数据2</td>
</tr>
</tbody>
</table>
</div>
<button onClick={handlePrint}>打印表格</button>
</div>
);
};
打印前数据处理
在打印前处理数据:
const DataPrintComponent = () => {
const [data, setData] = React.useState([]);
const printRef = useRef();
const fetchDataBeforePrint = async () => {
const response = await fetch('api/data');
const result = await response.json();
setData(result);
setTimeout(() => window.print(), 500); // 等待数据渲染
};
return (
<div>
<div ref={printRef}>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
<button onClick={fetchDataBeforePrint}>加载并打印数据</button>
</div>
);
};
这些方法提供了从简单到复杂的打印解决方案,可以根据具体需求选择适合的方式实现React应用的打印功能。





