如何使用PyQT5在一个循环中将多个HTML文档转换为PDF

2024-10-02 12:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,它使用一个通用的模板,从PDF转换成HTML,为个人创建个性化的报告。为了将最终的HTML文件转换回PDF,我使用PyQT5及其printToPdf方法。它可以完美地工作一次,但程序会一直挂起,直到我关闭打开的widget视图,此时它会分段并结束整个python程序。如何以编程方式和平地关闭程序,以便在一次扫描中呈现所有HTML?也许有什么办法不放弃线程到小部件?你知道吗

这是我现在的密码。你知道吗

for htmlFileAsString in files:

   app = QtWidgets.QApplication(sys.argv)
   loader = QtWebEngineWidgets.QWebEngineView()
   loader.setZoomFactor(1)
   loader.setHtml(htmlFileAsString)
   loader.page().pdfPrintingFinished.connect(
     lambda *args: print('finished:', args))
   def emit_pdf(finished):
     loader.show()
     loader.page().printToPdf('output/' + name + '/1.pdf')

   loader.loadFinished.connect(emit_pdf)
   app.exec()

Tags: 程序模板apppdfhtmlconnectpageargs
1条回答
网友
1楼 · 发布于 2024-10-02 12:35:47

the ekhumoro answer中所述,问题是您无法创建多个QApplication(您必须查看所示的答案以了解更多详细信息),因此应用相同的技术,解决方案如下:

import os
from PyQt5 import QtWidgets, QtWebEngineWidgets


class PdfPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super().__init__()
        self._htmls_and_paths = []
        self._current_path = ""

        self.setZoomFactor(1)
        self.loadFinished.connect(self._handleLoadFinished)
        self.pdfPrintingFinished.connect(self._handlePrintingFinished)

    def convert(self, htmls, paths):
        self._htmls_and_paths = iter(zip(htmls, paths))
        self._fetchNext()

    def _fetchNext(self):
        try:
            self._current_path, path = next(self._htmls_and_paths)
        except StopIteration:
            return False
        else:
            self.setHtml(html)
        return True

    def _handleLoadFinished(self, ok):
        if ok:
            self.printToPdf(self._current_path)

    def _handlePrintingFinished(self, filePath, success):
        print("finished:", filePath, success)
        if not self._fetchNext():
            QtWidgets.QApplication.quit()


if __name__ == "__main__":

    current_dir = os.path.dirname(os.path.realpath(__file__))

    paths = []
    htmls = []
    for i in range(10):
        html = """<html>
    <header><title>This is title</title></header>
    <body>
    Hello world-{i}
    </body>
    </html>""".format(
            i=i
        )
        htmls.append(html)
        paths.append(os.path.join(current_dir, "{}.pdf".format(i)))

    app = QtWidgets.QApplication([])
    page = PdfPage()
    page.convert(htmls, paths)
    app.exec_()

    print("finished")

相关问题 更多 >

    热门问题