如何使用 PyQT5 在一个循环中将多个 HTML 文档转换为 PDF [英] How to use PyQT5 to convert multiple HTML docs to PDF in one loop

查看:62
本文介绍了如何使用 PyQT5 在一个循环中将多个 HTML 文档转换为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序使用从 PDF 转换为 HTML 的通用模板来为个人创建个性化报告.为了将最终的 HTML 文件转换回 PDF,我使用了 PyQT5 及其 printToPdf 方法.它可以完美运行一次,但程序会挂起,直到我关闭打开的小部件视图,此时它会出现段错误并结束整个 python 程序.如何以编程方式和平关闭程序,以便我可以一次性渲染所有 HTML?也许有什么方法可以不让线程放弃小部件?

I'm writing a program that uses a generic template that was converted from PDF to HTML to create personalized reports for individuals. In order to convert the final HTML files back to PDF I am using PyQT5 and its printToPdf method. It works perfectly once, but the program hangs until I close the widget view that opens, at which point it segfaults and ends the entire python program. How can I close the program peacefully programmatically so that I can render all of the HTML in one sweep? Perhaps there is some way not to forfeit the thread over to the widget?

这是我当前的代码.

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()

推荐答案

ekhumoro 答案所述,问题是您不能创建多个 QApplication(您必须查看指示的答案以获取更多详细信息),因此应用相同的技术解决方案如下:

As stated in the ekhumoro answer, the problem is that you cannot create several QApplication (you must review the answer indicated for more details), so applying the same technique the solution is as follows:

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")

这篇关于如何使用 PyQT5 在一个循环中将多个 HTML 文档转换为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆