PDF文件未获取上下文数据,它使用Django显示空表值

时间:2019-05-15 17:27:07

标签: python django pdf-generation

这是我的大学项目,我创建了Web应用程序,该应用程序生成了一些值和图表结果,现在我想以pdf格式下载该结果,我尝试使用以下代码,但是该代码创建了pdf,但显示了空表格值,但未显示图表。上下文数据未获取。

我尝试了以下代码。请给我建议。谢谢您。

def upload1(request):
   form = ReadFileForm()

   if request.method == 'POST':
       form = ReadFileForm(request.POST, request.FILES)
       if form.is_valid():
           file = request.FILES['file']
           ascii_data = np.loadtxt(file)

           data_m_sec = ascii_data
           data = {}
           data["RR"] = np.array(data_m_sec)
           data["BeatTime"] = np.cumsum(data["RR"]) / 1000.0
           data["niHR"] = 60.0 / (data["RR"] / 1000.0)


           info = {}
           info["beats"] = "{0:.2f}".format((len(data["BeatTime"])))
           info["minhr"] = "{0:.2f}".format(min(data["niHR"]))
           info["maxhr"] = "{0:.2f}".format(max(data["niHR"]))
           info["meanhr"] = "{0:.2f} bps".format(np.mean(data["niHR"]))
           info["meanrr"] = "{0:.2f} msec.".format(np.mean(data["RR"]))


           # for RR Histogram
           fig1 = plt.figure(1)
           axes = fig1.add_subplot(1, 1, 1)
           axes.hist(data["RR"], 30, density=1, facecolor="red")
           axes.set_xlabel("RR (msec.)")
           axes.set_ylabel("Probability")
           axes.set_title("RR histogram")
           axes.grid(True)
           img_in_memory = BytesIO()
           plt.savefig(img_in_memory, format="png")
           img_in_memory.seek(0)
           image1 = base64.b64encode(img_in_memory.getvalue())
           image1 = image1.decode('utf8')
           plt.close(fig1)

           context = {
               "image1": image1,
               "beats": info["beats"],
               "meanhr": info["meanhr"],
               "meanrr": info["meanrr"],
               "minhr": info["minhr"],
               "maxhr": info["maxhr"],
           }

            return render(request, "upload/base.html", context)
    return render(request, "upload/upload.html", {"form": form})

def generate_pdf(request):
    report = upload1(request)
    template_path = 'upload/base.html'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

    html = render_to_string(template_path, {'report': report})
    print (html)

    pisaStatus = pisa.CreatePDF(html, dest=response)

    return response

0 个答案:

没有答案