PDF文件中,如何根据关键字,获取坐标信息

package com.dhcc.zhfc.elesign.util;

import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.hibernate.annotations.common.util.StringHelper;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PdfBoxKeyWordPosition
 * @Description TODO
 * @Author 86173
 * @Date 2020/5/11 15:14
 * @Version 1.0
 */
public class PdfBoxKeyWordPosition extends PDFTextStripper {
    // 关键字字符数组
    private char[] key;
    // PDF文件路径
    private String pdfPath;
    private byte[] fileBytes;
    // 坐标信息集合
    private List<float[]> list = new ArrayList<float[]>();
    // 当前页信息集合
    private List<float[]> pagelist = new ArrayList<float[]>();
    // 有参构造方法
    public PdfBoxKeyWordPosition(String keyWords, String pdfPath,byte[] bin) throws IOException {
        super();
        super.setSortByPosition(true);
        this.pdfPath = pdfPath;
        this.fileBytes= bin;
        char[] key = new char[keyWords.length()];
        for (int i = 0; i < keyWords.length(); i++) {
            key[i] = keyWords.charAt(i);
        }
        this.key = key;
    }
    public char[] getKey() {
        return key;
    }
    public void setKey(char[] key) {
        this.key = key;
    }
    public String getPdfPath() {
        return pdfPath;
    }
    public void setPdfPath(String pdfPath) {
        this.pdfPath = pdfPath;
    }
    // 获取坐标信息
    public List<float[]> getCoordinate() throws IOException {
        try {
            if(!StringHelper.isEmpty(pdfPath)){
                document = PDDocument.load(new File(pdfPath));
            }
            if(document==null&&fileBytes!=null){
                document = PDDocument.load(fileBytes);
            }
            int pages = document.getNumberOfPages();
            for (int i = 1; i <= pages; i++) {
                pagelist.clear();
                super.setSortByPosition(true);
                super.setStartPage(i);
                super.setEndPage(i);
                Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
                super.writeText(document, dummy);
                for (float[] li : pagelist) {
                    li[2] = i;
                }
                list.addAll(pagelist);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
        }
        return list;
    }

    // 获取坐标信息
    @Override
    protected void writeString(String string, List<TextPosition> textPositions) throws IOException {
        for (int i = 0; i < textPositions.size(); i++) {
            String fonts = textPositions.get(i).getFont().getName();
            String str = textPositions.get(i).getUnicode();
            if (str.equals(key[0] + "")) {
                int count = 0;
                for (int j = 0; j < key.length-1; j++) {
                    String s = "";
                    try {
                        s = textPositions.get(i + j).getUnicode();
                    } catch (Exception e) {
                        s = "";
                    }
                    if (s.equals(key[j] + "")) {
                        count++;
                    }
                }
                if (count == key.length-1) {
                    float[] idx = new float[3];
                    // 需要进行一些调整 使得章盖在字体上
                    // X坐标 在这里加上了字体的长度,也可以直接 idx[0] = textPositions.get(i).getX()
                    idx[0] = textPositions.get(i).getX()+textPositions.get(i).getFontSize();
                    // Y坐标 在这里减去的字体的长度,也可以直接 idx[1] = textPositions.get(i).getPageHeight()-textPositions.get(i).getY()
                    idx[1] = textPositions.get(i).getHeight()-textPositions.get(i).getY()-4*textPositions.get(i).getFontSize();
                    System.out.println("x=" + idx[0] + ",y=" + idx[1]);
                    pagelist.add(idx);
                    return;
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String pdfPath = "C:\\Users\\pangq\\Desktop\\555.pdf";
        File file = new File(pdfPath);
        //PDDocument doc = PDDocument.load(file);
        String keyWords = "纪海祥";
        //PDImageXObject pdImage = PDImageXObject.createFromFile("C:/Programs/test/sign.png", doc);
        byte[] bytes = File2byte(file);
        PdfBoxKeyWordPosition pdf = new PdfBoxKeyWordPosition(keyWords, "",bytes);
        PDPageContentStream contentStream = null;
        List<float[]> list = pdf.getCoordinate();
        List<Integer> convertResult =  convert(list);
        String  a = convert2String(list);
        // 多页pdf的处理*/
        for (float[] fs : list) {
            float x = fs[0];
            float y = fs[1];
        }
        //doc.close();
    }
    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        FileInputStream fis =null;
        ByteArrayOutputStream bos =null;
        try
        {
             fis = new FileInputStream(tradeFile);
             bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fis !=null){
                try {
                    fis.close();
                }catch (IOException io){
                    io.printStackTrace();
                }
            }
            if(bos !=null){
                try {
                    bos.close();
                }catch (IOException io){
                    io.printStackTrace();
                }
            }
        }
        return buffer;
    }

    public static List<Integer> convert(List<float[]> list){
        List<Integer>  res = new ArrayList<Integer>();
        if(list!=null&&list.size()>0) {
            for (float[] fs : list) {
                int page = (int) fs[2];
                if(!res.contains(page)){
                    res.add(page);
                }
            }
        }
        return res;
    }
    public static String convert2String(List<float[]> list){
        List<Integer>  res = convert(list);
        String str = StringUtils.join(res.iterator(),",");
        return str;
    }


    /**
     * 获取pdf中页码
     * @param bystes
     * @return
     */
    public  static  int getPdfNubers(byte[] bystes){

        int pages = 0;
        ByteArrayInputStream in = new ByteArrayInputStream(bystes);
        PDDocument pdfReader = null;
        try {
            pdfReader = PDDocument.load(in);
            pages= pdfReader.getNumberOfPages();
        } catch (IOException e) {
            return pages;
        }

        return pages;

    }

}


 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题需要用到 iTextSharp 库来解决。首先,你需要安装该库并导入它。然后,你可以使用以下代码获取指定关键字坐标位置信息: ```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace PdfKeywordCoordinates { class Program { static void Main(string[] args) { string filename = @"C:\example.pdf"; // pdf 文件路径 string keyword = "example keyword"; // 指定关键字 using (PdfReader reader = new PdfReader(filename)) { for (int page = 1; page <= reader.NumberOfPages; page++) { ITextExtractionStrategy strategy = new LocationTextExtractionStrategy(); string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy); if (currentText.Contains(keyword)) { var kwLocation = new List<RectAndText>(); var renderFilter = new RenderFilter[1]; renderFilter[0] = new RegionTextRenderFilter(new Rectangle(0, 0, 1000, 1000)); var textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(textExtractionStrategy); processor.ProcessContent(reader.GetPageContent(page)); kwLocation = ((LocationTextExtractionStrategy)textExtractionStrategy).GetLocations(); foreach (RectAndText rectAndText in kwLocation) { if (rectAndText.text.Contains(keyword)) { Console.WriteLine("Page: " + page + " X: " + rectAndText.rect.Left + " Y: " + rectAndText.rect.Bottom); } } } } } Console.ReadLine(); } } public class RectAndText { public iTextSharp.text.Rectangle rect; public String text; public RectAndText(iTextSharp.text.Rectangle rect, String text) { this.rect = rect; this.text = text; } } } ``` 这个代码将在指定的 PDF 文件查找指定的关键字,并输出该关键字在每一页坐标位置信息。注意,这个代码是使用 C# 编写的,如果你使用的是 Python,你需要使用 Python 版本的 iTextSharp 库,并使用相应的语法来实现相同的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值