Search code examples
pythondjangopdfweasyprint

Django and weasyprint, merge pdf


It's possible to merge multiple pdf in django with weasyprint?

I have something like this:

def verpdf(request, pk):
    odet = get_object_or_404(Note, pk = pk)
    template = get_template('pdfnot.html')
    template1 = get_template('pdfnot2.html')
    p1 = template.render({'odet': odet}).encode(encoding="ISO-8859-1")
    p2 = template1.render({'note':odet}).encode(encoding="ISO-8859-1")
    pdf1 = HTML(string=p1).render()
    pdf2 = HTML(string=p2).render()
    all_pages = [po for po in pdf1.pages for doc in pdf2.pages]
    pdf_file = pdf1.copy(all_pages).write_pdf()
    http_response = HttpResponse(pdf_file, content_type='application/pdf')
    http_response['Content-Disposition'] = 'filename="report.pdf"'

    return http_response

But i'm not able to join the two files, always output only the first template, it's possible to merge the two documents into one pdf? Can you help me? Thanks.


Solution

  • Took me a while, but i solved it, was my fault for not understand the documentation lol, here is the code if anyone have the same problem:

    def verpdf(request, pk):
        odet = get_object_or_404(Note, pk = pk)
        template = get_template('pdfnot.html')
        template1 = get_template('pdfnot2.html')
        p1 = template.render({'odet': odet}).encode(encoding="ISO-8859-1")
        p2 = template1.render({'note':odet}).encode(encoding="ISO-8859-1")
        pdf1 = HTML(string=p1)
        pdf2 = HTML(string=p2)
        pdf11 = pdf1.render()
        pdf12 = pdf2.render()
    
        val = []
    
        for doc in pdf11, pdf12:
            for p in doc.pages:
                val.append(p)
    
        pdf_file = pdf11.copy(val).write_pdf() # use metadata of pdf11
    
        http_response = HttpResponse(pdf_file, content_type='application/pdf')
        http_response['Content-Disposition'] = 'filename="report.pdf"'
    
        return http_response
    

    And with this an pdf output with two pages.