This is a follow up to my previous question Adding multiple images to a html file using Jinja2
I am trying to save the html created using jinja2
to pdf.
import jinja2
env = jinja2.Environment(
loader=jinja2.FileSystemLoader('.'),
trim_blocks=True,
lstrip_blocks=True,
)
template = env.get_template("template.html")
template_vars = [
{"title": "TITLE", "graph": "obj.jpg"},
{"title": "TITLE2", "graph": "obj2.jpg"},
]
#template_vars = {"title":"TITLE", "graph":'obj.png'}
text = template.render(template_vars)
with open("test.html", "w") as f_out:
f_out.write(text)
Template:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>TITLE</title>
</head>
<body>
<h2>Graph Goes Here</h2>
<dl>
{% for image in template_vars %}
<dt>{{ image.title }}</dt>
<dd><img title="{{ image.title }}" src="{{ image.graph }}"></dd>
{% endfor %}
</dl>
</body>
</html>
To convert the html created in the above code, I tried to use pdfkit
pdfkit.from_file('test.html', 'test.pdf')
But this didn't work for me; I get the following error
Error:
File "C:\Users\xxxx\anaconda3\envs\pancreas_model\lib\site-packages\pdfkit\pdfkit.py", line 155, in handle_error
raise IOError('wkhtmltopdf reported an error:\n' + stderr)
OSError: wkhtmltopdf reported an error:
Exit with code 1 due to network error: ProtocolUnknownError
I also tried xhtml2pdf
and this fails due to the image paths
with open('test.pdf', "w+b") as f_out:
pisa.CreatePDF(
src=text, # HTML to convert
dest=f_out)
WARNING:xhtml2pdf:Need a valid file name! ''
Could someone please suggest how to convert the html with multiple images to pdf? I am not sure if I have to specify a template for the pdf output like the one specified for html.
EDIT:
The relative path is specified in the template in the following line
<dd><img title="{{ image.title }}" src="./{{ image.graph }}"></dd>