You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PDF.js中文本与图片坐标关联:Transform坐标系转换适配问题

PDF文本与图片坐标匹配问题

我有一个包含图片与文本的PDF,需要实现页面中文本内容与图片内容的位置关联。当前视口尺寸为612×792,所有文本内容的y值处于0-792区间,但图片的lastTransform y值为2181.25,经视口转换后为-1389,而实际图片显示在文本正上方。我无法理解如何将文本的y坐标(约540)与图片的坐标关联,希望能将图片坐标转换为与文本一致的坐标系(如y≈535),使其与渲染位置匹配。

获取文本Transform的代码

const page = await pdfDoc.getPage(pageNum);
const textContent = await page.getTextContent();
const operatorList = await page.getOperatorList();
const viewPort = await page.getViewport({ scale: 1.0 });

for (let i = 0; i <= 25; i++) {
  let item = textContent.items[i];
  const tx = pdfjsLib.Util.transform(
    viewPort.transform,
    item.transform
  );
  console.log(item)
  console.log("################  ITEM TX");
  console.log(tx)
}

代码输出示例

{
  str: '06:14:59 pm',
  dir: 'ltr',
  width: 51.8906226578906,
  height: 8.999999625,
  transform: [
    8.999999625,
    0,
    0,
    8.999999625,
    93.74999609374998,
    251.25002253125012
  ],
  fontName: 'g_d0_f3',
  hasEOL: false
}
################  ITEM TX
[
  8.999999625,
  0,
  0,
  -8.999999625,
  93.74999609374998,
  540.7499774687499
]

获取图片信息的代码

let lastTransform = null;
for (let j = 0; j < operatorList.fnArray.length; j++) {
  const fn = operatorList.fnArray[j];
  if (fn === pdfjsLib.OPS.transform) {
    lastTransform = operatorList.argsArray[j];
  } else if (fn === pdfjsLib.OPS.paintImageXObject) {
    const args = operatorList.argsArray[j];
    const imageId = args[0]; // The name of the image XObject
    const imageXObject = await page.objs.get(imageId);
    console.log(imageXObject)
    const tx = pdfjsLib.Util.transform(
      viewPort.transform,
      lastTransform
    );
    console.log(tx)
  }
}

代码输出示例

{
  width: 2016,
  height: 1512,
  interpolate: undefined,
  kind: 2,
  data: Uint8ClampedArray(9144576) [
    84, 76, 65, 83, 75, 64, 82, 74, 63, 83, 75, 64,
    84, 76, 65, 86, 78, 67, 87, 79, 68, 87, 79, 68,
    82, 74, 63, 85, 77, 66, 84, 76, 65, 82, 74, 63,
    84, 76, 65, 89, 81, 70, 86, 78, 67, 78, 70, 59,
    82, 74, 63, 82, 74, 63, 83, 75, 64, 83, 75, 64,
    83, 75, 64, 83, 75, 64, 82, 74, 63, 82, 74, 63,
    84, 76, 65, 82, 74, 63, 81, 73, 62, 81, 73, 62,
    81, 73, 62, 82, 74, 63, 82, 74, 63, 82, 74, 63,
    80, 72, 61, 80,
    ... 9144476 more items
  ],
  dataLen: 9144576,
  ref: '22R'
}
################  LAST TRANSFORM
[ 1250, 0, 0, -937.5, 390.625, 2181.25 ]
################  TX
[ 1250, 0, 0, 937.5, 390.625, -1389.25 ]

内容的提问来源于stack exchange,提问作者obf73

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 08:14:51