編輯:關於 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 的性質往往更快。
自製 Banner 輪播控制元件:完美實作無限循環
需求背景 先前有個需求要做一個公告列,必須無限輪播。第一時間想到的是 ViewPager,網上一查也幾乎都是這個解法。但自己動手做過之後,發現效果其實不夠理想。 常見的兩
Android VectorDrawable 與 SVG:動手做兩個炫酷的向量動畫
Android 從 5.0 開始提供了新的 API VectorDrawable,讓我們可以直接使用向量圖 SVG。在 XML 檔中,透過 <vector>、
Android 自定義圓形頭像裁剪與縮放控制項
許多 App 都需要使用者上傳頭像,而圓形頭像因為視覺柔和、辨識度高,經常被採用。本文說明如何自定義一個可拖動、可縮放、可裁剪圓形區域的圖片控制項,模擬常見的頭像編輯流程
用 HttpClient 的 GET 與 POST 實作登入:完整流程與程式碼
一、HttpClient 是什麼 HttpClient 是 Apache Jakarta Commons 底下的子專案,提供了一套高效、功能完整的 HTTP 協議用戶端編