I'm having the same problem but still no solution found on the internet.
Maybe an (awful?) workaround would be to copy the content of the .css file and paste it as internal CSS (with <style>...</style>
) through the context into the .html template ?
I'm in the same situation of dynamically generating an invoice pdf file with xhtmltopdf python library (from this tutorial).
Generate pdf from html template :
from xhtml2pdf import pisa
# Additional imports
def html2pdf(template_src, context=None, request=None):
context = context or {}
html = render_to_string(template_src, context, request=request)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
Display the generated file to user though view :
def view_invoice_pdf(request, invoice):
pdf = html2pdf('path/to/invoice_template.html',
context={'invoice': invoice},
request=request)
return HttpResponse(pdf, content_type='application/pdf')
Simple template example :
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Invoice {{ invoice.full_name }}</title>
<meta name="created" content="{% now 'DATETIME_FORMAT' %}"/>
<meta name="changed" content="{% now 'DATETIME_FORMAT' %}"/>
<link href="{% static 'my_app/css/sample.css' %}" rel="stylesheet" type="text/css"/>
</head>
<body>
<p class="foo-class">Fancy styled text</p>
{{ invoice }}
</body>
</html>
I also tried playing with RequestContext
but not sure what to do and could not find the way to go.
Hope someone will come with a solution!