简体   繁体   中英

How the coordinates of the browser preview map to the coordinates in the PDF file

I now have a PDF file that is rendered in PDFBox into a single image per page

// 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
}

The image saved in this step will be previewed in the browser. The user can drag and drop the image into this preview, and then I map this coordinate to the real PDF, but there is always some error. Here is how I mapped:

  1. Get the preview in the browser's width, height , get drag and drop images in the preview in the upper left corner of the x, y
  2. The backend fetches the PDF's actual width, height , and then computes the width, height , and height of the preview, resulting in a drag-and-drop image at the top left of the PDF in x, y
  3. Because the origin of coordinates in PDF is the lower left corner of the document, the final formula for x and y is:

    • x: float targetX = (previewX 1.0F / previewWidth) pdfPageWidth;
    • y: float targetY = pdfPageHeight - (previewY 1.0F / previewHeight) pdfPageHeight - dragImageHeight
  4. According to the previous calculation of x, y in this page PDF to draw this figure, but there are errors, and the error is obvious, how can I do?

Reference document

iText

Edit I also try use 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());

```

麻烦了将近一个星期,终于解决了问题,算法本身没有问题,但是第三方系统会缩放目标图像,用这种缩放比例计算位置是准确的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM