React中设置大屏幕viewport为1280px解决PDF导出UI变形问题
问题描述
使用HTML2Canvas和jsPDF导出PDF文档时,浏览器视口宽度为1280px时生成的PDF能正常显示UI;但视口宽度大于1280px时,UI会出现变形。尝试通过修改viewport meta标签的content属性为width=1280来解决,该方法在小设备上有效,但在大屏幕设备上无效。
解决方案
核心思路是脱离原页面视口限制,强制以固定宽度渲染目标DOM,避免视口尺寸影响PDF生成效果,具体实现:
- 创建离线隐藏容器,固定宽度为1280px,克隆目标DOM到该容器中进行渲染
- 利用html2canvas的
width参数强制固定渲染宽度,保证不同屏幕下渲染结果一致 - 渲染完成后清理离线容器,不影响原页面布局
修改后的代码如下:
const pdfExport = async (sections: any[]) => { dispatch(setIsexporting(true)); const doc = new jsPDF("p", "mm"); const targetWidth = 1280; // 固定渲染宽度 const offlineContainer = document.createElement('div'); // 设置离线容器样式:固定宽度、隐藏不影响原页面 Object.assign(offlineContainer.style, { position: 'fixed', top: '-9999px', left: '-9999px', width: `${targetWidth}px`, height: 'auto', overflow: 'hidden' }); document.body.appendChild(offlineContainer); const pageHeight = 292; // PDF页面高度 for (let index = 0; index < sections.length; index++) { const section = sections[index]; const divToPrint = section.current; if (divToPrint.clientHeight > 20) { // 克隆目标DOM到离线容器 const clonedDiv = divToPrint.cloneNode(true) as HTMLElement; offlineContainer.appendChild(clonedDiv); // 强制以1280px宽度渲染,适配高清屏 const canvas = await html2canvas(clonedDiv, { width: targetWidth, scale: window.devicePixelRatio || 1, useCORS: true }); const imgData = canvas.toDataURL("image/jpeg", 1); const imgWidth = 206; // PDF内图片宽度(适配A4边距) const imgHeight = (canvas.height * imgWidth) / canvas.width; const positionX = 2; const positionY = 2; if (index > 0) { doc.addPage(); } doc.addImage( imgData, "JPEG", positionX, positionY, imgWidth, imgHeight ); // 填充页面剩余空白区域 const remainingSpace = pageHeight - (positionY + imgHeight) + 4; if (remainingSpace > 0) { doc.setFillColor(247, 248, 250); doc.rect(positionX, positionY + imgHeight, imgWidth, remainingSpace, "F"); } // 添加页面边框 doc.setDrawColor(247, 248, 250); doc.setLineWidth(5); doc.rect(0, 0, 210, 298); // 移除当前克隆的DOM offlineContainer.removeChild(clonedDiv); if (index === sections.length - 1) { doc.save("exhibitors_statistics.pdf"); } } } // 清理离线容器 document.body.removeChild(offlineContainer); dispatch(setIsexporting(false)); };
关键说明
- 离线容器:完全隔离原页面视口影响,确保渲染环境固定
- 固定宽度渲染:html2canvas的
width参数强制以1280px宽度生成画布,解决不同视口下的UI变形问题 - 高清适配:使用设备像素比作为缩放比例,避免生成的PDF出现模糊
内容的提问来源于stack exchange,提问作者Rishav Singh
相关产品推荐
相关产品推荐

