如何在Qprinter pyqt5中打印带有图像的html页面 [英] how to print html page with image in Qprinter pyqt5

查看:129
本文介绍了如何在Qprinter pyqt5中打印带有图像的html页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 html 代码为我的程序生成了一份报告,但它没有在 Qprinter 中显示图像.

i have generated a report for my program using html code but it doesn't show image in Qprinter.

def run(self):
    view = QtWebEngineWidgets.QWebEngineView()
    view.setHtml("""<img src="header.jpeg" alt="logo" width="280" height="100">""")
    printer = QPrinter()
    printer.setPaperSize(QtCore.QSizeF(80 ,297), QPrinter.Millimeter)
    try :
        r = QPrintDialog(printer)
        if r.exec_() == QPrintDialog.Accepted:
            view.page().print(printer, self.print_completed)
    except Exception as e :
        print(e)

我想打印的 html 代码.同一目录中的 header.jpeg .

html code that i want to print . the header.jpeg in same directory .

推荐答案

Qt Webengine 在打印时异步执行任务,由于 view 和 printer 是局部变量,当同步功能完成时它们将被消除.解决方案是在您完成运行后保留这些对象.

Qt Webengine executes the tasks asynchronously as printing, and since view and printer are local variables they will be eliminated when the synchro function is finished. The solution is to keep those objects even when you finish running.

不需要使用 QWebEngineView,因为您不会显示任何内容,只显示 QWebEnginePage.

Not necessary to use QWebEngineView since you will not show anything, just QWebEnginePage.

另一方面,文档说明外部资源(如图像)是根据传递的第二个参数的 URL 加载的.所以解决办法就是以当前目录为基础传递一个url.

On the other hand the docs states that external resources such as images are loaded based on the URL that is passed second parameter. So the solution is to pass a url using the current directory as a basis.

import os
# ...
def run(self):
    current_dir = os.path.dirname(os.path.abspath(__file__))
    self._page = QtWebEngineWidgets.QWebEnginePage()
    self._page.setHtml('''
    ... <img src="header.jpeg" alt="logo" width="280" height="100"> ...
    ''', QtCore.QUrl.fromLocalFile(os.path.join(current_dir, "index.html")))
    self._printer = QtPrintSupport.QPrinter()
    self._printer.setPaperSize(QtCore.QSizeF(80 ,297), QtPrintSupport.QPrinter.Millimeter)
    r = QtPrintSupport.QPrintDialog(self._printer)
    if r.exec_() == QtPrintSupport.QPrintDialog.Accepted:
        self._page.print(self._printer, self.print_completed)

这篇关于如何在Qprinter pyqt5中打印带有图像的html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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