2013-09-24 61 views
1

我想從pdf中提取文本並重新發布它。 我的代碼如下:如何使用mupdf從pdf中提取文本?

BOOL CTextEditorDoc::loadTxt() 
{ 
    if(m_strPDFPath.IsEmpty()) 
     return FALSE; 

#ifdef _DEBUG 
    DWORD dwTick = GetTickCount(); 
    CString strLog; 
#endif 

    CString strFile; 
    fz_context *ctx; 
    fz_document* doc; 

    fz_matrix ctm; 
    fz_page *page; 
    fz_device *dev; 
    fz_text_page *text; 
    fz_text_sheet *sheet; 
    int i,line,rotation,pagecount; 

    if(!gb2312toutf8(m_strPDFPath,strFile)) 
     return FALSE; 

    ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED); 
    fz_try(ctx){ 
     doc = fz_open_document(ctx, strFile.GetBuffer(0)); 
    }fz_catch(ctx){ 
     fz_free_context(ctx); 
     return FALSE; 
    } 

    line = 0; 
    rotation = 0; 
    pagecount = 0; 
    pagecount = fz_count_pages(doc); 

    fz_rotate(&ctm, rotation); 
    fz_pre_scale(&ctm,1.0f,1.0f); 

    sheet = fz_new_text_sheet(ctx); 
    for(i=0;i<pagecount;i++){ 
     page = fz_load_page(doc,i); 
     text = fz_new_text_page(ctx); 
     dev = fz_new_text_device(ctx, sheet, text); 

#ifdef _DEBUG 
     dwTick = GetTickCount(); 
#endif 
     fz_run_page(doc, page, dev, &ctm, NULL); 

#ifdef _DEBUG 
     strLog.Format("run page:%d ms\n",GetTickCount() - dwTick); 
     OutputDebugString(strLog); 
     dwTick = GetTickCount(); 
#endif 

     //m_linesInfoVector.push_back(line); 
     print_text_page(ctx,m_strContent,text,line); 

#ifdef _DEBUG 
     strLog.Format("print text:%d ms\n",GetTickCount() - dwTick); 
     OutputDebugString(strLog); 
     dwTick = GetTickCount(); 
#endif 

     fz_free_device(dev); 
     fz_free_text_page(ctx,text); 
     fz_free_page(doc, page); 
    } 

    fz_free_text_sheet(ctx,sheet); 
    fz_close_document(doc); 
    fz_free_context(ctx); 
    return TRUE; 
} 

這段代碼可以提取PDF的所有文字,但它可能是太慢了。如何改進? 大部分時間用於功能fz_run_page。也許只是從pdf中提取文本,我不需要執行fz_run_page

回答

2

快速瀏覽一下你的代碼看起來不錯。

爲了從你需要解釋PDF操作流的PDF文本。 fz_run_page執行此操作。它會調用您指定的任何設備 - 在本例中爲結構化文本提取設備。這整理來自全國各地的頁面的隨機定位字形進字/行/段落/列等

因此,簡而言之你正在做正確的事情的更多的結構形式。

有提高這個速度沒有當前用戶servicable方式。有可能我們可能會使用設備提示來避免在將來的版本中讀取圖像等。我會思考這一點,並與其他開發者討論。但現在你正在做正確的事情。

HTH。

+0

@@ Robin Watts,您認爲mupdf是世界上最好的pdf庫嗎? – tfzxyinhao

+0

@Robin Watts,有沒有關於加速閱讀PDF文本的任何事情? – EekTheCat

1

沒有,需要的fz_run_page電話。您需要解釋文檔的頁面以提取文本,這就是fz_run_page所做的。

也許你可以創建一個避免跟蹤字符位置的簡單文本的設備,但我懷疑,這將使性能的真正區別。

+0

是,fz_new_text_device創建deivce,它只能解析器PDF文本。 – tfzxyinhao