使用PyQt5将HTML转PDF时设置页面尺寸遇AttributeError问题求助
解决PyQt5中QPageSize的AttributeError问题
我编写了一段Python代码用于将HTML输入文件转换为PDF文件,但在添加自定义页面宽高的代码时,出现如下错误:
AttributeError: module 'PyQt5.QtPrintSupport' has no attribute 'QPageSize'
错误原因
- PyQt5里
QPageSize类归属PyQt5.QtGui模块,而非QtPrintSupport。你代码里虽然已经导入了from PyQt5.QtGui import QPageSize,但实际调用时却用了QtPrintSupport.QPageSize,这就导致找不到对应属性。 - 代码还存在作用域问题:
handle_print_finished和handle_load_finished函数定义在html_to_pdf外部,无法访问函数内部的page、pdf等变量,运行时会报错。 - 自定义页面尺寸的写法绕了弯路,其实
QPrinter有更直接的方法设置自定义宽高。
修复方案
- 修正
QPageSize的引用,直接用导入的QPageSize类,或者明确写QtGui.QPageSize。 - 将两个回调函数移到
html_to_pdf函数内部,确保能访问内部变量。 - 用
QPrinter.setPageSizeMM()直接设置自定义页面尺寸,简化代码逻辑。
修正后的完整代码
import os import sys 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_mm = 8.5 * 25.4 custom_page_height_mm = 11 * 25.4 printer = QtPrintSupport.QPrinter() # 直接设置自定义页面宽高(毫米单位) printer.setPageSizeMM(QPageSize(QPageSize.Custom, custom_page_width_mm, custom_page_height_mm)) page = QtWebEngineWidgets.QWebEnginePage() def handle_print_finished(filename, status): print("转换完成", filename, status) QtWidgets.QApplication.quit() def handle_load_finished(status): if status: page.printToPdf(pdf, printer=printer) else: print("HTML加载失败") 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>>")
额外说明
- 调用
printToPdf时需要传入printer参数,否则自定义的页面尺寸不会生效。 - 确保你的PyQt5版本是较新的,旧版本可能存在模块结构差异,如果还是有问题,可以尝试升级PyQt5:
pip install --upgrade pyqt5 pyqtwebengine
内容的提问来源于stack exchange,提问作者fpisto
相关产品推荐
相关产品推荐

