【问题标题】:How to convert a local html file to pdf using PyQt5?如何使用 PyQt5 将本地 html 文件转换为 pdf?
【发布时间】:2020-08-12 18:07:22
【问题描述】:

我尝试过使用 wkhtml 和 weasyprint 库,但所有这些库都会呈现一个空白的 pdf 页面。唯一可行的选择是 pdfcrowd,但这是一个付费图书馆。我发现了几个使用 PyQt 转换网页的选项:

import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
    lambda *args: print('finished:', args))
loader.load(QtCore.QUrl('https://en.wikipedia.org/wiki/Main_Page'))

def emit_pdf(finished):
    loader.show()
    loader.page().printToPdf("test.pdf")

loader.loadFinished.connect(emit_pdf)

app.exec()

但是,我不太确定如何将其调整为本地保存的 html 文件。

【问题讨论】:

    标签: python python-3.x pyqt pyqt5


    【解决方案1】:

    您必须使用 QUrl.fromLocalFile() 将文件路径作为 url 传递,也不必创建 QWebEngineView 而只需使用 QWebEnginePage:

    import os
    import sys
    
    from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
    
    
    def html_to_pdf(html, pdf):
        app = QtWidgets.QApplication(sys.argv)
    
        page = QtWebEngineWidgets.QWebEnginePage()
    
        def handle_print_finished(filename, status):
            print("finished", filename, status)
            QtWidgets.QApplication.quit()
    
        def handle_load_finished(status):
            if status:
                page.printToPdf(pdf)
            else:
                print("Failed")
                QtWidgets.QApplication.quit()
    
        page.pdfPrintingFinished.connect(handle_print_finished)
        page.loadFinished.connect(handle_load_finished)
        page.load(QtCore.QUrl.fromLocalFile(html))
        app.exec_()
    
    
    if __name__ == "__main__":
    
        CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(CURRENT_DIR, "index.html")
        print(filename)
    
        html_to_pdf(filename, "test.pdf")
    

    【讨论】:

    • 如何修改上述代码中的视口宽度?我正在尝试转换一个响应式页面,而 pdf 似乎有一个很小的页面/视口宽度......你知道我该如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2015-08-14
    • 2016-03-10
    • 2020-02-14
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多