1

我需要调整一些使用 QPrinter 将 HTML 转换为 PDF 的 Python 代码。HTML 包含一些 PNG,但现在需要用 SVG 替换。我真的不知道该怎么做。我天真地用等效的 SVG 替换了 PNG,但是 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>

似乎不起作用,而用等效的 PNG 替换 SVG 会产生完美的 PDF。有谁知道如何解决这一问题?

4

1 回答 1

0

我最终使用了 pdfkit(请参阅https://github.com/JazzCore/python-pdfkit),遵循此处给出的说明:wkhtmltopdf failure when embed an 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>

我想应该仍然可以在不求助于另一个库的情况下修复代码,但是这个解决方案对我来说是可行的。

于 2014-07-23T02:06:08.550 回答