blog.Ring.idv.tw

PDFBox - 擷取PDF檔案中的純文字

PDFBox - 擷取PDF檔案中的純文字


PDFBox.是一個Open Source的Java PDF Library,可以利用它來協助處理PDF檔案的一些應用(用iText也是可行的,不過它好像不支援擷取純文字「iText in Action, pp. 576」),例如:擷取PDF檔案中的純文字、轉換PDF檔案到Image檔等等.. 諸如此類的應用。

而且「Lucene」就是用它來轉換PDF到純文字再進行索引的~

下述是擷取PDF檔案中的純文字:(FontBox-0.1.0-dev.jar、PDFBox-0.7.3.jar required!)

import java.io.IOException;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

public class PDFTextExtractor
{
    private PDDocument document;
    
    public String extractText(String file) throws IOException
    {
        document = PDDocument.load(file);       
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setStartPage(1);
        stripper.setEndPage(document.getNumberOfPages());
        return stripper.getText(document);
    }

    public static void main(String[] args)
    {
        PDFTextExtractor extractor = new PDFTextExtractor();
        try
        {
            String text = extractor.extractText("C:\\test.pdf");
            System.out.println(text);
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

相關資源

PDF Reference and Adobe Extensions to the PDF Specification - PDF規格書

Glyph & Cog: Text Extraction - 解釋為何擷取PDF中的純文字不是那麼容易

2009-01-03 18:17:22

3 comments on "PDFBox - 擷取PDF檔案中的純文字"

  1. 1. zack 說:

    不好意思,可以跟您請教一下,如果PDF被加上密碼或限制編輯,請問有辦法可以可以取出純文字嗎?

    2012-04-12 10:16:37

  2. 2. Shen 說:

    Dear zack,

    理論上只要PDF檔案格式的內容沒有被加密的話,基本上應該都是能擷取的出來的,至於你所提到加上密碼或限制編輯的方式,我沒有實際測試過~ 也許你可以試著用上述的程式試試。

    2012-04-12 20:19:02

  3. 3. Pman 說:

    Dear zack,
    加密過的PDF無法提取
    會出現錯

    2012-04-23 11:58:44

Leave a Comment

Copyright (C) Ching-Shen Chen. All rights reserved.

::: 搜尋 :::

::: 分類 :::

::: Ads :::

::: 最新文章 :::

::: 最新回應 :::

::: 訂閱 :::

Atom feed
Atom Comment