简体   繁体   中英

Printing to PDF Django & ReportLab

I currently have this view in Django, which renders a bunch of records on my html page perfectly

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
                             }
                  )

I also have this code which prints perfectly, I could easily insert a variable.

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

My Question, does anyone have an idea of how I might render to pdf AND print to PDF, ie next to the record on the html I have a print button which currently runs my print to pdf script.

OK, so of course I'm a newbie and learning but here' what I did, I essentially passed a record number through a url into my function. I'm sure there's a better (more secure) way, but I secured it with a superuser decorator for now. (from here: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM