Search code examples
pythondjangowkhtmltopdf

wkhtmltopdf-django dynamic template to render


Is there any way to generate a PDF dynamically, with content being fetched from the database?

My goal is to allow my users to generate their own PDF design from a wysiwyg editor.

This is my model

    class DocumentService(models.Model):
        name = models.CharField(max_length=60, blank=True)
        html_content = models.TextField(blank=True)

I use django-wkhtmltopdf to render html to PDF.

    response = PDFTemplateResponse(
            request=request,
            template="document.html",
            filename=filename,
            context=data,
            show_content_in_browser=True,
            cmd_options=cmd_options,
        )

How can I render the content of this record into my PDF?

    document = DocumentService.objects.get(pk=1)
    document.html_content # <-- this content

The HTML content should be something like this

<html>
  <body>
    <p>
      <strong>Date: </strong> {{date}}
      <strong>User: </strong> {{user.name}}
      <strong>Email: </strong> {{user.email}}
      <strong>Info: </strong> {{user.info}}
      ...
    </p>
  </body>
 </html>

Solution

  • Just use engines.from_string(template_code)

    from django.template import engines
    
    document = DocumentService.objects.get(pk=1)
    data = {'data': document.html_content}
    str_template = render_to_string("document.html", data) 
    response = PDFTemplateResponse(
                request=request,
                template= engines['django'].from_string(str_template),
                filename=filename,
                context=data,
                show_content_in_browser=True,
                cmd_options=cmd_options,
            )
    

    and inside your document.html you've to add like this

    <body>
     {{data|safe}} <!--- Use safe if you want to render html --->
    </body>