amr_aly

render to pdf

May 28th, 2021 (edited)
1,243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.62 KB | None | 0 0
  1. ###################### views.py
  2. from django.shortcuts import render
  3. # import cStringIO as StringIO
  4. from io import BytesIO
  5. # from typing import ContextManager  
  6. from django.http import HttpResponse
  7. from django.template.loader import get_template
  8. from xhtml2pdf import pisa
  9.  
  10. # from bidi import algorithm as bidialg
  11. # import win_unicode_console
  12. # win_unicode_console.enable()
  13. # from pyarabic import araby
  14. # import pyarabic.araby as araby #, normalize_ligature
  15. # import pyarabic.number as number
  16. # from pyarabic.araby import strip_diacritics, normalize_ligature
  17.  
  18.  
  19.  
  20. def render_to_pdf(template_src, context_dict={}):
  21.     template = get_template(template_src)
  22.     html  = template.render(context_dict)
  23.     result = BytesIO()
  24.  
  25.     ''' important notes about rendring html to pdf via 'pisa' next three lines are working good to fix the problem
  26.    of Arabic language except the letters are separated
  27.    '''
  28.     # pdf = pisa.CreatePDF(bidialg.get_display(html, base_dir="L"), result, encoding='iso-8859-6') # CreatePDF = pisaDocument
  29.     # pdf = pisa.pisaDocument(BytesIO(bidialg.get_display(html.encode('utf-8'), base_dir='L')), result)
  30.     # pdf = pisa.pisaDocument(bidialg.get_display(html.encode('UTF-8')), result)
  31.    
  32.     pdf = pisa.CreatePDF(BytesIO(html.encode("UTF-8")), result)
  33.    
  34.     #
  35.     # pdf = pisa.pisaDocument(BytesIO(html.encode("iso-8859-6")), result)
  36.     # pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
  37.        
  38.     # print(type(html.encode('utf8')))#(var.encode('utf8'))
  39.     # print((bytes(b,'utf-8')))
  40.     # https://stackoverflow.com/questions/60139294/rendering-pdf-template-in-django-in-arabic-language
  41.     # pdf = pisa.pisaDocument(BytesIO(html.encode('cp1252')), result)
  42.     if not pdf.err:
  43.         return HttpResponse(result.getvalue(), content_type='application/pdf')
  44.     return None
  45.  
  46.  
  47.  
  48. #This is method based to render to pdf
  49. def get_pdf(request, visit_id, *args, **kwargs):
  50.     vis_id = Visits.objects.get(id=visit_id)
  51.     qs = Medicine.objects.filter(visit=visit_id).order_by('-id')
  52.     plan = Medicine.objects.values('plan').filter(visit=visit_id).first()
  53.     plan1 = Medicine.objects.filter(plan=plan['plan'])
  54.     vdate = Visits.objects.values('visitdate').filter(id=visit_id).first()
  55.     visitdate = vdate['visitdate']
  56.  
  57.     patname = Medicine.objects.values('patient').filter(visit=visit_id).first()
  58.     patient = Patients.objects.get(id=patname['patient'])#patname['patient']
  59.  
  60.     print(patient , plan1)
  61.     query = Medicine.objects.all().order_by('-id')
  62.     # print()
  63.     # zero_remain = LaundryBill.objects.filter(sumtotal__gt=0, returns=False, remain=0).order_by('-id')
  64.     template = get_template('clinic/pdf.html')
  65.     context = {
  66.         'qs': qs,
  67.         "query":query,
  68.         "visit_no": vis_id,
  69.         "name": patient,
  70.         "date": visitdate,
  71.         "today": "Today",
  72.     }
  73.     html = template.render(context)
  74.     pdf = render_to_pdf('clinic/pdf.html', context)
  75.     if pdf:
  76.         response = HttpResponse(pdf, content_type='application/pdf')
  77.         filename = "Prescription_"+str(time.strftime('%d-%m-%Y'))+".pdf" #%('%Y-%m-%d')
  78.         content = "inline; filename=%s" %(filename)
  79.         download = request.GET.get("download")
  80.         if download:
  81.             content = "attachment; filename='%s'" %(filename)
  82.         response['Content-Disposition'] = content
  83.         return response
  84.     return HttpResponse(pdf, content_type='application/pdf')
  85.  
  86.  
  87. ###################################### pdf.html
  88.  
  89. <!-- # -*- coding: utf-8 -*- -->
  90. <!--  -->
  91. {% load render_table from django_tables2 %} {% load querystring from django_tables2 %} {% load static %}
  92.  
  93. <!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -->
  94. <!DOCTYPE html>
  95. <html dir="auto" lang="ar">
  96. <!-- <html xmlns="" xml:lang="ar" lang="ar" dir="rtl"> -->
  97. <!-- dir="rtl" http://www.w3.org/1999/xhtml -->
  98.  
  99. <head>
  100.     <title>عرض الملفات</title>
  101.     <meta charset="UTF-8">
  102.     <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
  103.     <!-- <meta http-equiv="content-type" content="text/html; charset=windows-1256"> -->
  104.     <!-- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-6"> -->
  105.     <meta http-equiv=Content-Type content="text/html;charset=utf-8">
  106.     <meta http-equiv="content-type" content="text/html" charset="utf-8">
  107.     <meta http-equiv="content-language" content="ar">
  108.     <link rel="" href="{% static 'fonts/Raleway.css' %}">
  109.     <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
  110.     <style type="text/css">
  111.         @font-face {
  112.             font-family: 'TimesNewRoman', 'Lucida Grande', Verdana, Helvetica, Arial, sans-serif, Courier, 'serif', Tahoma, "DejaVu Sans";
  113.             /* src: url("D:/Django_Project/Projects/gitlab_django_clinic/myproject/static/fonts/RobotoRegular.ttf"); */
  114.             src: url("D:/Django_Project/Projects/gitlab_django_clinic/myproject/static/fonts/DejaVuSans.ttf");
  115.             /* src: url("D:/Django_Project/Projects/gitlab_django_clinic/myproject/static/fonts/Amiri-Bold.ttf"); */
  116.             /* src: url("D:/Django_Project/Projects/gitlab_django_clinic/myproject/static/fonts/roboto-regular.woff2") format('woff'); */
  117.             /* font-family: 'mywebfont'; */
  118.             /* src: url('adobe_regular.eot');
  119.             src: url('adobe_regular.eot?#iefix') format('embedded-opentype'), url('adobe_regular.woff') format('woff'), url('adobe_regular.ttf') format('truetype'), url('adobe_regular.svg#adobe_regular') format('svg'); */
  120.             /* font-weight: normal;
  121.             font-style: normal; */
  122.         }
  123.         /* html {
  124.             font-family: 'Droid Arabic Kufi', serif, Tahoma, "DejaVu Sans";
  125.             font-size: 100%;
  126.         } */
  127.        
  128.         body {
  129.             font-family: 'TimesNewRoman', 'Lucida Grande', Verdana, Helvetica, Arial, sans-serif, Courier, 'serif', Tahoma, "DejaVu Sans";
  130.             font-weight: 200;
  131.             font-size: 14px;
  132.             text-align: right;
  133.             /* unicode-bidi: bidi-override !important; */
  134.         }
  135.        
  136.         .header {
  137.             font-size: 20px;
  138.             font-weight: 100;
  139.             text-align: center;
  140.             color: #007cae;
  141.         }
  142.        
  143.         .title {
  144.             font-size: 22px;
  145.             font-weight: 100;
  146.             /* text-align: right;*/
  147.             padding: 10px 20px 0px 20px;
  148.         }
  149.        
  150.         .title span {
  151.             color: #007cae;
  152.         }
  153.        
  154.         .details {
  155.             padding: 10px 20px 0px 20px;
  156.             text-align: left !important;
  157.             /* text-align: left !important; */
  158.             /*margin-left: 40%;*/
  159.         }
  160.        
  161.         .hrItem {
  162.             border: none;
  163.             height: 1px;
  164.             /* Set the hr color */
  165.             color: #333;
  166.             /* old IE */
  167.             background-color: #fff;
  168.             /* Modern Browsers */
  169.         }
  170.     </style>
  171.     <button>Print Me</button>
  172. </head>
  173.  
  174. <body>
  175.     <button>Print Me</button>
  176.     <!-- <div dir="auto" style="text-align:left">اى حاجة عشان اعرف</div> -->
  177.     <div class='wrapper' dir="rtl" lang="ar">
  178.         <div class='header' dir="auto">
  179.             <p class='title' dir="auto">الروشتة</p>
  180.         </div>
  181.         <!-- {% comment %}
  182.         <div> {% endcomment %} -->
  183.         <div class='details' dir="auto">
  184.             <hr class='hrItem' /> {% for format in table.export_formats %}
  185.             <a href="{% querystring '_export'=format %}">
  186.                     download <code>.{{ format }}</code>
  187.             </a> {% endfor %}
  188.             <!--  -->
  189.             Visit No: {{ visit_no }}<br /> Name: {{ name }}<br /> Visit Date: {{ date }}
  190.             <!-- {% now "Y-m-d" %} -->
  191.             <!-- {% comment %} {% querystring '_export'=format %} {% endcomment %} {% comment %} {{billtable}} {% endcomment %} -->
  192.             <table class="fl-table" id="table">
  193.                 <!-- class="fl-table" -->
  194.                 <thead>
  195.                     <!-- <tr>
  196.                         <th>Drug</th>
  197.                         <th>Plan</th>
  198.                     </tr> -->
  199.                 </thead>
  200.                 {% for cl in qs %}
  201.                 <tbody>
  202.                     <tr dir="auto" style="text-align: center;">
  203.                         <!-- <td>{{cl.id}}</td> -->
  204.                         <!-- <td>{{cl.recieveDate}}</td> -->
  205.                         <td>{{cl.name}}</td>
  206.                         <td>{{cl.plan}}</td>
  207.                     </tr>
  208.                 </tbody>
  209.                 {% endfor %}
  210.             </table>
  211.         </div>
  212.     </div>
  213. </body>
  214.  
  215. </html>
  216.  
  217.  
  218.  
  219.  
  220.  
  221.  
Add Comment
Please, Sign In to add comment