django - 如何保存文件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的路径..谢谢!
解决方案
你可以使用这个脚本,这对我来说很好,但你需要安装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
推荐阅读
- swift - 在 Swift 中,导航栏消失并且永远不会回来
- groovy - 显示一个键的多个值
- python - 从数据库中获取 TransmogrifAI 的数据
- python-3.x - Pandas Excel 读取 - 整数列在循环时转换为浮点数
- angular5 - ng add 不适用于使用 angular 5 的 ngx-bootstrap
- android - 在 Service 、Alarm Manager 和 Job Scheduler 中哪个概念最好使用
- azure - 如何在 Azure 流分析中解压缩 Gzip 数据?
- redis - Redis 键在集群模式下被自动删除
- xml - xml 类型元素的术语是什么
- xamarin.forms - 如何在 xamarin StackLayout 中为 TextEdit 和 Button 提供 ID