Skip to content

Django HTML & CSS render to pdf

I’m trying to convert HTML & CSS into a pdf page using Django-weasyprint but I’m kind of stuck with their tutorial because I want the PDF to render the current page when the user clicks on the download button and the pdf downloads automatically with read-only privileges. This whole process kind of feels painful to do.

Currently, weasyprint just converts a URL in Django to pdf, but I don’t know how to set the button to look at the weasyprint view.

Maybe I am looking past it and over complicating it, any assistance would be appreciated.

Weasyprints example code:

from django.conf import settings
from django.views.generic import DetailView

from django_weasyprint import WeasyTemplateResponseMixin
from django_weasyprint.views import CONTENT_TYPE_PNG


class MyModelView(DetailView):
    # vanilla Django DetailView
    model = MyModel
    template_name = 'mymodel.html'


class MyModelPrintView(WeasyTemplateResponseMixin, MyModelView):
    # output of MyModelView rendered as PDF with hardcoded CSS
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'css/app.css',
    ]
    # show pdf in-line (default: True, show download dialog)
    pdf_attachment = False
    # suggested filename (is required for attachment!)
    pdf_filename = 'foo.pdf'


class MyModelImageView(WeasyTemplateResponseMixin, MyModelView):
    # generate a PNG image instead
    content_type = CONTENT_TYPE_PNG

    # dynamically generate filename
    def get_pdf_filename(self):
        return 'bar-{at}.pdf'.format(
            at=timezone.now().strftime('%Y%m%d-%H%M'),
        )

I made a virtual env on my pc and it’s setup exactly like the example. Currently using Boostrap 4.

*Edit if there is a better way of doing it, you are more than welcome to share it 🙂

Also I want to target just the body tags so that it converts only that section to pdf and not the ENTIRE page.

The solution I used before this is: https://codepen.io/AshikNesin/pen/KzgeYX but this doesn’t work very well.

*EDIT 2.0

I’ve moved on to js and I’m stuck with this script where it doesn’t want to create the pdf form on click function also is there a way to set the js function to ONLY download the selected Id in the div and not on certain scale? (afraid that it’s going to use the resolution instead of the actual content that needs to be rendered)

https://jsfiddle.net/u4ko9pzs/18/

Any suggestions would be greatly appreciated.

Answer

You don’t need to use that django app. You can write a custom view to handle printing as per example in the blog post https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/

I found that app limiting and wrote my own views. It’s not that hard.