react如何实现下载页面成pdf
使用html2canvas和jsPDF库
安装依赖库html2canvas和jsPDF:
npm install html2canvas jspdf
创建一个React组件并实现下载功能:
import React from 'react';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
const DownloadPDF = () => {
const downloadPDF = () => {
const input = document.getElementById('content-to-export');
html2canvas(input).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('download.pdf');
});
};
return (
<div>
<div id="content-to-export">
{/* 这里放需要导出为PDF的内容 */}
<h1>PDF导出示例</h1>
<p>这是将被导出为PDF的内容</p>
</div>
<button onClick={downloadPDF}>下载PDF</button>
</div>
);
};
export default DownloadPDF;
使用react-pdf库
安装react-pdf库:
npm install @react-pdf/renderer
创建PDF文档组件:

import React from 'react';
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>PDF文档标题</Text>
<Text>这是使用react-pdf生成的PDF内容</Text>
</View>
</Page>
</Document>
);
const styles = StyleSheet.create({
page: {
padding: 30
},
section: {
margin: 10
}
});
export default MyDocument;
实现下载功能:
import React from 'react';
import { PDFDownloadLink } from '@react-pdf/renderer';
import MyDocument from './MyDocument';
const DownloadButton = () => (
<PDFDownloadLink document={<MyDocument />} fileName="document.pdf">
{({ loading }) => (loading ? '加载中...' : '下载PDF')}
</PDFDownloadLink>
);
export default DownloadButton;
使用浏览器打印功能
通过CSS媒体查询优化打印样式:
@media print {
body * {
visibility: hidden;
}
#printable-area, #printable-area * {
visibility: visible;
}
#printable-area {
position: absolute;
left: 0;
top: 0;
}
}
在React组件中触发打印:

const PrintComponent = () => {
const handlePrint = () => {
window.print();
};
return (
<div>
<div id="printable-area">
{/* 可打印内容 */}
<h1>可打印内容</h1>
</div>
<button onClick={handlePrint}>打印/保存为PDF</button>
</div>
);
};
注意事项
确保要导出的内容完全加载后再触发PDF生成,特别是包含异步数据或图片时
对于复杂布局,可能需要调整html2canvas的配置参数以获得更好的渲染效果
考虑添加加载状态指示器,因为PDF生成可能需要一些时间
测试不同浏览器的兼容性,某些功能可能在特定浏览器中表现不同






