PdfBox文字定位并且插入图片

Github地址

PDF文字定位插入图片

核心库



    org.apache.pdfbox
    pdfbox
    2.0.22

效果示例

所有演示基于AllPdfSearch

普通文档PDF

// 传入需要查找的文字和图片插入时需要定位的文字下标
PrintTextLocations stripper = new PrintTextLocations("审核单位盖章", 5);
image
PrintTextLocations stripper = new PrintTextLocations("授权签署人签字", 6);

image

可以看到图片定位到下标5的"章"字,以及下标6的"字"字

特殊类PDF

image
PrintTextLocations stripper = new PrintTextLocations("北京/广州办事处", 7);
image

核心代码

  • 重写 writeString获取文字坐标相关信息
@Override
protected void writeString(String text, List textPositions) throws IOException {
    for (int i = 0; i < textPositions.size(); i++) {
        TextPosition textInfo = textPositions.get(i);
        String pdfStringTxt = textInfo.getUnicode();
        List targetStringList = List.of(this.targetString.split(""));
        int targetSize = targetStringList.size();
        String firstString = targetStringList.get(0);
        boolean findTarget = false;
        // 打印文字
//            log.info("{}, X: {}, Y: {}", pdfStringTxt, textInfo.getX(), textInfo.getY());
        if (firstString.equals(pdfStringTxt)) {
            for (int j = 1; j 

提示

  • 获取的文字Y轴是没有计算空行的,解析时忽略的空行
  • 目前定位文字跨行了就无法定位因为PDFbox的原因,本人暂时未做处理

你可能感兴趣的:(PdfBox文字定位并且插入图片)