Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 上解析並取出 PDF 文字:PDFBox 解析器實作

編輯:關於 Android 程式設計

想在 App 裡顯示 PDF 內容,得先過「解析」這一關。Android 沒有內建的 PDF 文字擷取能力,實務上多會借助 PDFBox 這套 Java 函式庫——把它的 jar 放進專案即可使用。

核心其實只有兩個類別

PDFBox 取文字的關鍵在 PDDocument(代表文件本身)與 PDFTextStripper(負責把頁面內容抽成純文字)。流程是載入文件、讀取文件資訊、抽字、關閉文件。

我把這段包成一個 PDFExtractor,繼承自既有的 AbstractExtractor,讓 PDF 與其他格式共用同一套呼叫介面:

private String getContent(LingJoinFile f) {
    PDDocument doc = null;
    try {
        doc = PDDocument.load(f);
        PDFTextStripper stripper = new PDFTextStripper();
        this.setLingJoinFileInfo(f, doc.getDocumentInformation());
        return stripper.getText(doc);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "";
}

順手把文件資訊也讀出來

PDDocumentInformation 裡有作者、標題等中繼資料。我寫了個小方法把作者帶回自己的檔案物件,方便後續顯示或檢索:

private void setLingJoinFileInfo(LingJoinFile f, PDDocumentInformation info) {
    if (info.getAuthor() != null) {
        f.setlAuthor(info.getAuthor());
    }
}

對外提供兩種輸出形式

呼叫端有時要字串,有時要串流,因此我準備了兩個方法:

public void paserFileToReader(LingJoinFile f) throws Exception {
    f.setlContentReader(this.getContentReader(f));
}

public void paserFileToString(LingJoinFile f) throws Exception {
    f.setlContent(this.getContent(f));
}

其中 getContentReader 只是把字串包進 StringReader 再外層加上 BufferedReader:

private BufferedReader getContentReader(LingJoinFile f) {
    return new BufferedReader(new StringReader(this.getContent(f)));
}

兩個實務上的坑

第一,doc.close() 一定要放在 finally。PDFBox 會佔用檔案資源,忘記釋放後在同一頁面上反覆開檔很容易出問題。

第二,PDFTextStripper 只處理「文字型」PDF。若文件其實是掃描後的影像,抽出來會是空字串——那需要 OCR,是完全另一條路。看到 return "" 時先別急著懷疑程式碼,確認一下 PDF 的性質往往更快。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved