我尝试按照以下位置使用PrintImageLocations.java提取嵌入PDF的图像的x,y,宽度和高度:
https://svn.apache.org/repos/asf/pdfbox/tags/2.0.3/examples/src/main/java/org/apache/pdfbox/examples/util/PrintImageLocations.java
但是,返回值的所有实例都不符合我的期望。由于这些值太不合理了,因此我从下面的位置运行了SaveImagesInPdf类,以确保PDFBox查看的是正确的图像,并且确实确实找到并提取了所需的图像。
https://www.tutorialkart.com/pdfbox/extract-images-from-pdf-using-pdfbox/
我期望提取特定文本时,我作为Rectangle2D输入到PDFTextStripperByArea类的x,y,宽度和高度相同。
我已经做了大量的互联网研究,但我找不到真正的答案。从我所阅读的内容来看,我认为我用来提取文本的坐标系与用于图像的坐标系不同。
如果是这种情况,是否仍然可以将PrintImageLocations.java带回的值转换为我用于PDFTextStripperByArea的Rectangle2D坐标?
在此问题上的任何帮助将不胜感激。
最佳答案
我有一个类似的问题。我图像的Y位置偏离了(页面顶部而不是页面底部)。经过大量搜索,我终于找到了一个新的PrintImageLocations,其中包含以下代码,该代码进行了必要的调整以纠正问题所在:
PDImageXObject image = (PDImageXObject)xobject;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
float imageXScale = ctmNew.getScalingFactorX();
float imageYScale = ctmNew.getScalingFactorY();
float yScaling = ctmNew.getScaleY();
float angle = (float)Math.acos(ctmNew.getValue(0, 0)/ctmNew.getScaleX());
if (ctmNew.getValue(0, 1) < 0 && ctmNew.getValue(1, 0) > 0)
{
angle = (-1)*angle;
}
PDPage page = getCurrentPage();
double pageHeight = page.getMediaBox().getHeight();
ctmNew.setValue(2, 1, (float)(pageHeight - ctmNew.getTranslateY() - Math.cos(angle)*yScaling));
ctmNew.setValue(2, 0, (float)(ctmNew.getTranslateX() - Math.sin(angle)*yScaling));
// because of the moved 0,0-reference, we have to shear in the opposite direction
ctmNew.setValue(0, 1, (-1)*ctmNew.getValue(0, 1));
ctmNew.setValue(1, 0, (-1)*ctmNew.getValue(1, 0));
System.out.println("NEW NEW: position in PDF = " + ctmNew.getTranslateX() + ", " + ctmNew.getTranslateY() + " in user space units");