React.js中如何在PDF iFrame用坐标实现表单字段联动高亮
解决PDF与表单联动高亮的步骤
一、先搞懂坐标逻辑
API返回的坐标是PDF页面的相对比例值,四个参数顺序为:
x1:区域左上角相对于PDF页面宽度的比例(0=最左侧,1=最右侧)y1:区域左上角相对于PDF页面高度的比例(0=最顶部,1=最底部)x2:区域右下角相对于PDF页面宽度的比例y2:区域右下角相对于PDF页面高度的比例
比如示例里的0.466, 0.250, 0.510, 0.259,意思是这个区域覆盖了PDF页面宽度的46.6%到51.0%、高度的25.0%到25.9%的范围。
二、关联表单字段与坐标数据
先把API返回的数据整理成键值对,方便通过表单字段快速匹配对应坐标:
// 假设API返回的原始数据存在data变量中 const fieldCoordsMap = data.reduce((map, item) => { // 假设表单输入框的name属性和item.value一一对应,比如<input name="First Name"> map[item.value] = item.coordinates.split(',').map(num => parseFloat(num.trim())); return map; }, {});
三、监听表单字段的聚焦事件
给所有表单输入字段绑定focus事件,触发PDF高亮逻辑;同时绑定blur事件移除高亮:
const formInputs = document.querySelectorAll('form input'); formInputs.forEach(input => { input.addEventListener('focus', () => { const targetCoords = fieldCoordsMap[input.name]; if (targetCoords) { showPDFHighlight(targetCoords); } }); input.addEventListener('blur', () => { hidePDFHighlight(); }); });
四、计算绝对位置并生成高亮层
通过iframe的实际显示尺寸,把相对坐标转换成像素值,动态创建高亮div:
function showPDFHighlight(coords) { const pdfIframe = document.getElementById('pdf-viewer'); const iframeRect = pdfIframe.getBoundingClientRect(); const pdfDisplayWidth = iframeRect.width; const pdfDisplayHeight = iframeRect.height; // 计算高亮框的绝对像素位置和尺寸 const leftOffset = coords[0] * pdfDisplayWidth; const topOffset = coords[1] * pdfDisplayHeight; const highlightWidth = (coords[2] - coords[0]) * pdfDisplayWidth; const highlightHeight = (coords[3] - coords[1]) * pdfDisplayHeight; // 先移除已有高亮 hidePDFHighlight(); // 创建高亮层元素 const highlightLayer = document.createElement('div'); highlightLayer.id = 'pdf-highlight'; highlightLayer.style.position = 'absolute'; highlightLayer.style.left = `${iframeRect.left + leftOffset}px`; highlightLayer.style.top = `${iframeRect.top + topOffset}px`; highlightLayer.style.width = `${highlightWidth}px`; highlightLayer.style.height = `${highlightHeight}px`; highlightLayer.style.backgroundColor = 'rgba(255, 255, 0, 0.3)'; // 半透明黄色高亮 highlightLayer.style.pointerEvents = 'none'; // 不遮挡PDF的交互操作 highlightLayer.style.zIndex = 1000; document.body.appendChild(highlightLayer); } function hidePDFHighlight() { const existingHighlight = document.getElementById('pdf-highlight'); if (existingHighlight) { existingHighlight.remove(); } }
注意事项
- 确保PDF iframe没有拉伸变形,要和API坐标的基准尺寸(原始PDF尺寸)比例一致,否则高亮位置会偏移
- 如果PDF有多页,API返回的数据需要额外包含页码字段,高亮时要先切换到对应页码再显示高亮层
- 若使用PDF.js这类内嵌PDF查看器,可能需要直接操作iframe内部的页面DOM,通过
pdfIframe.contentDocument访问内部元素后再添加高亮层
内容的提问来源于stack exchange,提问作者Rohit Verma
相关产品推荐
相关产品推荐

