def generate_discharge_report(patient_id, email): patient = PatientRegistration.objects.get(id=patient_id) consultations = PatientConsultation.objects.filter( patient=patient).order_by("-created_date") diseases = Disease.objects.filter(patient=patient) if consultations.exists(): consultation = consultations.first() samples = PatientSample.objects.filter(patient=patient, consultation=consultation) daily_rounds = DailyRound.objects.filter(consultation=consultation) investigations = InvestigationValue.objects.filter( consultation=consultation.id) investigations = list( filter(lambda inv: inv.value is not None or inv.notes is not None, investigations)) else: consultation = None samples = None daily_rounds = None investigations = None date = make_aware(datetime.datetime.now()) disease_status = DiseaseStatusEnum( patient.disease_status).name.capitalize() html_string = render_to_string( "patient_pdf_template.html", { "patient": patient, "samples": samples, "consultation": consultation, "consultations": consultations, "dailyrounds": daily_rounds, "date": date, "diseases": diseases, "investigations": investigations, "disease_status": disease_status, }, ) filename = str(int(round(time.time() * 1000))) + randomString(10) + ".pdf" bytestring_to_pdf( html_string.encode(), default_storage.open(filename, "w+"), **{ "no-margins": None, "disable-gpu": None, "disable-dev-shm-usage": False, "window-size": "2480,3508" }, ) file = default_storage.open(filename, "rb") msg = EmailMessage( "Patient Discharge Summary", "Please find the attached file", settings.DEFAULT_FROM_EMAIL, (email, ), ) msg.content_subtype = "html" # Main content is now text/html msg.attach(patient.name + "-Discharge_Summary.pdf", file.read(), "application/pdf") msg.send() default_storage.delete(filename)
def get(self, request, *args, **kwargs): """ Render page to the specified output filename using headless browser """ response = super(PDFViewMixin, self).get(request, *args, **kwargs) if 'html' in request.GET: return response response.render() output_file = NamedTemporaryFile() extra_args = {} if self.virtual_time_budget is not None: extra_args.update( {'virtual-time-budget': self.virtual_time_budget}) bytestring_to_pdf(response.content, output_file, **extra_args) # Return the file response = FileResponse(output_file, content_type="application/pdf") atc = 'attachment;' if self.download_attachment else '' response['Content-Disposition'] = '{}filename="{}"'.format( atc, self.get_filename()) return response
def get_file_response(self, content, output_file, extra_args): bytestring_to_pdf(content, output_file, **extra_args) return FileResponse(output_file, content_type="application/pdf")