Python PyQt4从qlayout创建pdf

时间:2017-01-26 09:43:37

标签: python pdf pyqt pyqt4 qlayout

我正在使用Pyt4开发一个应用程序。我想有一个选项将主要小部件打印到pdf文档。我有一个主要小部件的自定义qlayout,我想用该qlayout创建一个pdf文档。我读了很多关于pyqt qprinter的内容,但我不确定这是我想要的。

有人可以建议我如何用qlayout创建一个充满qwidgets的pdf吗?

1 个答案:

答案 0 :(得分:1)

使用QPixmap.grabWidget将小部件渲染为像素图,然后将其绘制在QPrinter上,然后将其转换为pdf:

import sys
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.text = QtGui.QTextEdit(self)
        self.text.setText(open(__file__).read())
        self.edit = QtGui.QLineEdit(self)
        self.edit.setText('/tmp/test.pdf')
        self.buttonSave = QtGui.QPushButton('Save', self)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.text, 0, 0, 1, 2)
        layout.addWidget(self.edit, 1, 0, 1, 1)
        layout.addWidget(self.buttonSave, 1, 1, 1, 1)

    def handleSave(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
        printer.setPageSize(QtGui.QPrinter.A6)
        printer.setColorMode(QtGui.QPrinter.Color)
        printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
        printer.setOutputFileName(self.edit.text())
        pixmap = QtGui.QPixmap.grabWidget(self).scaled(
            printer.pageRect(QtGui.QPrinter.DevicePixel).size().toSize(),
            QtCore.Qt.KeepAspectRatio)
        painter = QtGui.QPainter(printer)
        painter.drawPixmap(0, 0, pixmap)
        painter.end()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 640, 640)
    window.show()
    sys.exit(app.exec_())

修改

如果QPainter部分由于某种原因在您的设置中失败,您可以尝试以下替代保存方法:

    def handleSave(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
        printer.setPageSize(QtGui.QPrinter.A9)
        printer.setColorMode(QtGui.QPrinter.Color)
        printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
        printer.setOutputFileName(self.edit.text())
        self.render(printer)

或另一种选择是使用QTextDocument

    def handleSave(self):
        printer = QtGui.QPrinter()
        printer.setPageSize(QtGui.QPrinter.A5)
        printer.setResolution(200)
        printer.setColorMode(QtGui.QPrinter.Color)
        printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
        printer.setOutputFileName(self.edit.text())
        size = printer.pageRect(QtGui.QPrinter.DevicePixel).size()
        pixmap = QtGui.QPixmap.grabWidget(self).scaled(
            size.toSize(), QtCore.Qt.KeepAspectRatio,
            QtCore.Qt.SmoothTransformation)
        data = QtCore.QByteArray()
        buffer = QtCore.QBuffer(data)
        pixmap.save(buffer, 'PNG')
        document = QtGui.QTextDocument()
        document.setPageSize(size)
        document.setHtml('<img src="data:image/png;base64,%s"/>' %
                         bytes(data.toBase64()).decode('ascii'))
        document.print_(printer)