django 可自动下载的发票pdf

zpqajqem  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(98)

我想创建一个选项来下载一个pdf文件,该文件在django数据库管理中具有以下属性:

型号.py:

from django.db import models

from appsystem.models import Outlet
from core.models import Item, Supplier
from location.models import Warehouse, Zone, Section, Level

class MainPurchases(models.Model):
    METHOD_A = 'CASH'
    METHOD_B = 'CREDIT'

    PAYMENT_METHODS = [
        (METHOD_A, 'CASH'),
        (METHOD_B, 'CREDIT'),
    ]

    product = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.PositiveSmallIntegerField()
    purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
    paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
    date_created = models.DateTimeField(auto_now_add=True)
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)

我需要这是一个可打印的发票与指定的价值,但我只是不能得到任何地方。

vnjpjtjt

vnjpjtjt1#

这实际上是两个问题:如何从数据库中的数据生成pdf,以及如何将其传递到Web客户端(浏览器)。
作为对第二个问题的回答,这里有一个我之前写过的观点

from io import BytesIO

def pdfview( request, pk):

    quote = get_object_or_404( Quote, pk=pk)  # object to build pdf from

    pdf = build_pdf( quote)

    iobuf = BytesIO( bytearray(pdf.output( dest='S' ), encoding='latin-1'))

    response = HttpResponse( iobuf, content_type='application/pdf')
    response['Content-Disposition'
            ] = 'inline; filename={}.pdf'.format(quote.quotenumber) 

    # inline; will ask for an immediate display  of the content
    # attachment; will offer options to the user, including save without display
    # exact details are  browser-specific.

return response

至于build_pdf,我使用的是fpdf

from fpdf import FPDF

def build_pdf( quote):
    pdf = FPDF() 

    # pdf.this( ...)
    # pdf.that( ...)

    # much later, when done
    return pdf

相关问题