Django and weasyprint, merge pdf

廉价感情. 提交于 2020-05-10 06:55:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38987854/django-and-weasyprint-merge-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!