用PDFBOX读取PDF内容

PDFBox(一个BSD许可下的源码开放项目)是一个为开发人员读取和建立PDF文档而准备的纯Java类库。java

主要功能
提取文本,包括Unicode字符
和Jakarta Lucene等文本搜索引擎的整合过程十分简单
加密/解密PDF文档
从PDF和XFDF格式中导入或导出表单数据
向已有PDF文档中追加内容
将一个PDF文档切分为多个文档
覆盖PDF文档apache

示例代码使用的jaride

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.14</version>
</dependency>

1.读取PDF内容搜索引擎

PDDocument helloDocument = null;
try {
    helloDocument = PDDocument.load(new File("XXX.pdf"));

    PDFTextStripper textStripper = new PDFTextStripper();
    System.out.println(textStripper.getText(helloDocument));

    helloDocument.close();
} catch (IOException e) {
    e.printStackTrace();
}

2.读取PDF内容,与位置加密

public class GetWordsAndPositionFromPDF extends PDFTextStripper{
    
    //用来记录,PDF中读到的词
    static List<String> words = new ArrayList<String>();

    public GetWordsAndPositionFromPDF() throws IOException {
        super();
    }
    
    /**
     * 解析PDF文档
     * 从PDF中读取文字以及文字的位置
     */
    public static void main( String[] args ) throws IOException {
        PDDocument document = null;
        String fileName = "XXX.pdf"; // replace with your PDF file name
        try {
            document = PDDocument.load( new File(fileName) );
            
            PDFTextStripper stripper = new GetWordsAndPositionFromPDF();
            stripper.setSortByPosition( true );
            stripper.setStartPage( 0 );
            stripper.setEndPage( document.getNumberOfPages() );
            
            Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
            stripper.writeText(document, dummy);

            // print words
            for(String word:words){
                System.out.println(word); 
            }
        }
        finally {
            if( document != null ) {
                document.close();
            }
        }
    }
    
    @Override
    protected void writeString(String text) throws IOException{
        String[] wordsInStream = text.split(getWordSeparator());
        if(wordsInStream!=null){
            for(String word :wordsInStream){
                words.add(word);
            }
        }
    }
    
    @Override
    protected void writeString(String text, List<TextPosition> textPositions) throws IOException{
        //读到的词,以及位置
        for (int i = 0; i < textPositions.size(); i++) {
             
            String str = textPositions.get(i).getUnicode();
            String x = "x=" + textPositions.get(i).getX();
            String y = "y=" + textPositions.get(i).getY();
            
            System.out.println(" textPositions.get(i) = " + str + "  x="+x + "  y="+y);
        }
        
        writeString(text);
    }
}
相关文章
相关标签/搜索