当前位置: 首页 > 工具软件 > WeasyPrint > 使用案例 >

weasyprint 生成发票pdf文件

南宫兴德
2023-12-01
  • 语言Python
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
import weasyprint

@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    # 渲染
    html = render_to_string('orders/order/pdf.html',
                         {'order': order})

    # 构造response                 
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=\
          "order_{}.pdf"'.format(order.id)
    # 写入
    weasyprint.HTML(string=html).write_pdf(response,
       stylesheets=[weasyprint.CSS(
           settings.STATIC_ROOT + 'css/pdf.css')])
    return response
 类似资料: