PDF元件 PDFBox --zt

需求: 
1. 從pdf裏截取出文字. 
2. 產生pdf的縮圖

或許你知道的是ITextSharp,不過 ITextSharp的主要是"產生"pdf,他在讀取pdf方面是不大行的(我實在搞不懂他的PdfReader要怎麼用)

PDFBox 是用 java開發的,但他有特意搭配 IKVM(一個讓java的類別可對應到.net的library) ,讓你在.net 上也可以順利使用。

總共要加入參考5個dll,IKVM的dll,下載PDFBox裏面就有了
PDFBox-0.7.3.dll
IKVM.Runtime.dll
IKVM.GNU.Classpath.dll
IKVM.AWT.WinForms.dll
FontBox-0.1.0-dev.dll

網址 http://www.pdfbox.org/

那我先從轉換文字檔的部份先試起,還蠻慢的,或許是我選了一個8MB的pdf關係吧,不過可以順利轉喔。

 

    /// 
    /// 將 PDF 檔轉換成文字檔
    /// 
    /// 
    /// 
    public void PdfToText(string pdfFile, string txtFile) {
        PDDocument doc = PDDocument.load(pdfFile);
        PDFTextStripper stripper = new PDFTextStripper();
        string str = stripper.getText(doc);
        StreamWriter sw = new StreamWriter(txtFile);
        sw.WriteLine("作者:" + doc.getDocumentInformation().getAuthor());
        sw.WriteLine("標題:" + doc.getDocumentInformation().getTitle());
        sw.WriteLine(str);
        sw.Close();
    }

接下來才是我真的想要的,將PDF的第1頁,轉換成縮圖,放在網頁當索引,
可是... 當我按圖索code操作時, 他很爽快的丟出 exception給我「type not implemented yet 」
哎..是誰 是誰搞的鬼啊,是PDFBox? 是IKVM? 還是我??
好吧,慢慢追,PDFBox雖然說 convertToImage 目前還在beta階段,但是PdPage.java底下,的確有該段code,
而且"看起來"也很合理(其實java我看不大懂:p)。
那他在初始BufferedImage是出了什麼問題? 接下來往IKVM 裏面追,這時就該 .Net Refactor 出動啦
(因為我沒下載ikvm的原始碼啦,這時也懶的下載了),挖出傢伙挖開IKVM.GNU.Classpath.dll來瞧瞧。
 
BufferedImage裏面 有一種type 還沒實作@@, 而且就是PDFBox 要用的那種(TYPE_BYTE_INDEXED) -_-|||,
好吧,我的好奇心告一段落,我要等下個版本的IKVM,看會不會實作這,或是PDFBox改成用別種Image型態....

底下是失敗的程式碼

    /// 
    ///  將 PDF 轉換成 JPG 圖片
    /// 
    /// 
    /// 
    /// 第幾頁
    public void PdfToJpg(string pdfFile,string jpgFile,int pageIndex) {
        PDDocument doc = PDDocument.load(pdfFile);
        java.util.List pages = doc.getDocumentCatalog().getAllPages();
        if (pages.size() > 0) {
            PDPage page = (PDPage)pages.get(pageIndex);
            BufferedImage image = page.convertToImage();
            java.awt.Graphics gc = image.getGraphics();
            Bitmap bitmap = ((ikvm.awt.NetGraphics)gc).getBitmap();
            bitmap.Save(jpgFile);
        }
    }
殘念...

posted @ 2011-01-27 17:00  Nina  阅读(561)  评论(0编辑  收藏  举报