如何使用python-poppler-qt4显示PDF?

How to display PDF with python-poppler-qt4?

我已经下载并安装了python-poppler-qt4,现在正在尝试一个简单的Qt应用程序来显示PDF页面。 我遵循了从网络上获取的信息,即将PDF转换为QImage,然后转换为QPixMap,但这是行不通的(我得到的只是一个没有可见内容的小窗口)。

我可能在某个时候失败了(QImage.width()返回我输入的宽度,QPixMap.width()返回0)。

这是代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python

import sys
from PyQt4 import QtGui, QtCore
import popplerqt4

class Application(QtGui.QApplication):
    def __init__(self):
        QtGui.QApplication.__init__(self, sys.argv)    
        self.main = MainWindow()
        self.main.show()

    class MainWindow(QtGui.QFrame):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.layout = QtGui.QVBoxLayout()
            self.doc = popplerqt4.Poppler.Document.load('/home/benjamin/test.pdf')
            self.page = self.doc.page(1)
# here below i entered almost random dpi, position and size, just to test really
            self.image = self.page.renderToImage(150, 150, 0, 0, 210, 297)
            self.pixmap = QtGui.QPixmap()
            self.pixmap.fromImage(self.image)
            self.label = QtGui.QLabel(self)
                    self.label.setPixmap(self.pixmap)
            self.layout.addWidget(self.label)
            self.setLayout(self.layout)

    if __name__ =="__main__":
            application = Application()
            sys.exit(application.exec_())

这里哪里出问题了? 谢谢。


我不熟悉python,因此这可能无法直接应用,但是QPixmap::fromImage是返回QPixmap的静态函数。 因此,您的代码应为:

1
 self.pixmap = QtGui.QPixmap.fromImage(self.image)

换句话说,self.pixmap.fromImage不会更改self.pixmap,它会返回一个新的像素图,该像素图是根据您提供的图像作为参数生成的。