我在Django中使用ReportLab制作条形图。我能够生成pdf,但它保存在我的根目录中。相反,我希望PDF应该在浏览器中打开。我该怎么办?
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics import renderPDF
from django.http import HttpResponse
def generate_report(request):
drawing = Drawing(400, 200)
data = [
(13, 5, 20, 22, 37, 45, 19, 4)
]
bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
#bc.strokeColor = colors.black
bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.valueAxis.valueStep = 10
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99',
'Apr-99','May-99','Jun-99','Jul-99','Aug-99']
drawing.add(bc)
# this returns None, but the file is saved in the directory.
return HttpResponse(renderPDF.drawToFile(drawing, 'example.pdf', 'lineplot with dates'))
修改
def generate_report(request):
# Create the HttpResponse object with the appropriate PDF headers.
ctx = { "power_energy_update_interval" : gv.power_energy_update_interval, \
"comparison_graph_update_interval" : gv.comparison_graph_update_interval, \
"hourly_update_interval" : gv.hourly_update_interval
}
if request.is_ajax():
if request.POST.has_key('start_date'):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
# Create the PDF object, using the response object as its "file."
p = canvas.Canvas(response)
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
p.drawString(100, 100, "Hello world.")
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
return response
return render(request, 'generate_report/reports.html', ctx)
在AJAX请求响应中尝试时,它不会返回响应。为什么呢?
答案 0 :(得分:1)
尝试:
# code...
page = renderPDF.drawToFile(drawing, 'example.pdf', 'lineplot with dates')
response = HttpResponse(page, mimetype='application/pdf')
我正在使用reportlab.pdfgen.canvas
,效果很好
请记住,在将其识别为PDF后,在浏览器中打开文件是客户端的浏览器(和/或操作系统)作业。
修改强>
这就是我在某些Web2Print解决方案上展示发票的方式:
from django.http import HttpResponse
from reportlab.pdfgen import canvas
def invoice_to_response(request, invoice):
response = HttpResponse(mimetype='application/pdf')
p = canvas.Canvas(response, pagesize='A4', pageCompression=0)
# here I draw on 'p' like p.setFillColor(black)
p.showPage()
p.save()
return response