首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何保存文件xhtml2pdf

如何保存文件xhtml2pdf
EN

Stack Overflow用户
提问于 2018-10-19 14:53:52
回答 1查看 875关注 0票数 1

我想把我的pdf文件保存到路径,但我不知道如何使这一点。

我的代码:

代码语言:javascript
复制
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。谢谢!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-19 15:33:08

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52894918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档