浏览器预览的坐标如何映射到 PDF 文件中的坐标
How the coordinates of the browser preview map to the coordinates in the PDF file
我现在有一个 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 中,但总是会出现一些错误。这是我的映射方式:
- 在浏览器中获取预览
width, height
,在上层预览中获取拖放图片left corner of the x, y
- 后端获取 PDF 的
actual width, height
,然后计算 width, height
和预览的高度,从而在 [中的 PDF 左上角生成拖放图像=18=]
由于PDF中的坐标原点是文档的左下角,所以x和y的最终公式为:
- x: float targetX = (previewX 1.0F / previewWidth) pdfPageWidth;
- y: float targetY = pdfPageHeight - (previewY 1.0F / previewHeight) pdfPageHeight - dragImageHeight
根据之前计算的本页PDF中的x,y来画这个图,但是有错误,而且错误很明显,怎么办?
参考文档
编辑
我也尝试使用 iText:
```
矩形 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());
```
困扰了将近一个星期,终于解决了问题,算法本身没有问题,但是第三方系统会对目标图片进行缩放,这个缩放计算出来的位置是准确的。
我现在有一个 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 中,但总是会出现一些错误。这是我的映射方式:
- 在浏览器中获取预览
width, height
,在上层预览中获取拖放图片left corner of the x, y
- 后端获取 PDF 的
actual width, height
,然后计算width, height
和预览的高度,从而在 [中的 PDF 左上角生成拖放图像=18=] 由于PDF中的坐标原点是文档的左下角,所以x和y的最终公式为:
- x: float targetX = (previewX 1.0F / previewWidth) pdfPageWidth;
- y: float targetY = pdfPageHeight - (previewY 1.0F / previewHeight) pdfPageHeight - dragImageHeight
根据之前计算的本页PDF中的x,y来画这个图,但是有错误,而且错误很明显,怎么办?
参考文档
编辑 我也尝试使用 iText: ``` 矩形 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());
```
困扰了将近一个星期,终于解决了问题,算法本身没有问题,但是第三方系统会对目标图片进行缩放,这个缩放计算出来的位置是准确的。