如何在Python中将包含SVG的HTML文档转换为PDF文件
我需要调整一些用Python编写的代码,这段代码是用QPrinter把HTML转换成PDF的。HTML里面有一些PNG格式的图片,但现在我需要把它们换成SVG格式的。我其实不太知道该怎么做。我简单粗暴地把PNG换成了对应的SVG,但结果是SVG在生成的PDF里没有显示出来。具体来说,像这样
from PyQt4.QtGui import QTextDocument, QPrinter, QApplication
import sys
app = QApplication(sys.argv)
doc = QTextDocument()
doc.setHtml('''
<html>
<body>
<h1>Circle</h1>
<p><img src="circle.svg"/></p>
</body>
</html>
''')
printer = QPrinter()
printer.setOutputFileName("circle.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
doc.print_(printer)
用circle.svg替换
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" fill="orange" />
</svg>
似乎不行,而把SVG换成相应的PNG就能生成完美的PDF。有没有人知道该怎么解决这个问题?
1 个回答
1
我最后选择使用了pdfkit(可以查看这个链接:https://github.com/JazzCore/python-pdfkit),按照这里的说明进行操作:wkhtmltopdf在嵌入SVG时出错。现在我的Python代码看起来是这样的:
import base64
import os
import pdfkit
with open("circle.svg") as f:
data=f.read()
encoded_string = base64.b64encode(data.encode('utf-8'))
b64 = encoded_string.decode('utf-8')
html = '''
<html>
<body>
<h1>Circle</h1>
<p><img alt="" src="data:image/svg+xml;base64,''' + b64 + '''" /></p>
</body>
</html>
'''
pdfkit.from_string(html, "circle.pdf")
而SVG文件修改成了:
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" fill="orange" />
</svg>
我觉得应该还是可以不使用其他库来修复代码,但这个解决方案对我来说是可行的。