2014-07-20 52 views
1

我需要修改一些使用QPrinter将HTML转换为PDF的Python代码。 HTML包含一些PNG,但现在需要用SVG取代它们。我真的不知道该怎么做。我天真地用相同的SVG取代了PNG,但是然后SVG没有出现在最终的PDF中。更具体的,像这样如何将包含SVG的HTML文档转换为Python中的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。有谁知道如何解决这一问题?

+0

我们仍在努力寻求一个很好的解决方案,但希望能够为JS和其他开发做出贡献的人们提供帮助。我们将把所有内容都转移到Github nexxt周,但你可以在这里看看。包括最终的SVG ... http://www.xportability.com/XEPOnline/FOTestSuite.html –

回答

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> 

我想,应该还是可以修复的代码而不诉诸另一个库,但这种方法是对我来说可行。

相关问题