[ django响应pdf文件 ]


Django响应Pdf文件

class PdfView(View):
    def get(self, request):
        buffer = io.BytesIO()
        p = canvas.Canvas(buffer)

        p.drawString(100, 100, "hello word.")
        p.showPage()
        p.save()
        buffer.seek(0)
        return FileResponse(buffer, as_attachment=True, filename="hello.pdf")


from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table
from reportlab.lib import colors
class PdfView1(View):
    def get(self, request):
        # 定义数据和表格样式(去掉了GRID属性)
        data = [
            ['Name', 'Age', 'Country'],
            ['John Doe', 30, 'USA'],
            ['Jane Smith', 25, 'Canada'],
            ['Tom Brown', 35, 'UK']
        ]
        table_style = [
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 12),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 0), (-1, 0), '#CCCCCC'),
            ('TEXTCOLOR', (0, 0), (-1, 0), '#000000'),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.white), 
            # ('GRID', (0, 0), (-1, -1), 0),  # 将GRID属性设为0
        ]

        # 创建PDF文档对象并添加表格
        pdf_buffer = io.BytesIO()
        pdf = SimpleDocTemplate(pdf_buffer, pagesize=letter)
        table = Table(data)
        table.setStyle(table_style)
        elements = [table]
        pdf.build(elements)

        # 将生成的PDF文件作为HTTP响应返回
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="example.pdf"'
        response.write(pdf_buffer.getvalue())
        pdf_buffer.close()
        return response