我想使用Django制作pdf文件。我找到了ReportLab,并实现了它,但是主要的问题是我想从模板中创建pdf文件。该怎么办?
这是视图
from io import BytesIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
import random
def write_pdf_view(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
buffer = BytesIO()
p = canvas.Canvas(buffer)
papercustomization = ShortBlankDescriptionQuestions.objects.get(id=1)
# Start writing the PDF here
p.drawString(100, 100, papercustomization.sbd_question_text)
# End writing
p.showPage()
p.save()
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
答案 0 :(得分:0)
**#使用Django2.2和Python 3.8在Reportlab中制作的学校的特定教师报告 **
#views.py
class docente(View):
def _header_footer(self,canvas,doc):
canvas.saveState()
canvas.setTitle("PDF")
styles = getSampleStyleSheet()
header20 = Paragraph('Fecha: '+ time.strftime("%d/%m/%y"), styles['Normal'])
w, h = header20.wrap(doc.width-320, doc.topMargin)
header20.drawOn(canvas, 520, doc.height + doc.topMargin+15 )
footer = Paragraph('', styles['Normal'])
w, h = footer.wrap(doc.width, doc.bottomMargin)
footer.drawOn(canvas, doc.leftMargin, h)
canvas.restoreState()
def get(self,request, pk=None):
print ("Genero el PDF")
response = HttpResponse(content_type='application/pdf')
pdf_name = "clientes.pdf" # llamado clientes
# la linea 26 es por si deseas descargar el pdf a tu computadora
# response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
buff = BytesIO()
doc = SimpleDocTemplate(buff,
pagesize=letter,
rightMargin=40,
leftMargin=40,
topMargin=110,
bottomMargin=40,
)
if request.user:
clientes = []
styles = getSampleStyleSheet()
header=Paragraph('Reporte del Docente',styles['Heading1'])
clientes.append(header)
allclientes = Docente.objects.filter(pk=pk)
header5=Paragraph('',styles['Heading4'])
clientes.append(header5)
header5=Paragraph('Lista del docente',styles['Heading4'])
clientes.append(header5)
listas = []
count = 0
for i in allclientes:
count = count+1
vari = (count,i.cedula_docente,i.nombre_docente,i.apellido_docente,i.sexo,i.edad)
listas.append(vari)
#TABLA NUMERO 1
headings1 = ('N°','CEDULA','APELLIDOS','NOMBRES','SEXO','EDAD')
t1 = Table([headings1] + listas)
t1.setStyle(TableStyle(
[ ('GRID', (0, 0), (5, -1), 1, colors.black),
('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
]
))
header5=Paragraph('',styles['Heading4'])
clientes.append(header5)
clientes.append(t1)
doc.build(clientes,onFirstPage=self._header_footer,onLaterPages=self._header_footer,canvasmaker=NumberedCanvas)
else:
clientes = []
styles = getSampleStyleSheet()
header=Paragraph('Lista de usuarios registrados',styles['Heading1'])
clientes.append(header)
doc.build(clientes,onFirstPage=self._header_footer,onLaterPages=self._header_footer,canvasmaker=NumberedCanvas)
response.write(buff.getvalue())
buff.close()
return response
class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
canvas.Canvas.__init__(self, *args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
"""add page info to each page (page x of y)"""
num_pages = len(self._saved_page_states)
for state in self._saved_page_states:
self.__dict__.update(state)
self.draw_page_number(num_pages)
canvas.Canvas.showPage(self)
canvas.Canvas.save(self)
def draw_page_number(self, page_count):
self.setFont("Helvetica", 9)
self.drawRightString(211 * mm, 4 * mm + (0.1 * inch),"Pagina %d de %d" % (self._pageNumber, page_count))
#urls.py
path('docente/<int:pk>',login_required(docente.as_view()), name = 'docente'),