简体   繁体   English

PyQt5可以使用QWebEngineView在后台打印PDF,没有GUI?

[英]PyQt5 possible to use QWebEngineView to print PDF in background, no GUI?

I want to use Python to convert some html files to PDF. 我想使用Python将一些html文件转换为PDF。 After looking at the modules and possibilities to do this, I settled on Qt5. 在查看了模块和执行此操作的可能性之后,我选择了Qt5。

I have code that works, but it doesn't work exactly how I want. 我有可以工作的代码,但是并不能完全按照我的要求工作。 I want to run my program via the command line, and it to exit once finished. 我想通过命令行运行程序,并在完成后退出。 Currently, it produces the PDF but stays running. 当前,它会生成PDF,但仍可运行。

If I uncomment and show the QWebEngineView with view.show(), then I can close the window that opens and the program will exit. 如果取消注释并使用view.show()显示QWebEngineView,则可以关闭打开的窗口,程序将退出。 (But I don't want to have any GUI, so this isn't good) (但是我不想有任何GUI,所以这不好)

Next, I tried to show the view, then immediately close it after with view.close(), but when I do this a PDF doesn't get generated. 接下来,我尝试显示该视图,然后使用view.close()立即将其关闭,但是当我这样做时,不会生成PDF。 I tried adding a 5 second sleep after view.show() and before view.close(), but still the same result. 我尝试在view.show()之后和view.close()之前添加5秒钟的睡眠,但结果仍然相同。

I'm not sure if what I want is possible, I understand Qt is for GUIs but it would be very convenient if I could get this working completely through the command line. 我不确定我想要的是否可行,我了解Qt适用于GUI,但是如果我可以通过命令行完全使用它,将非常方便。

import sys
import os
from time import sleep

from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QDir, QUrl

# needed to load local html files
sys.argv.append("--disable-web-security")
app = QApplication(sys.argv)

raw_html = ""
with open('webpage.htm', 'r') as myfile:
    raw_html = myfile.read()

view = QWebEngineView()
view.setHtml(raw_html)

def save_pdf(finished):
    view.page().printToPdf("output.pdf")
    # view.show()
    # view.close()

view.loadFinished.connect(save_pdf)

sys.exit(app.exec_())

Try it: 试试吧:

import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

app = QtWidgets.QApplication(sys.argv)

loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)

loader.page().pdfPrintingFinished.connect(loader.close)             # <---

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM