5

从昨天开始,我尝试使用 python-poppler-qt4 从一个 pdf 中的一些突出显示的注释中提取文本。

根据这个文档,看起来我必须使用 Page.text() 方法获取文本,从突出显示的注释中传递一个 Rectangle 参数,我使用 Annotation.boundary() 得到。但我只得到空白文本。有人能帮我吗?我在下面复制了我的代码,并为我正在使用的 PDF 添加了一个链接。谢谢你的帮助!

import popplerqt4
import sys
import PyQt4


def main():

    doc = popplerqt4.Poppler.Document.load(sys.argv[1])
    total_annotations = 0
    for i in range(doc.numPages()):
        page = doc.page(i)
        annotations = page.annotations()
        if len(annotations) > 0:
            for annotation in annotations:
                if  isinstance(annotation, popplerqt4.Poppler.Annotation):
                    total_annotations += 1
                    if(isinstance(annotation, popplerqt4.Poppler.HighlightAnnotation)):
                        print str(page.text(annotation.boundary()))
    if total_annotations > 0:
        print str(total_annotations) + " annotation(s) found"
    else:
        print "no annotations found"

if __name__ == "__main__":
    main()

测试pdf: https ://www.dropbox.com/s/10plnj67k9xd1ot/test.pdf

4

1 回答 1

9

查看注释的文档,边界属性似乎以标准化坐标返回此注释的边界矩形。page.pageSize().width()虽然这似乎是一个奇怪的决定,但我们可以简单地通过和.height()值 来缩放坐标。

import popplerqt4
import sys
import PyQt4


def main():

    doc = popplerqt4.Poppler.Document.load(sys.argv[1])
    total_annotations = 0
    for i in range(doc.numPages()):
        #print("========= PAGE {} =========".format(i+1))
        page = doc.page(i)
        annotations = page.annotations()
        (pwidth, pheight) = (page.pageSize().width(), page.pageSize().height())
        if len(annotations) > 0:
            for annotation in annotations:
                if  isinstance(annotation, popplerqt4.Poppler.Annotation):
                    total_annotations += 1
                    if(isinstance(annotation, popplerqt4.Poppler.HighlightAnnotation)):
                        quads = annotation.highlightQuads()
                        txt = ""
                        for quad in quads:
                            rect = (quad.points[0].x() * pwidth,
                                    quad.points[0].y() * pheight,
                                    quad.points[2].x() * pwidth,
                                    quad.points[2].y() * pheight)
                            bdy = PyQt4.QtCore.QRectF()
                            bdy.setCoords(*rect)
                            txt = txt + unicode(page.text(bdy)) + ' '

                        #print("========= ANNOTATION =========")
                        print(unicode(txt))

    if total_annotations > 0:
        print str(total_annotations) + " annotation(s) found"
    else:
        print "no annotations found"

if __name__ == "__main__":
    main()

此外,我决定连接.highlightQuads()以更好地表示实际突出显示的内容。

<space>请注意我已附加到每个四边形文本区域的明确内容。

在示例文档中,返回的内容QString不能直接传递给print()or str(),解决方案是unicode()改用。

我希望这对某人有所帮助,因为它对我有所帮助。

注意:页面旋转可能会影响缩放值,我无法对此进行测试。

于 2014-04-29T14:25:13.257 回答