浏览器预览的坐标如何映射到 PDF 文件中的坐标



我现在有一个PDF文件,它以PDFBox呈现为每页的单个图像

// load pdf and save image
try (PDDocument document = PDDocument.load("some file")) {
PDFRenderer render = new PDFRenderer(document);
BufferedImage scaledImage = render.renderImageWithDPI(pageIndex, 326);
// save image
}

在此步骤中保存的图像将在浏览器中预览。用户可以将图像拖放到此预览中,然后我将此坐标映射到真实的PDF,但总是存在一些错误。这是我的映射方式:

  1. 在浏览器width, height中获取预览,在上部left corner of the x, y的预览中获取拖放图像
  2. 后端获取 PDF 的actual width, height,然后计算预览的width, height和高度,从而在 PDF 的左上角生成一个拖放图像x, y
  3. 由于 PDF 中坐标的原点是文档的左下角,因此 x 和 y 的最终公式为:

    • x: float targetX = (previewX 1.0F/previewWidth) pdfPageWidth;
    • y: float targetY = pdfPageHeight - (previewY 1.0F/previewHeight) pdfPageHeight - dragImageHeight
  4. 按照前面计算的x、y在这个页面PDF中画出这个图,但是有误差,而且误差明显,我该怎么办?

参考文档

目录

编辑我也尝试使用iText: ``` Rectangle cropBox = reader.getCropBox(firstPageIndex);

float widthRatio = renderRandomX * 1.0F / renderWidth;
float heightRatio = renderRandomY * 1.0F / renderHeight;
float offsetLLX = cropBox.getWidth() * widthRatio;
float offsetLLY = cropBox.getHeight() - cropBox.getHeight() * heightRatio;
Rectangle drawSignRect = new Rectangle(cropBox.getLeft() + cropBox.getWidth() * widthRatio,
cropBox.getBottom() + offsetLLY,
cropBox.getLeft() + offsetLLX + signImage.getWidth(),
cropBox.getBottom() + offsetLLY + signImage.getHeight());

'''

困扰了将近一周,终于解决了问题,算法本身没问题,但第三方系统会缩放目标图像,用这种缩放计算位置是准确的。

最新更新