12

I want to generate reports using WeasyPrint in Django. But I don't know how to integrate the css (specifically the bootstrap css file). I am able to see the generated html. But I get a warning when I add this line to my template-

<link href="/static/css/bootstrap.min.css" rel="stylesheet"/>

The warning is - Relative URI reference without a base URI: at line None

I would like to know how to send the base URI to the template. Any help would be appreciated.

aishpant
  • 903
  • 10
  • 19

2 Answers2

22

I had to add base_url=request.build_absolute_uri(). So the print command looks like:

weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response)
aishpant
  • 903
  • 10
  • 19
  • 2
    where does the request object come from? – Maecky Aug 02 '16 at 12:00
  • @Maecky I'm probably way to late with answering this, but this question has the Django tag. I assume `request` is the variable that is passed with all Django views. If you are in a Django view and you don't have a `request` variable available, you probably need to use `self.request`. Check out [this page in the Django docs](https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.build_absolute_uri) – JerkMan Nov 23 '16 at 16:22
  • 2
    For further readers Weasyprint basically wants this `HTML(string=html_rendered, base_url="/app")`- that's an absolute location or URL. It should be de-hardcoded, of course. – laimison Dec 28 '21 at 00:14
0

Adding '/' to request.build_absolute_uri() worked for me -> request.build_absolute_uri('/'):

weasyprint.HTML(string=html,base_url=request.build_absolute_uri('/')).write_pdf(response)
Liza Amatya
  • 141
  • 6