打印为PDF Django和ReportLab

问题描述 投票:1回答:1

我目前在Django中具有此视图,该视图可在我的html页面上完美呈现一堆记录

def patient_page(request, id):
    pat = models.patient.objects.get(pk=id) # Goes to patient models returns pk according to page
    rec = models.record.objects.all().filter(patient_assign__pk=id).order_by('-date')
    return render(request=request,
                  template_name = 'main/patient_page.html',
                  context = {"pats":pat,
                             "rec":rec
                             }
                  )

我也有这段代码可以完美打印,我可以轻松地插入一个变量。

def write_pdf_view(textobject):

    #Need to play with filename.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="txt_obj.pdf"'
    buffer = BytesIO()
    my_canvas = canvas.Canvas(buffer)

    # Create textobject(s)
    textobject = my_canvas.beginText(30 * mm, 65 * mm)
    textobject.setFont('Times-Roman', 8)
    textobject.textLine(text="+ Hello This text is written 30mm in and 65mm up from the mark")

    my_canvas.drawText(textobject)

    title = "this is my title"
    my_canvas.setTitle(title)


    my_canvas.showPage()
    my_canvas.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

[我的问题,有没有人知道如何渲染为pdf并打印为PDF,即在html上的记录旁边,我有一个打印按钮,该按钮当前可将我的打印结果转换为pdf脚本。

python django reportlab
1个回答
0
投票

[确定,所以我当然是新手,正在学习,但是这里是我所做的,我实际上通过URL将一个记录号传递给了我的函数。我敢肯定有一种更好(更安全)的方法,但是我现在使用超级用户装饰器将其固定。 (从这里:django @login_required decorator for a superuser

{% for rec in rec %}
<ul>
  <b>Created: </b>{{ rec.date  }}  <b>Record:</b>  &nbsp <a href="{% url 'main:record_specific' rec.exam_record_number %}">{{ rec.exam_record_number }}</a>
<a href="{% url 'main:print_record' rec.exam_record_number %}" download style="float: right;">Print</a>
 <br>
    <p>{{ rec.exam_record  |safe}}</p>
  <hr>
</ul>

© www.soinside.com 2019 - 2024. All rights reserved.