diogenes
diogenes

Reputation: 2129

Add CSS to Pdfkit in Django?

I am not able to add my css to my PdfKit code.

The normal Static links in the HTML do not work.

<link href="{% static 'css/print.css' %}" rel="stylesheet">

I see this approach in the View but can not find a way to link the css file in Django.

css = 'print.css'
pdfkit.from_file('file.html', css=css)

Also found this answer for Flask - how to do the same for Django?

How to link stylesheet files to pdfkit in Flask application?

Thanks.

Upvotes: 2

Views: 6541

Answers (1)

Borut
Borut

Reputation: 3364

You need to add full path. Instead of

<link href="{% static 'css/print.css' %}" rel="stylesheet">

you'd use

<link href="http://localhost/static/css/print.css" rel="stylesheet">

The second approach you have found works too, but again you need to use full path for files, something like:

import os
from django.conf import settings

css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css')
pdfkit.from_file('file.html', css=css)

In the latter case you need to provide full path to file.html as well. In Django, however, you'd probably rather first render file.html to string and then use rendered html to create PDF. Something like:

import os
from django.conf import settings
from django.template.loader import render_to_string

t = render_to_string('file.html', {})
css = os.path.join(settings.STATIC_ROOT, 'css', 'print.css')

pdf = pdfkit.from_string(t, 'file.pdf', css=css)

... or if you'd like to return PDF as response

from django.http import HttpResponse

pdf = pdfkit.from_string(t, False, css=css)
response = HttpResponse(pdf)
response['Content-Type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment; filename = file.pdf'
return response

Upvotes: 10

Related Questions