Python PyQt4 从 qlayout 创建 pdf

Python PyQt4 creating pdf from qlayout

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

谁能建议我如何创建一个 qlayout 充满 qwidgets 的 pdf?

使用 QPixmap.grabWidget to render the widget to a pixmap, then paint that on a 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)