Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I need to adapt some Python code that converts HTML to PDF using QPrinter. The HTML includes some PNGs, but these now need to be replaced by SVGs. I do not really know how to do this. I naively replaced the PNGs with equivalent SVGs, but then the SVGs did not show up in the resulting PDF. To be more concrete, something like this
from PyQt4.QtGui import QTextDocument, QPrinter, QApplication
import sys
app = QApplication(sys.argv)
doc = QTextDocument()
doc.setHtml('''
<h1>Circle</h1>
<p><img src="circle.svg"/></p>
</body>
</html>
printer = QPrinter()
printer.setOutputFileName("circle.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
doc.print_(printer)
with circle.svg given by
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" fill="orange" />
does not seem to work, whereas replacing the SVG with an equivalent PNG produces a perfect PDF. Does anyone know how to fix this?
–
I ended up using pdfkit (see https://github.com/JazzCore/python-pdfkit), following the instructions given here: wkhtmltopdf failure when embed an SVG. The Python code now looks like this:
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 = '''
<h1>Circle</h1>
<p><img alt="" src="data:image/svg+xml;base64,''' + b64 + '''" /></p>
</body>
</html>
pdfkit.from_string(html, "circle.pdf")
with the SVG modified to:
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" fill="orange" />
I guess that it should still be possible to fix the code without resorting to another library, but this solution is workable for me.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.