我正在使用Django和Reportlabs以PDF格式生成报告。我指的是this tutorial。
我还阅读了this thread以及this thread,其中说使用了canv.showpage()
,然后我就可以将1个图表合并为1个pdf,但我仍然只得到那个图表在代码中排在第二位,在我的例子中只有折线图。
如何以1 pdf格式保存2张图表?
这是我的代码。
import barchart
import linechart
from django.http import HttpResponse
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics import renderPDF
from reportlab.pdfgen import canvas
def generate_report(request):
#instantiate a drawing object
canv = canvas.Canvas('output.pdf')#,pagesize=LETTER)
canv.setPageCompression(0)
d = barchart.MyBarChartDrawing()
#extract the request params of interest.
#I suggest having a default for everything.
if 'height' in request:
d.height = int(request['height'])
if 'width' in request:
d.width = int(request['width'])
if 'numbers' in request:
strNumbers = request['numbers']
numbers = map(int, strNumbers.split(','))
d.chart.data = [numbers] #bar charts take a list-of-lists for data
if 'title' in request:
d.title.text = request['title']
#get a GIF (or PNG, JPG, or whatever)
binaryStuff = d.asString('pdf')
#binaryStuff.save()
#return HttpResponse(binaryStuff, 'image/pdf')
#instantiate a drawing object
canv.showPage()
a = linechart.MyLineChartDrawing()
#extract the request params of interest.
#I suggest having a default for everything.
a.height = 300
a.chart.height = 300
a.width = 300
a.chart.width = 300
a.title._text = request.session.get('Some custom title')
a.XLabel._text = request.session.get('X Axis Labell')
a.YLabel._text = request.session.get('Y Axis Label')
a.chart.data = [((1,1), (2,2), (2.5,1), (3,3), (4,5)),((1,2), (2,3), (2.5,2), (3.5,5), (4,6))]
labels = ["Label One","Label Two"]
if labels:
# set colors in the legend
a.Legend.colorNamePairs = []
for cnt,label in enumerate(labels):
a.Legend.colorNamePairs.append((a.chart.lines[cnt].strokeColor,label))
#get a GIF (or PNG, JPG, or whatever)
binaryStuff1 = a.asString('pdf')
canv.showPage()
return HttpResponse(binaryStuff, 'pdf')
条形图和折线图代码与this site相同。
我如何只保存在一个pdf文件中?
答案 0 :(得分:0)
根据提供的代码,您只获得折线图,因为您只是将BinaryStuff传递给响应(查看代码的最后3行)。
尝试将图形创建为图像,将图像绘制到画布上,然后将画布作为PDF返回。