我正在使用Python 2.7和PySide,我需要将一个大的 html 文件导出到一个 pdf 文件。
我尝试使用 a 加载它,QWebView
然后将其打印到QPrinter
配置为 pdf 格式的文件中。这很好用。
但是,我的解决方案存在一个大问题:当我调用 时QWebView.print_()
,gui 被锁定,对于 windows,我的程序看起来像是崩溃了。发生这种情况是因为我的 html 很大(1000 页或更多)。
所以我的问题是:有没有一种干净的方法可以避免这种“崩溃”?
编辑:
我尝试在单独的线程中进行打印,就像 jadkik94 建议的那样。据我了解,下面的代码应该可以工作。不幸的是,它随机崩溃。;) 任何想法为什么会这样?
import sys
from PySide import QtGui, QtWebKit, QtCore
class PrintThread(QtCore.QThread):
def __init__(self, webview, printer, parent=None):
super(PrintThread, self).__init__(parent)
self._webview = webview
self._printer = printer
def run(self):
self._webview.print_(self._printer)
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow,self).__init__()
# a printer to print on
self._myPrinter = QtGui.QPrinter()
self._myPrinter.setOutputFormat(QtGui.QPrinter.PdfFormat)
self._myPrinter.setPrintRange(QtGui.QPrinter.AllPages)
self._myPrinter.setOrientation(QtGui.QPrinter.Portrait)
self._myPrinter.setPaperSize(QtGui.QPrinter.A4)
self._myPrinter.setNumCopies(1)
# a webview for loading the html and printing it
self._webview = QtWebKit.QWebView(self)
self.setCentralWidget( self._webview )
self._webview.loadFinished.connect(self.webViewLoadFinished)
# print-preview-dialog
self._previewDlg = QtGui.QPrintPreviewDialog(self._myPrinter)
#self._previewDlg.paintRequested.connect(self.dlgPaintRequestNoThread) # works but freezes the mainthread
self._previewDlg.paintRequested.connect(self.dlgPaintRequestWithThread) # as far is i understand this should work... but crashes randomly ;)
# load the html
self._webview.load('index.htm') # file is 2MB
def webViewLoadFinished(self):
# when webview has finished loading, show the dialog
self._previewDlg.show()
def dlgPaintRequestNoThread(self):
self._webview.print_(self._myPrinter)
def dlgPaintRequestWithThread(self):
self.printPages()
# wait for the print-thread to finish without blocking the mainthread
eventLoop = QtCore.QEventLoop()
self.worker.finished.connect(eventLoop.quit)
eventLoop.exec_()
def printPages(self):
self.worker = PrintThread(self._webview, self._myPrinter)
self.worker.finished.connect(self.donePrinting)
self.progressDlg = QtGui.QProgressDialog()
self.progressDlg.setCancelButton(None)
self.progressDlg.show()
self.worker.start()
def donePrinting(self):
self.progressDlg.close()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()