如何提取PDF索引/目录与poppler



我发现像okular和evince这样的pdf查看器能够很好地显示pdf文档(图书)的索引,并提供每个段落的链接。他们怎么能做到呢?他们用的是poppler库,我怎么用poppler提取索引呢?

它只是在第一级停止(递归需要更深入)

toc=document->toc();
QDomElement docElem = toc->documentElement();
 QDomNode n = docElem.firstChild();
 while(!n.isNull()) {
     QDomElement e = n.toElement(); // try to convert the node to an element.
     if(!e.isNull()) {
         qDebug("elem %sn",qPrintable(e.tagName())); // the node really is an element.
     }
     n = n.nextSibling();
 }

下面是如何在Python中使用poppler完成此操作的演示:

import poppler
def walk_index(iterp, doc):
    while iterp.next():
      link=iterp.get_action()
      s = doc.find_dest(link.dest.named_dest)
      print link.title,' ', doc.get_page(s.page_num).get_label()
      child = iterp.get_child()
      if child:
        walk_index(child, doc)
def main():
    uri = ("file:///"+path_to_pdf)
    doc = poppler.document_new_from_file(uri, None)
    iterp = poppler.IndexIter(doc)
    link = iterp.get_action()
    s = doc.find_dest(link.dest.named_dest)
    print link.title,' ', doc.get_page(s.page_num).get_label()
    walk_index(iterp, doc)
    return 0

if __name__ == '__main__':
    main()

python poppler库已经过时,下面是如何使用Gobject:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# walk to table of contents and print titles and pages
import sys
from gi.repository import Poppler
def walk_index(iterp, doc):
    while iterp.next():
        link=iterp.get_action()
        dest=doc.find_dest(link.goto_dest.dest.named_dest)
        s = doc.get_page(dest.page_num-1)
        print link.goto_dest.title, dest.page_num, s.get_label()
        child = iterp.get_child()
        if child:
            walk_index(child, doc)
def main():
    uri = ("file:///"+sys.argv[1])
    doc = Poppler.Document.new_from_file(uri, None)
    iterp = Poppler.IndexIter.new(doc)
    link = iterp.get_action()
    dest=doc.find_dest(link.goto_dest.dest.named_dest)
    s = doc.get_page(dest.page_num-1)
    print link.goto_dest.title, dest.page_num, s.get_label()
    walk_index(iterp, doc)
    return 0

if __name__ == '__main__':
    main()

相关内容

  • 没有找到相关文章

最新更新