How to create pdf with multiple pages based on html using python pdfkit

I am trying to create a pdf with python using pdfkit library in my Django project, and I want to separate each content in a different page, how can I do it

import pdfkit
from django.template.loader import render_to_string

my_contents = [
    {'title':'Example 1', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 2', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 3', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 4', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 5', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}
]

final_html = ''
for content in my_contents:
    data = {
        'title': content['title'],
        'contents': content['contents'],
    }
    final_html += render_to_string(
        'pdfs/routines_handout.html', data)

my_pdf = pdfkit.from_string(final_html, 'out.pdf')

FOUND IT!! If I add the style='page-break-after' on every end of page, the next one would be in another page

<div style='page-break-after: always;'></div>

My final fixed code would be:

import pdfkit
from django.template.loader import render_to_string

my_contents = [
    {'title':'Example 1', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 2', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 3', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 4', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']},
    {'title':'Example 5', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}
]

cont = 0
final_html = ''
total_length = len(my_contents)
for content in my_contents:
    cont += 1
    data = {
        'title': content['title'],
        'contents': content['contents'],
    }

    final_html += render_to_string(
        'pdfs/routines_handout.html', data)
    if not cont == total_length:
        final_html += "<div style='page-break-after: always;'></div>"

my_pdf = pdfkit.from_string(final_html, 'out.pdf')
Back to Top