react实现前端生成pdf
使用 react-pdf 库生成 PDF
react-pdf 是一个流行的 React 库,专门用于生成 PDF 文件。它提供了一套 React 组件,可以直接在 React 应用中渲染 PDF 内容。
安装 react-pdf:
npm install @react-pdf/renderer
创建一个简单的 PDF 文档组件:
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
const styles = StyleSheet.create({
page: {
flexDirection: 'column',
backgroundColor: '#E4E4E4',
padding: 10
},
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>
);
export default MyDocument;
渲染并下载 PDF:
import { PDFDownloadLink } from '@react-pdf/renderer';
import MyDocument from './MyDocument';
const App = () => (
<div>
<PDFDownloadLink document={<MyDocument />} fileName="somename.pdf">
{({ loading }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
</div>
);
使用 jsPDF 生成 PDF
jsPDF 是一个纯 JavaScript 库,可以在客户端生成 PDF 文件,适合需要更精细控制 PDF 生成的场景。
安装 jsPDF:
npm install jspdf
基本使用示例:
import { jsPDF } from "jspdf";
const generatePDF = () => {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
};
function App() {
return (
<div>
<button onClick={generatePDF}>Generate PDF</button>
</div>
);
}
添加图片和表格:
// 添加图片
doc.addImage(imageData, 'JPEG', 15, 40, 180, 160);
// 添加表格
const data = [
['Name', 'Age', 'Country'],
['John', '30', 'USA'],
['Jane', '25', 'UK']
];
doc.autoTable({
head: [data[0]],
body: data.slice(1),
startY: 80
});
使用 html2canvas 和 jsPDF 生成 PDF
这种方法适合需要将 React 组件直接转换为 PDF 的场景,先使用 html2canvas 捕获 DOM 元素,再用 jsPDF 生成 PDF。
安装依赖:
npm install jspdf html2canvas
实现代码:
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
const printDocument = () => {
const input = document.getElementById('divToPrint');
html2canvas(input).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0);
pdf.save("download.pdf");
});
};
function App() {
return (
<div>
<div id="divToPrint">
<h1>This will be printed</h1>
<p>All content here will be converted to PDF</p>
</div>
<button onClick={printDocument}>Print</button>
</div>
);
}
使用 pdf-lib 进行高级 PDF 操作
pdf-lib 是一个强大的库,可以创建和修改 PDF 文档,支持嵌入字体、添加交互式表单等高级功能。
安装 pdf-lib:
npm install pdf-lib
基本使用示例:
import { PDFDocument, rgb } from 'pdf-lib';
async function createPdf() {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([550, 750]);
page.drawText('Creating PDFs in JavaScript is awesome!', {
x: 50,
y: 700,
size: 30,
color: rgb(0.95, 0.1, 0.1),
});
const pdfBytes = await pdfDoc.save();
download(pdfBytes, "pdf-lib_creation_example.pdf", "application/pdf");
}
性能优化和注意事项
对于复杂文档,考虑分页渲染以避免内存问题。react-pdf 支持动态分页,可以自动处理内容溢出。
使用 web worker 处理大型 PDF 生成任务,避免阻塞主线程。pdf-lib 和 jsPDF 都支持在 worker 中运行。
对于包含大量文本的文档,预加载字体可以提高性能。react-pdf 支持自定义字体嵌入。
在服务器端生成场景,可以考虑使用 Puppeteer 无头浏览器捕获页面并生成 PDF,但这需要 Node.js 后端支持。







