【问题标题】:Get Images by rectangle按矩形获取图像
【发布时间】:2017-08-03 18:04:37
【问题描述】:

我有这个方法可以提取pdf中特定位置的文本

public static void getTextByRectangle(PDDocument doc,Rectangle rect) throws IOException{
    PDFTextStripperByArea stripper = new PDFTextStripperByArea();
    stripper.setSortByPosition( true );
    stripper.addRegion( "class1", rect );
    PDPage firstPage = doc.getPage(0);
    stripper.extractRegions( firstPage );
    System.out.println( "Text in the area:" + rect );
    System.out.println( stripper.getTextForRegion( "class1" ) );
}

除了提取图像之外,是否可以做同样的事情?

【问题讨论】:

    标签: java image pdf pdfbox


    【解决方案1】:

    是的,您可以提取所有图像,并比较 rectimages 的位置。这是pdfbox 的示例。这可以获得图像位置。

    1. 你需要创建一个类扩展PDFStreamEngine。像这样,

      public class PrintImageLocations extends PDFStreamEngine

    2. 您应该覆盖processOperator。而从ctmNew,你可以得到图片的位置,然后将image与你的rect进行比较,你会得到正确的图片。

      @Override
      protected void processOperator(Operator operator, List<COSBase> operands)  throws IOException {
          String operation = operator.getName();
          if ("Do".equals(operation)) {
              COSName objectName = (COSName) operands.get(0);
              PDXObject xobject = getResources().getXObject(objectName);
              if (xobject instanceof PDImageXObject) {
                   PDImageXObject image = (PDImageXObject) xobject;
                   Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
                   float imageXScale = ctmNew.getScalingFactorX();
                   float imageYScale = ctmNew.getScalingFactorY();
                   // position in user space units. 1 unit = 1/72 inch at 72 dpi
                   System.out.println("position in PDF = " + ctmNew.getTranslateX() + ", " + ctmNew.getTranslateY() + " in user space units");
                   // displayed size in user space units
                   System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in user space units");
              } else if (xobject instanceof PDFormXObject) {
                   PDFormXObject form = (PDFormXObject) xobject;
                   showForm(form);
              }
          } else {
              super.processOperator(operator, operands);
          }
      }
      

    感谢 mkl 和 FiReTiTi 的建议。

    【讨论】:

    • 请不要仅提供链接答案;至少将示例中的关键代码复制到您的答案中。
    猜你喜欢
    • 2017-11-23
    • 2015-07-11
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多