使用Python中的PyQT5将html转换为pdf

问题描述 投票:0回答:1

我在将 HTML 输入文件转换为 PDF 文件时遇到此代码问题。 当我想指定 page_width 和 page_height (特别是在“app”和“page”之间添加行)并返回以下错误时,问题就出现了:

AttributeError:模块“PyQt5.QtPrintSupport”没有属性“QPageSize”

有人知道怎么解决吗?

import os
import sys
import PyQt5

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtPrintSupport
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtGui import QPageSize


def html_to_pdf(html, pdf):
   app = QtWidgets.QApplication([])

   custom_page_width = 8.5
   custom_page_height = 11
   custom_page_size_mm = QtCore.QSizeF(custom_page_width * 25.4, custom_page_height * 25.4)
   custom_page = QtPrintSupport.QPageSize(QtPrintSupport.QPageSize.Letter)
   custom_page.setRect(QtCore.QRectF(QtCore.QPointF(0, 0), custom_page_size_mm))

   printer = QtPrintSupport.QPrinter()
   printer.setPageSize(custom_page)

   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__":

   filename = r"<<input_path.html>>"
   print(filename)

   html_to_pdf(filename, r"<<output_path.pdf>>")
python pyqt5 html-to-pdf
1个回答
0
投票

QPageSize
位于
QtGui
,而不是
QPrintSupport
。您已经正确导入了:

from PyQt5.QtGui import QPageSize

您现在可以将其称为

QPageSize
。通过尝试以
QPrintSupport.QPageSize
的形式访问它,您会收到所描述的错误,但该错误并不存在。

© www.soinside.com 2019 - 2024. All rights reserved.