如何循环 PyQt5 函数以从 url 列表打印到 pdf?

How to loop a PyQt5 function for printing from list of url to pdf?

我有一个列表,其中包含许多字符串格式的 URL。

url_list=['www.url1.com', 'www.url2.com', 'www.url3.com', 'www.url4.com']

我可以将 url 单独打印为 pdf,但我想知道如何遍历 url 列表并再次重复该过程。我试过使用 for 循环,但它不起作用。

import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loader = QtWebEngineWidgets.QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QPageSize.A4Extra))
    layout.setOrientation(QPageLayout.Portrait)
    loader.load(QUrl(url_list[0]))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())

    def emit_pdf(finished):
        loader.page().printToPdf(f"{number}_url_file.pdf", pageLayout=layout)

    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec_())

你要实现一个顺序打印的逻辑,即打印完第N页后,开始打印第N+1页。

from collections import deque
from functools import cached_property

from PyQt5.QtCore import QCoreApplication, QObject, QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEnginePage


class PrintManager(QObject):
    def __init__(self, qtargs=None, parent=None):
        super().__init__(parent=parent)
        self.app = QApplication(qtargs or [])

    @cached_property
    def page(self):
        page = QWebEnginePage()
        page.pdfPrintingFinished.connect(self.handle_print_finished)
        page.loadFinished.connect(self.handle_load_finished)
        return page

    @cached_property
    def queue(self):
        return deque()

    def append(self, url, filename):
        self.queue.append((QUrl.fromUserInput(url), filename))

    def start(self):
        self._start()
        QCoreApplication.instance().exec_()

    def _start(self):
        try:
            url, filename = self.queue.popleft()
        except IndexError:
            QCoreApplication.quit()
        else:
            self.page.setProperty("filename", filename)
            self.page.load(url)

    def handle_load_finished(self, ok):
        if ok:
            filename = self.page.property("filename")
            layout = QPageLayout()
            layout.setPageSize(QPageSize(QPageSize.A4Extra))
            layout.setOrientation(QPageLayout.Portrait)
            self.page.printToPdf(filename, pageLayout=layout)
        else:
            print("failed")
            self._start()

    def handle_print_finished(self):
        self._start()


def main():
    print_manager = PrintManager()
    data = [
        (" "67837489.pdf"),
        (" "59274653.pdf"),
    ]
    for url, filename in data:
        print_manager.append(url, filename)
    print_manager.start()


if __name__ == "__main__":
    main()