react如何把dom转成PDF
使用html2canvas和jsPDF库
安装html2canvas和jsPDF库:
npm install html2canvas jspdf
在React组件中引入库并实现转换逻辑:
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
const exportToPDF = () => {
const input = document.getElementById('target-dom');
html2canvas(input).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 210; // A4宽度210mm
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('download.pdf');
});
};
使用react-pdf/renderer库
安装react-pdf库:
npm install @react-pdf/renderer
创建PDF文档组件:
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
const MyDocument = () => (
<Document>
<Page size="A4">
<View style={styles.section}>
<Text>Hello PDF</Text>
</View>
</Page>
</Document>
);
const styles = StyleSheet.create({
section: {
margin: 10,
padding: 10,
}
});
导出PDF文件:
import { PDFDownloadLink } from '@react-pdf/renderer';
<PDFDownloadLink document={<MyDocument />} fileName="document.pdf">
{({ loading }) => (loading ? 'Loading...' : 'Download')}
</PDFDownloadLink>
使用pdf-lib处理复杂PDF
安装pdf-lib库:
npm install pdf-lib
创建并修改PDF文档:
import { PDFDocument, rgb } from 'pdf-lib';
const createPDF = async () => {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([550, 750]);
page.drawText('Hello World', {
x: 50,
y: 700,
size: 50,
color: rgb(0, 0, 0),
});
const pdfBytes = await pdfDoc.save();
download(pdfBytes, 'document.pdf', 'application/pdf');
};
注意事项
DOM转PDF时需确保所有资源加载完成后再执行转换,特别是图片等异步资源
对于复杂布局,建议使用专门设计PDF的库如react-pdf而非html2canvas转换
考虑添加加载状态提示用户转换过程
PDF尺寸单位通常使用毫米(mm)或磅(pt),需注意与像素的换算







