需要引入的文件:
import domtoimage from 'dom-to-image'; import pdfMake from 'pdfmake';
需要截取的元素:
<div ref={screenRef}></div>
点击截取导出:
<button onClick={captureScreen}>截屏并保存为PDF</button>
const screenRef = useRef(null);
const captureScreen = async () => {
const element = screenRef.current; // 要截取的元素
const totalHeight = element.scrollHeight; // 页面总高度
const chunkHeight = 500; // 每个分段的高度
const numChunks = Math.ceil(totalHeight / chunkHeight); // 计算总段落数
const chunks = []; // 存储每个段落的图像数据URL
// 分段截取页面
for (let i = 0; i < numChunks; i++) {
const top = i * chunkHeight; // 当前段落的顶部位置
const bottom = Math.min((i + 1) * chunkHeight, totalHeight); // 当前段落的底部位置
try {
// 使用dom-to-image库截取当前段落的元素,并指定高度、宽度和位置进行适当的裁剪
const dataUrl = await domtoimage.toPng(element, {
height: bottom - top,
width: element.clientWidth,
style: { transform: `translate(0px, -${top}px)` },
});
chunks.push(dataUrl); // 将截取的图像数据URL存储到chunks数组中
} catch (error) {
console.error('截图出错:', error);
}
}
const content = chunks.map((dataUrl) => ({ image: dataUrl, width: 500 })); // 将图像数据URL转换为pdfMake可接受的内容格式
const pdf = new pdfMake.createPdf({ content }); // 创建PDF实例,传入内容参数
pdf.download('exported_pdf.pdf'); // 下载生成的PDF文件
};