【问题标题】:how to extract text from pdf using mupdf?如何使用mupdf从pdf中提取文本?
【发布时间】:2013-09-24 07:52:17
【问题描述】:

我想从 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

【问题讨论】:

    标签: visual-c++ pdf mupdf


    【解决方案1】:

    快速浏览一下您的代码看起来不错。

    要从 PDF 中提取文本,您需要解释 PDF 运算符流。 fz_run_page 执行此操作。它会导致调用您指定的任何设备 - 在本例中为结构化文本提取设备。这会将整个页面中随机定位的字形整理成更结构化的单词/行/段落/列等形式。

    所以,简而言之,你做对了。

    目前没有用户可用的方法来提高此速度。在未来的版本中,我们可能会使用设备提示来避免读取图像等。我将对此进行思考并与其他开发人员讨论。但现在你做的是正确的事。

    HTH。

    【讨论】:

    • @@Robin Watts,你认为 mupdf 是世界上最好的 pdf 库吗?
    • @Robin Watts,有没有关于加速从 pdf 中读取文本的工作?
    【解决方案2】:

    不,需要 fz_run_page 调用。您需要解释文档的页面以提取文本,这就是 fz_run_page 所做的。

    您可能可以创建一个更简单的文本设备,避免跟踪字符位置,但我怀疑这会对性能产生真正的影响。

    【讨论】:

    • 是的,fz_new_text_device 创建一个只能解析pdf文本的设备。
    猜你喜欢
    • 2014-10-15
    • 2013-01-08
    • 1970-01-01
    • 2016-01-28
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多