Getting the base URI for Weasyprint in Python

I am using the Weasyprint library for Python in an attempt to print an html file to pdf. I am trying to insert an image in the background of my page. Here is the code:

    <h1>The title</h1>
    <p>Content goes here
''', base_url=os.path.dirname(os.path.realpath(__file__))).write_pdf("hello.pdf",  stylesheets=[CSS(string='body{background-image: url("example_image.png")}')])


The output I get for this code is as follows:

Ignored `background-image: url("example_image.png")` at 1:6, Relative URI reference without a base URI: 'example_image.png'.
blah@blah:~/Dropbox/Terraverde/annual_reports$ python3


I tried to find Stackoverflow to solve this problem and read the documentation, but the closest thing I could find in the answer is the following post about an identical problem, but for Django: Warning about CSS integration in Django WeasyPrint: Relative URI reference without base URI : <link href = "/static/css/bootstrap.min.css"> on line None

I have also tried using document.baseURI in my code:

base_url=os.path.dirname(os.path.realpath(__file__))).write_pdf("hello.pdf",  stylesheets=[CSS(string='body{background-image: url(document.baseURI + "example_image.png")}')])


but that still gave an error:

Parse error at 1:24, unexpected BAD_URI token in property value


Any suggestions on how to handle the problem, or maybe a Django-like command request.build_absolute_uri()

for regular Python or for Flask?


source to share

1 answer

I had the same error when I had this tag, on OSX, in a template that I rendered with pystache:

<img src="/Users/my_username/my_project/my_image.png" />


So, I tried this and it worked:

<img src="file:///Users/my_username/my_project/my_image.png" />


Just add file: // before the / Users / .... path (Note that these are 3 slashes).



All Articles