如何让PDF页面子元素宽度不超过可拖拽调整的父容器pdfContainer?
解决PDF页面超出父容器宽度的问题
1. 调整CSS约束页面最大宽度
先修改.pdfPage的样式,添加最大宽度限制和盒模型设置,确保页面不会超出父容器的可用宽度:
.pdfPage { width: auto; max-width: 100%; box-sizing: border-box; margin-bottom: 5px; }
max-width: 100%强制PDF页面宽度不超过父容器的宽度box-sizing: border-box确保页面的内边距、边框不会额外增加宽度,避免超出容器
2. 动态计算PDF缩放比例(适配拖拽调整的容器宽度)
因为父容器支持左右拖拽调整宽度,需要实时监听容器宽度变化,动态调整PDF的缩放比例,替代固定的projAttribute.pdfScale:
步骤1:给容器添加Ref
const pdfContainerRef = useRef<HTMLDivElement>(null);
并绑定到pdfContainer元素上:
<div id="pdfContainer" ref={pdfContainerRef} className={styles.previewBody} onScroll={(e) => handlePdfScroll(e)}> <Document options={options} file={curPdfUrl} onLoadSuccess={onDocumentLoadSuccess}> {renderPages(numPages)} </Document> </div>
步骤2:监听容器宽度变化并更新缩放比例
使用ResizeObserver监听容器尺寸变化,实时计算合适的缩放比例:
import { useEffect, useState } from 'react'; // 新增状态存储原始页面宽度 const [originalPageWidth, setOriginalPageWidth] = useState<number>(0); useEffect(() => { const container = pdfContainerRef.current; if (!container) return; const updateScale = () => { const containerWidth = container.offsetWidth; if (containerWidth > 0 && originalPageWidth > 0) { // 计算适配容器宽度的缩放比例,若需要留边距可调整计算逻辑(比如containerWidth - 20) const newScale = containerWidth / originalPageWidth; // 更新projAttribute中的pdfScale setProjAttribute(prev => ({ ...prev, pdfScale: newScale })); } }; // 初始化时计算一次 updateScale(); // 监听容器尺寸变化 const observer = new ResizeObserver(updateScale); observer.observe(container); return () => observer.disconnect(); }, [originalPageWidth]);
步骤3:在文档加载成功时获取原始页面宽度
修改onDocumentLoadSuccess方法,获取PDF页面的原始宽度:
const onDocumentLoadSuccess = async (document: PDFDocumentProxy) => { const firstPage = await document.getPage(1); const viewport = firstPage.getViewport({ scale: 1 }); setOriginalPageWidth(viewport.width); setNumPages(document.numPages); };
3. 优化父容器布局
调整.previewBody的样式,优化滚动和对齐效果:
.previewBody { flex-grow: 1; background-color: rgb(233, 233, 233); display: flex; overflow: auto; /* 仅在需要时显示滚动条 */ justify-content: center; align-items: flex-start; /* 避免页面顶部被容器截断 */ padding: 10px 0; /* 可选,给页面上下增加留白 */ }
内容的提问来源于stack exchange,提问作者Dolphin
相关产品推荐
相关产品推荐

