react如何实现直接打印pdf
使用 react-to-print 库实现 PDF 打印
安装 react-to-print 库:
npm install react-to-print
创建一个可打印的组件:
import React from 'react';
import { useReactToPrint } from 'react-to-print';
class PrintableComponent extends React.Component {
render() {
return (
<div>
<h1>可打印内容</h1>
<p>这里是要打印的内容</p>
</div>
);
}
}
const PrintComponent = () => {
const componentRef = React.useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<PrintableComponent ref={componentRef} />
<button onClick={handlePrint}>打印</button>
</div>
);
};
export default PrintComponent;
使用 window.print() 方法
创建一个打印按钮并绑定 window.print():
const PrintButton = () => {
const handlePrint = () => {
window.print();
};
return <button onClick={handlePrint}>打印页面</button>;
};
添加打印样式到 CSS 文件:
@media print {
body * {
visibility: hidden;
}
.printable-area, .printable-area * {
visibility: visible;
}
.printable-area {
position: absolute;
left: 0;
top: 0;
}
.no-print {
display: none;
}
}
使用 html2canvas 和 jsPDF 生成 PDF
安装所需库:

npm install html2canvas jspdf
实现代码:
import React from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const PDFGenerator = () => {
const printRef = React.useRef();
const handleDownloadPdf = async () => {
const element = printRef.current;
const canvas = await html2canvas(element);
const data = canvas.toDataURL('image/png');
const pdf = new jsPDF();
const imgProperties = pdf.getImageProperties(data);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProperties.height * pdfWidth) / imgProperties.width;
pdf.addImage(data, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('print.pdf');
};
return (
<div>
<div ref={printRef}>
<h1>要转换为PDF的内容</h1>
<p>这里是详细内容</p>
</div>
<button onClick={handleDownloadPdf}>下载PDF</button>
</div>
);
};
export default PDFGenerator;
使用 @react-pdf/renderer 生成 PDF 文档
安装库:
npm install @react-pdf/renderer
创建 PDF 文档组件:

import React from 'react';
import { Page, Text, View, Document, StyleSheet, PDFDownloadLink } from '@react-pdf/renderer';
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
const PDFExport = () => (
<div>
<PDFDownloadLink document={<MyDocument />} fileName="somename.pdf">
{({ loading }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
</div>
);
export default PDFExport;
注意事项
确保打印内容在渲染时完全加载,避免打印空白页或部分内容
对于复杂布局,可能需要调整 CSS 打印样式以确保正确显示
某些浏览器可能需要用户手动允许弹出窗口进行打印操作
考虑添加加载状态,特别是在生成大型 PDF 文件时





