首页 > 解决方案 > 如何保存文件xhtml2pdf

问题描述

我想将我的 pdf 文件保存到路径中,但我没有关于如何制作它的信息。

我的代码:

def createPDf(request):
    num_sale = request.POST.get('num_sale')
    sale_header = Sale.objects.filter(secuence_id=num_sale).first()
    context = {
        'sale_header': sale_header,
    }

    pdf = render_to_pdf('reportes/pdf/pdfSale.html', context)

    # Force Download
    if pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        filename = "Sale_%s.pdf" % (str(sale_header.secuence))
        content = "inline; filename='%s'" % (filename)

        content = "attachment; filename='%s'" % (filename)
        response['Content-Disposition'] = content
        return response

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

请有人建议或链接如何保存pdf的路径..谢谢!

标签: djangoxhtml2pdf

解决方案


你可以使用这个脚本,这对我来说很好,但你需要安装pip install Weasyprint

def checkout_pdf(request, key):

from django.db.models import Sum

_queryset = CheckOut.objects.filter(id= key ).select_related('client').annotate(soma=Sum('checkoutitem__total_value')).all()
_company = SystemCustomization.objects.all().get()

from django.http import HttpResponse
from django.template.loader import render_to_string 
from weasyprint import HTML, CSS
import tempfile
from framework import settings

context= {'cli' : _queryset, 'company': _company}

 # Rendered
html_string = render_to_string('checkout-pdf.html', context) #choice your templae
html = HTML(string=html_string, base_url=request.build_absolute_uri())
result = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/application/css/invoice.css')]) #choice your css to customize the html

# Creating http response
response = HttpResponse(content_type='application/pdf;')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % key #choice filename
response['Content-Transfer-Encoding'] = 'binary'
with tempfile.NamedTemporaryFile(delete=True) as output:
    output.write(result)
    output.flush()
    output = open(output.name, 'rb')
    response.write(output.read())

return response

推荐阅读