3๐
I solved this problem by encoding the image in base64 and sending to the template through context, then rendering with CSS. You can put your uri definition just before using HTML
So, my task is like this:
from django.template.loader import get_template
from weasyprint import HTML
with open("path/to/image.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
context = {..., "img":encoded_string , ...}
html_template = get_template('my_template_to_PDF.html')
html = html_template.render(context).encode(encoding="UTF-8")
uri = request.build_absolute_uri()
pdf_file = HTML(string=html,base_url=uri,encoding="UTF-8").write_pdf('path/to/output.pdf')
The template:
<style>
...
div.image {
width:150px;
height:50px;
background-image:url(data:image/png;base64,{{img}});
}
...
</style>
...
<div class = 'image'></div>
...
Hope it helps!
๐คAlex
Source:stackexchange.com