Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDF output using Weasyprint not showing images (Django)

Tags:

I am trying to output PDF on Django using the Weasyprint library, but the images don't appear on the generated PDF. I have tried both relative and static URLs for the images, but even the static URL doesn't show the image. When opening the HTML itself on chrome, the images do show.

Here is my pdf generation view in the views.py file:

def pdf_generation(request, some_slug)
    stud = Student.objects.get(some_slug=some_slug)
    studid = stud.some_slug
    context = {'studid':studid}
    html_string = render_to_string('templates/pdf_gen.html', context)
    html = HTML(string=html_string)
    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')]);
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
    return response

Here is the part of the HTML of the image:

<DIV id="p1dimg1">
<IMG src="{% static 'img/image.jpg' %}" alt="">
</DIV>

And the CSS:

#page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z-
index:-1;width:792px;height:1111px;}
#page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;}

Thank you very much

like image 858
선풍기 Avatar asked Feb 26 '18 12:02

선풍기


1 Answers

Fixed by:

Add base_url=request.build_absolute_uri() so that

html = HTML(string=html_string)

becomes

html = HTML(string=html_string, base_url=request.build_absolute_uri())

That will allow for relative URLs in the HTML file.

For the images, only PNG images seems to work for some reason.

For the HTML styles to show on the PDF, add presentational_hints=True as per the Weasyprint docs:

    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')], presentational_hints=True);
like image 148
선풍기 Avatar answered Oct 21 '22 01:10

선풍기