react如何实现打印pdf功能
使用react-to-print库
安装react-to-print库:
npm install react-to-print
创建一个可打印的组件:
import React from 'react';
import { useReactToPrint } from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<div>
<h1>打印内容标题</h1>
<p>这是要打印的内容</p>
</div>
);
}
}
const Example = () => {
const componentRef = React.useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<ComponentToPrint ref={componentRef} />
<button onClick={handlePrint}>打印</button>
</div>
);
};
使用PDF库生成PDF
安装pdf-lib库:

npm install pdf-lib
创建并下载PDF文件:
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
const generatePdf = async () => {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
page.drawText('Hello World!', {
x: 50,
y: height - 50,
size: 30,
font,
color: rgb(0, 0, 0),
});
const pdfBytes = await pdfDoc.save();
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'document.pdf';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
使用浏览器打印API
直接调用浏览器打印功能:

const handlePrint = () => {
window.print();
};
// 在组件中
<button onClick={handlePrint}>打印页面</button>
样式调整优化打印效果
添加打印样式表:
@media print {
body * {
visibility: hidden;
}
.print-container, .print-container * {
visibility: visible;
}
.print-container {
position: absolute;
left: 0;
top: 0;
width: 100%;
}
.no-print {
display: none;
}
}
使用html2canvas和jspdf组合
安装依赖:
npm install html2canvas jspdf
实现截图转PDF:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
const exportToPDF = async (elementId, fileName) => {
const element = document.getElementById(elementId);
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
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(`${fileName}.pdf`);
};






