使用pyqt webview渲染pdf

pdf rendering using pyqt webview

我在 MS Excel 中创建了一个模板文件,导出为 html。模板文件包含多个字段,需要使用交互式 PyQt4 表单应用程序填充参数。问题是 PyQt4 webview 正确呈现文件并且只能在有单个 html 文件时直接打印,但对于多个文件(即生成 css 和 xml 文档)它不会return 正确的输出。如果没有 css 和 xml 文件,布局和样式将不匹配,并且会产生乱码打印。 代码是

dpi = 50
printer = QtGui.QPrinter()
printer.setResolution(dpi)
printer.setPageSize(QPrinter.A4)
printer.setPageMargins(12, 20, 10, 5, QPrinter.Millimeter)

document = QtWebKit.QWebView(self)
document.setHtml(self.template_html
                 ,QUrl("./misc/")) // here "misc" folder contains another   
                                   // folder "template_html_files" containing
                                   // the css and xml file

printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("added.pdf")

self.template_html 包含主要生成页面的 html 标签(使用 open 手动加载),以下文件由 MS excel 生成,用于被收录

filelist.xml
sheet001.htm
stylesheet.css
tabstrip.htm

目录结构为

./
|
|-----MainApplication.py
|-----misc
       |
       |-----template_html.html
       |-----template_html_files
                |
                |-------filelist.xml
                |-------sheet001.htm
                |-------stylesheet.css
                |-------tabstrip.htm

QWebView,setHtml()的第二个参数必须是QUrl。我想,QUrl不能是path-string,它必须是url, 见 Qt Documentation QUrl.

最简单的方法是,直接使用 html-file:

self.load(QtCore.QUrl('file://path to file')

在 html 的标题中找到如下链接

<LINK type="text/css" rel="stylesheet" href="./misc/Formatierung.CSS">

我只让它与 html-file

的绝对路径一起工作