По ReportLab у меня есть две задачи:
1) Есть большая динамическая таблица, нужно ее разделить на несколько страниц в PDF-файле.
2) Данные в таблице не отображаются в таблице
Полный код:
from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpRequest, HttpResponseRedirect, HttpResponse
from PIL import Image
import PIL
import reportlab
from django.http import FileResponse
from reportlab.pdfgen import canvas
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch, mm
from reportlab.platypus import Paragraph, Frame
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
def li(x):
return unicode(x, 'utf-8')
def total_report(pk):
#Set Dimensions of the sheet
width, height = letter
margin = inch
mwidth = width - 2*margin
mheight = height - 2*margin
#Set the styles to Centered and Arial
styleSheet = getSampleStyleSheet()
style = styleSheet['Normal']
style.alignment = 0
style.font = "Arial"
style.fontSize = 14
style.wordWrap = True
#Data
response = HttpResponse(content_type='application/pdf')
filename = 'total_report.pdf'
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
buffer = BytesIO()
p = canvas.Canvas(buffer)
p.setPageCompression(0)
p.translate(margin,margin)
p.translate(0,mheight-inch)
p.setFont("Arial",20)
#new_page
p.translate(margin,margin)
p.translate(0,mheight-inch)
p.setFont("Arial",20)
p.translate(0, -.2*inch)
p.drawCentredString(mwidth/2,0,u"Результаты".encode('utf-8'))
p.translate(0, -10*inch)
header = Paragraph("<bold><font size=18>TPS Report</font></bold>", style)
data = [['Дата', 'Текст', 'Ключевые слова', 'Ресурс','Источник/ автор','Язык','Участие эксперта','Тональность','комментарий'],
]
results = Results.objects.all()
ti = results.filter(theme=pk)
datas = []
for i in ti:
rt = []
rt.append(str(i.date)[:10])
rt.append(str(i.text))
rt.append(str(i.key_words))
rt.append(str(i.resource))
rt.append(str(i.author))
rt.append(str(i.language))
rt.append(str(" "))
rt.append(str(i.sa))
rt.append(str(" "))
datas.append(rt)
for j in datas:
print(j)
data.append(j)
data2 = [[Paragraph(li(cell.encode('utf-8')), styleSheet['Table']) for cell in row] for row in data]
u = Table(data2, colWidths=(50, 68, 50, 50,50, 50,50, 50,50))
u.setStyle(TableStyle([('FONT',(0, 0), (-1, -1), 'Arial'),
('FONTSIZE',(0, 0), (-1, -1), 9),
('BOX', (0, 0), (-1, -1), 0.25, colors.black),
('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ] ) )
u.wrapOn(p, mwidth, mheight)
u.drawOn(p,0,0)
p.showPage()
p.save()
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response