C ++ PoDoFo - 如何将PDF转换为原始TXT文件?

时间:2015-08-09 22:57:07

标签: c++ pdf

我正在尝试从PDF文件中提取原始文本。 我已经找到了PoDoFo库,它似乎能够完成这项工作。

基于this answer,我现在做的是:

#include <iostream>
#include <string>
#include <podofo/podofo.h>

//using namespace PoDoFo;

int main( int argc, char* argv[] )
{
    PoDoFo::PdfMemDocument pdf("inputpdftest.pdf");
    for (int pn = 0; pn < pdf.GetPageCount(); ++pn) 
    {
        std::cout << "Page: " << pn << std::endl;
        PoDoFo::PdfPage* page = pdf.GetPage(pn);
        PoDoFo::PdfContentsTokenizer tok(page);
        const char* token = NULL;
        PoDoFo::PdfVariant var;
        PoDoFo::EPdfContentsType type;
        while (tok.ReadNext(type, token, var)) 
        {
            if (type == PoDoFo::ePdfContentsType_Keyword)
            {
                // process type, token & var
                if (var.IsArray()) 
                {
                    PoDoFo::PdfArray& a = var.GetArray();
                    for (size_t i = 0; i < a.GetSize(); i++)
                    {
                        if (a[i].IsString())
                        {
                            std::string str = a[i].GetString().GetStringUtf8();
                            std::cout << str << " ";
                        }
                    }
                }
            }
        }
    }
    return 0;
}

输出与使用记事本打开PDF完全相同,只有一些垃圾:

  ( : ˝  ˝   - H  -   ( : ˝ ˇ  ; 7  < ˝ ˙ ˝  )     ˆ + 0  ( : ˝     % ˆ % ˘ ˚ : ˇ  ( 7  < ˝ ˙ ˝  )       ( -  ˝   % ' ˝ ) - 0 ˝      ˜ % / ˚ (  ˙ ˚ : ˇ  ( 7  < ˝ ˙ ˝  )       ( -  ˝   % ' ˝ ) - 0 ˝    ˜ % / ˚ (  ˙ ˚ : ˇ  ˆ 7  < ˝ ˙ ˝  )    

很明显,因为我没有设法将这些信息转换为普通文本,我问的是如何做到这一点?

因此,您可以看到我必须使用GetString函数处理PDF数据。现在,我将浏览每个标记,检查是否为数组(并包含TJ等PDF命令),然后使用此类元素GetString。在我的回答中,没有任何关于如何进一步处理的说法。

From documentation Returns the strings contents这是一个数组,我应该迭代它?

输入PDF不是扫描图片或图像。在给定的文件中,总会有一些文本,可以高亮显示,手动复制或搜索单词。

Example PDF

我真诚地要求回答如何从这些数据中获取文本。

1 个答案:

答案 0 :(得分:1)

问题是评论

// process type, token & var

打算用实际进行一些处理的代码替换。 只有在您确定当前命令为if (var.IsArray())时,才应执行TJ测试中的代码。您仍然需要处理许多文本命令。

有关更好的示例,请查看podofo源中podofotextextract工具的来源:https://svn.code.sf.net/p/podofo/code/podofo/trunk/tools/podofotxtextract

相关问题