from django.contrib import admin, messages
from django.urls import path
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from django.utils.html import format_html

# Register your models here.
#from django.contrib.auth.models import User
from users.models import CustomUser
from import_export.admin import ImportExportMixin, ImportExportModelAdmin, ImportExportActionModelAdmin
from import_export import resources
from .models import Curso, Alumno, Responsable, Miembro
from .forms import AlumnoChangeListForm
from django.contrib.admin.views.main import ChangeList

from django.http import HttpResponse
from reportlab.pdfgen import canvas
from reportlab.platypus import Image
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import defaultPageSize
from reportlab.lib.colors import red, black,white, blue ,lightcoral
from reportlab.graphics.barcode import *
from reportlab.graphics.barcode import code128
from reportlab.graphics.barcode.common import Codabar
from reportlab.graphics.barcode.code128 import *
from reportlab.graphics.shapes import Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.units import mm
from datetime import date
from reportlab.lib.pagesizes import letter, A4, landscape
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFontFamily

from django.core.mail import send_mail
from subprocess import Popen, PIPE

from import_export import resources
from import_export.admin import ImportExportModelAdmin

from textwrap import wrap
import os

import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders
import re
from unicodedata import normalize
from django.shortcuts import get_object_or_404


# from email.MIMEBase import MIMEBase
# from email.MIMEText import MIMEText
# from email.Utils import COMMASPACE, formatdate
# from email import Encoders
brushFile = "/home/cmsforg/djangox/static/fonts/brush_script_mt_kursiv.ttf"
pdfmetrics.registerFont(TTFont("brush_cursiva", brushFile))

lucidaFile = "/home/cmsforg/djangox/static/fonts/lucida_bold.ttf"
pdfmetrics.registerFont(TTFont("lucida_negrita", lucidaFile))

baskervilleFile = "/home/cmsforg/djangox/static/fonts/BaskervilleItalicBT.ttf"
pdfmetrics.registerFont(TTFont("baske_negrita", baskervilleFile))

vivaldiFile = "/home/cmsforg/djangox/static/fonts/VIVALDII.TTF"
pdfmetrics.registerFont(TTFont("vivaldi", vivaldiFile))

baskerville_normal_File = "/home/cmsforg/djangox/static/fonts/BASKVILL.ttf"
pdfmetrics.registerFont(TTFont("baske_normal", baskerville_normal_File))

libre_franklin_File = "/home/cmsforg/djangox/static/fonts/LibreFranklin-Light.ttf"
pdfmetrics.registerFont(TTFont("libre_franklin_light", libre_franklin_File))

libre_franklin_File_2 = "/home/cmsforg/djangox/static/fonts/LibreFranklin-Bold.ttf"
pdfmetrics.registerFont(TTFont("libre_franklin_bold", libre_franklin_File_2))

PAGE_WIDTH, PAGE_HEIGHT = A4
class CustomUserResource(resources.ModelResource):
    class Meta:
        model = CustomUser
        fields = ('id', 'email', 'username', 'first_name', 'last_name', 'password', 'is_superuser', 'is_staff', 'is_active', 'date_joined')
        # widgets = {
        #         'published': {'format': '%d.%m.%Y'},
        #         }

class AlumnoResource(resources.ModelResource):
    class Meta:
        model = Alumno
        import_id_fields = ['id_alumno','nro_doc']
        fields = ('id_alumno', 'nro_doc')

        # widgets = {
        #         'published': {'format': '%d.%m.%Y'},
        #         }
    def get_instance(self, instance_loader, row):
        try:
            params = {}
            for key in instance_loader.resource.get_import_id_fields():
                field = instance_loader.resource.fields[key]
                params[field.attribute] = field.clean(row)
            return self.get_queryset().get(**params)
        except Exception:
            return None

class MiembroResource(resources.ModelResource):
    class Meta:
        model = Miembro
        #import_id_fields = ['alumno', 'curso', 'enviar_mail', 'rol']
        fields = ('id', 'date_joined','alumno', 'curso', 'rol', 'enviar_mail')
        # widgets = {
        #         'published': {'format': '%d.%m.%Y'},
        #         }
    def get_instance(self, instance_loader, row):
        try:
            params = {}
            for key in instance_loader.resource.get_import_id_fields():
                field = instance_loader.resource.fields[key]
                params[field.attribute] = field.clean(row)
            return self.get_queryset().get(**params)
        except Exception:
            return None



class CustorUserInline(admin.StackedInline):
    model = CustomUser
    extra = 1


class AlumnoInline(admin.TabularInline):
    model = Alumno.cursos.through

class ResponsableInline(admin.TabularInline):
    model = Responsable.cursos.through


class CursoAdmin(admin.ModelAdmin):
    list_display = ('id_curso','nombre','anio','leyenda_1', 'leyenda_2', 'leyenda_3','tipo')    
    # list_filter = ('profesional',)    
    list_editable = ('nombre','anio','leyenda_1', 'leyenda_2', 'leyenda_3')    
    #inlines = [ResponsableInline, AlumnoInline,]
    inlines = [ResponsableInline,]
    search_fields = ['id_curso']
    search_fields = ('id_curso','nombre', 'tipo')
    list_filter = ('anio', 'tipo')
    actions = [
        'accion_validar_curso',
        'accion_duplicar_curso',
    ]
    def accion_validar_curso(self, request, queryset):
        for curso in queryset:
            errores = []

            if not curso.leyenda_1:
                errores.append("Falta leyenda_1")

            responsables = Responsable.objects.filter(cursos=curso.id_curso)
            for r in responsables:
                if not r.imagen_firma:
                    errores.append(f"{r.nombre} {r.apellido} sin firma")

            if errores:
                messages.warning(
                    request,
                    f'Curso "{curso.nombre}": ' + " | ".join(errores)
                )
            else:
                messages.success(
                    request,
                    f'Curso "{curso.nombre}": OK'
                )

    accion_validar_curso.short_description = "Validar curso (firmas y textos)"

    def accion_duplicar_curso(self, request, queryset):
        for curso in queryset:
            curso.pk = None
            curso.nombre = f"{curso.nombre} (COPIA)"
            curso.save()

        messages.success(request, "Curso duplicado correctamente")

    accion_duplicar_curso.short_description = "Duplicar curso"
    readonly_fields = getattr(admin.ModelAdmin, "readonly_fields", tuple()) + ("preview_pdf",)

    def preview_pdf(self, obj):
        if not obj:
            return "-"
        default_dni = "30196554"
        # OJO: desde /change/ hay que subir un nivel para ir a /<id>/preview-pdf/
        return format_html(
            '<a class="button" href="../preview-pdf/?dni={}" target="_blank">Previsualizar PDF</a>',
            default_dni
        )
    preview_pdf.short_description = "PDF Preview"

    def get_urls(self):
        urls = super().get_urls()
        custom = [
            # ✅ esto genera /admin/diplomas/curso/<id>/preview-pdf/
            path(
                "<int:object_id>/preview-pdf/",
                self.admin_site.admin_view(self.preview_pdf_view),
                name="curso_preview_pdf",
            ),
        ]
        return custom + urls

    def preview_pdf_view(self, request, object_id):
        dni = request.GET.get("dni") or ""
        dni = "".join(c for c in str(dni) if c.isdigit())

        if not dni:
            messages.error(request, "DNI inválido para previsualizar.")
            return HttpResponseRedirect(request.META.get("HTTP_REFERER", "../"))

        # 🔹 Buscar alumno por DNI (SEGÚN TU MODELO REAL)
        alumno = get_object_or_404(Alumno, nro_doc=dni)

        # 🔹 Validar que sea miembro del curso
        if not Miembro.objects.filter(curso_id=object_id, alumno=alumno).exists():
            messages.error(
                request,
                "El DNI ingresado no figura como alumno del curso."
            )
            return HttpResponseRedirect(request.META.get("HTTP_REFERER", "../"))

        # 🔹 Redirigir usando alumno_id REAL (NO DNI)
        return HttpResponseRedirect(
            f"/aplicaciones/diplomas/pdf/{object_id}/{alumno.id_alumno_id}/"
        )

class AlumnoAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    list_display = ('id_alumno','nro_doc', )
    fields = ('id_alumno','nro_doc',)
    resource_class = AlumnoResource
    search_fields = ('id_alumno__last_name','nro_doc',)

    inlines = [AlumnoInline]

    ordering =['id_alumno__last_name']
    autocomplete_fields = ['id_alumno', 'cursos']
    # list_filter = ('profesional',)    
    #list_editable = ('apellido','nombre','nro_doc')

    # def get_cursos(self, obj):
    #     return "\n".join([p.nombre for p in obj.cursos.all()])

    # def get_id_cursos(self, obj):

    #     return "\n".join([str(p.id_curso) for p in obj.cursos.all()])

    

class ResponsableAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    list_display = ('apellido','nombre','nro_doc','cargo','cargo_2')    
    # list_filter = ('profesional',)    
    #list_editable = ('apellido','nombre','nro_doc','cargo','cargo_2')    

class MiembroAdmin(ImportExportModelAdmin, admin.ModelAdmin):
    """docstring for MiembroAdmin"""
    list_display = ('alumno_id','get_alumno','get_email','rol','curso_id', 'get_curso','generado', 'date_joined', 'enviar_mail')
    list_editable =['enviar_mail']

    actions = ['generarDiploma']
    list_filter = ['curso__anio', 'curso_id']
    search_fields = ['alumno__nro_doc', 'alumno__id_alumno__last_name', 'curso__nombre']
    ordering =['alumno__id_alumno__last_name']
    resource_class = MiembroResource
    autocomplete_fields = ['alumno', 'curso']
    def get_alumno(self, obj):
        alumno = CustomUser.objects.get(id__exact = obj.alumno_id)
        return alumno
    get_alumno.short_description = "Apellido y Nombres"
    def get_email(self, obj):
        alumno = CustomUser.objects.get(id__exact = obj.alumno_id)
        return alumno.email
    get_email.short_description = "Email"
    
    def get_curso(self, obj):
        curso = Curso.objects.get(id_curso__exact = obj.curso_id)
        return curso
    get_curso.short_description = "Curso"
    
    def generarDiploma(self, request, queryset):
        ''' funcion que genera los diplomas segun la seleccion'''
        
        '''
            parametros:
            ------------
            queryset: conjunto de datos de los miembros

            return:
            ------------
            Mensaje de generación de diploma y de envio de email
        '''


        global ancho
        global inicio
        ancho = 554
        inicio = 22
        print (PAGE_HEIGHT)
        print (PAGE_WIDTH)


#para web
        # for o in queryset:
        #     alumno = CustomUser.objects.get(id__exact = o.alumno_id)
        #     curso =  Curso.objects.get(id_curso__exact = o.curso_id)
        #     alumno_doc = Alumno.objects.get(id_alumno__exact = o.alumno_id)
        #     response = HttpResponse(content_type='application/pdf')
        #     response['Content-Disposition'] = 'filename="somefilename.pdf"'
        #     p = canvas.Canvas(response, pagesize=landscape(A4))
        #     p = self.cabecera(p)
        #     p = self.cuerpo(p, alumno, curso, alumno_doc, o)
        #     p = self.firmas(p, curso)
        #     #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        #     #p.setFont('Helvetica', 7)
        #     #p.setFillColor(red)
        #     #p.drawString(102, 530, 'SR. PROFESIONAL RECUERDE QUE EL ATRASO DE LAS CUOTAS OCASIONA LA ACTUALIZACION DE LAS MISMAS')
        #     #print (str(curso))
        #     filename = str(alumno.first_name) + '_' + str(alumno.last_name)+ '_'+ str(curso.nombre)

        #     response['Content-Disposition'] = 'attachment; filename=' + filename + '.pdf'
            
        #     p.setTitle(filename)
        #     p.showPage()
        #     p.save()
        #     return response

        for o in queryset:
            alumno = CustomUser.objects.get(id__exact = o.alumno_id)
            curso =  Curso.objects.get(id_curso__exact = o.curso_id)
            alumno_doc = Alumno.objects.get(id_alumno__exact = o.alumno_id)
            #miembro  = Miembro.objects.get(alumno__exact = o.alumno_id, curso =curso.id_curso )
            #response = HttpResponse(content_type='application/pdf')
            #response['Content-Disposition'] = 'filename="somefilename.pdf"'
            filename = str(alumno.first_name) + '_' + str(alumno.last_name)+ '_'+ str(curso.nombre)+'_' + str(o.rol) + '.pdf'
            curso_nombre = str(curso).replace(" ", "_")
            curso_nombre = curso_nombre + '_' + str(curso.anio)
            carpeta = '/home/cmsforg/djangox/static/pdfs/' + curso_nombre

            try:
                os.makedirs(carpeta)
            except OSError as e:
                if e.errno == 17:
                    # Dir already exists. No biggie.
                    pass
            
            path = carpeta + '/' + filename
            path = path.replace(" ", "_")

            p = canvas.Canvas(path, pagesize=landscape(A4))
            
            if curso.tipo == 'CURSO':

                if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA'):
                    p = self.cabecera(p)
                    p = self.cuerpo_coor(p, alumno, curso, alumno_doc, o )
                    p = self.firmas_coor(p, curso)
                else:
                    p = self.cabecera(p)
                    p = self.cuerpo(p, alumno, curso, alumno_doc, o)
                    p = self.firmas(p, curso)
                
            elif curso.tipo == 'WEBINARIO':
                p = self.cabecera_web(p)
                p = self.cuerpo_web(p, alumno, curso, alumno_doc, o)
                p = self.firmas_web(p, curso)
            elif curso.tipo == 'CAFÉ FILOSÓFICO':
                p = self.cabecera_caf(p)
                p = self.cuerpo_caf(p, alumno, curso, alumno_doc, o)
                p = self.firmas_caf(p, curso)
            elif curso.tipo == 'JORNADA':
                p = self.cabecera(p)
                p = self.cuerpo_jor(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
            elif curso.tipo == 'REVISTA':
                p = self.cabecera(p)
                p = self.cuerpo_rev(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
            elif curso.tipo == 'NOCHES CULTURALES': # Noches culturales
                p = self.cabecera_cul(p)
                p = self.cuerpo_cul(p, alumno, curso, alumno_doc, o)
                p = self.firmas_cul(p, curso)
            elif curso.tipo == 'CURSORED': # Noches culturales
                p = self.cabecera(p)
                p = self.cuerpo_red(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
            else: # ad-honoren
                p = self.cabecera(p)
                p = self.cuerpo_ad(p, alumno, curso, alumno_doc, o)
                p = self.firmas_coor(p, curso)

            p.setTitle(filename)
            p.showPage()
            p.save()
            o.generado = True
            o.save()
            if o.enviar_mail == True:
                self.enviar_mail(p, curso, alumno, path, filename)
                message_bit = "1 Diploma/Certificado enviado"
                self.message_user(request, "%s correctamente." % message_bit)

        if queryset.count() == 1:
            message_bit = "1 Diploma/Certificado generado"
        else:
            message_bit = "%s Diplomas/Certificados generados" % queryset.count() 
        self.message_user(request, "%s correctamente." % message_bit)

            #return path

            #print(o.curso_id)
    def cabecera(self, p):
        ''' funcion que genera la cabecera del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('brush_cursiva', 60)
        titulo_colegio = 'Colegio de Médicos'
        titulo_colegio_width = stringWidth(titulo_colegio, 'brush_cursiva', 60)
        p.drawString((PAGE_HEIGHT - titulo_colegio_width)/2.0, 500, titulo_colegio)
        

        p.setFont('lucida_negrita', 12)
        segundo_texto = 'DE LA PROVINCIA DE SANTA FE'
        segundo_texto_width = stringWidth(segundo_texto, 'lucida_negrita', 12)
        p.drawString((PAGE_HEIGHT- segundo_texto_width)/2.0, 475, segundo_texto)

        tercer_texto = '1° CIRCUNSCRIPCIÓN - LEY 3950'
        tercer_texto_width = stringWidth(tercer_texto, 'lucida_negrita', 12)

        p.drawString((PAGE_HEIGHT - tercer_texto_width)/2.0, 460, tercer_texto)


        logo_col_path='/home/cmsforg/djangox/static/images/logo_colegio_web.jpg'
        logo_prov_path='/home/cmsforg/djangox/static/images/Escudo_de_Santa_Fe.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 30, 400, width=150, height=150)
        p.drawImage(logo_prov_path, 676, 385, width=115, height=165)
        p.drawImage(logo_fondo_path, 1, 1, width=460, height=60)
        
        return p

    def cuerpo(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
        nombre_y_apellido =alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        p.setFont('vivaldi', 44)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")
        leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' en el'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
        p.setFont('baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

        p.setFont('baske_normal', 18)
        leyenda_2 ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
        leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
        p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

        p.setFont('baske_negrita', 18)
        leyenda_3 = curso.leyenda_2
        if leyenda_3 != None:
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

        leyenda_5 = curso.leyenda_4
        if leyenda_5 != None:
            p.setFont('baske_negrita', 18)
            leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT-leyenda_5_width)/2.0 , 244, leyenda_5)

        leyenda_4 = curso.leyenda_3
        if leyenda_4 != None:    
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 208, leyenda_4)

        

        return p

    def cuerpo_red(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 28)
        primera_linea = 'Certificado de Aprobación'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 28)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
        nombre_y_apellido =alumno.first_name + ' ' + alumno.last_name        
        #nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        #p.setFont('vivaldi', 44)
        #p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")
        leyenda_1 = curso.leyenda_1 +' ' + nombre_y_apellido +', D.N.I. N°:'+ dni_+', ' + curso.leyenda_2
        #leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' en el'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 20)
        p.setFont('baske_negrita', 20)
        p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 340, leyenda_1)

        p.setFont('baske_normal', 20)
        curso_nombre ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
        curso_nombre_width = stringWidth(curso_nombre, 'baske_normal', 20)
        p.drawString((PAGE_HEIGHT - curso_nombre_width )/2.0 , 315, curso_nombre)

        p.setFont('baske_negrita', 20)
        leyenda_3 = curso.leyenda_3
        if leyenda_3 != None:
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 290, leyenda_3)

        

        leyenda_4 = curso.leyenda_4
        if leyenda_4 != None:
            p.setFont('baske_negrita', 20)
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT-leyenda_4_width)/2.0 , 265, leyenda_4)

        leyenda_5 = curso.leyenda_5
        if leyenda_5 != None:    
            leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 208, leyenda_5)

        

        return p
    def cuerpo_rev(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
        nombre_y_apellido =alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        p.setFont('vivaldi', 44)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")
        leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' del Artículo'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
        p.setFont('baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

        # p.setFont('baske_normal', 18)
        # leyenda_2 ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
        # leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
        # p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

        p.setFont('baske_normal', 18)
        leyenda_2 =curso.leyenda_2
        leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
        p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

        # p.setFont('baske_negrita', 18)
        # leyenda_3 = curso.leyenda_3
        # if leyenda_3 != None:
        #     leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
        #     p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

        leyenda_4 = curso.leyenda_4
        if leyenda_4 != None:
            #p.setFont('baske_negrita', 18)
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT-leyenda_4_width)/2.0 , 266, leyenda_4)

        leyenda_5 = curso.leyenda_5
        if leyenda_5 != None:    
            leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_5_width)/2.0, 244, leyenda_5)

        leyenda_6 = curso.leyenda_6
        if leyenda_6 != None:
            p.setFont('baske_negrita', 18)
            leyenda_6_width = stringWidth(leyenda_6, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT -leyenda_6_width )/2.0 , 222, leyenda_6)

        leyenda_7 = curso.leyenda_7
        if leyenda_7 != None:    
            leyenda_7_width = stringWidth(leyenda_7, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 186, leyenda_7)
        

        return p

    def cuerpo_jor(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
        nombre_y_apellido =alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        p.setFont('vivaldi', 44)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")
        leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' en la'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
        p.setFont('baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

        p.setFont('baske_normal', 18)
        leyenda_2 ='"'+ curso.nombre +  '"' 
        leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
        p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

        p.setFont('baske_negrita', 18)
        leyenda_3 = curso.leyenda_2
        if leyenda_3 != None:
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

        leyenda_4 = curso.leyenda_3
        if leyenda_4 != None:    
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT- leyenda_4_width)/2.0 , 244, leyenda_4)

        leyenda_5 = curso.leyenda_4
        if leyenda_5 != None:    
            leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT- leyenda_5_width)-20 , 206, leyenda_5)

        leyenda_6 = curso.leyenda_5
        if leyenda_6 != None:    
            leyenda_6_width = stringWidth(leyenda_6, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT- leyenda_6_width)/2.0 , 196, leyenda_6)
        return p

    def cuerpo_coor(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        

        if (curso.leyenda_4 != None and curso.leyenda_5 !=None and o.rol == 'COORDINADOR'):
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido) #Nombre y apellido
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ','
            leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1) #dni y nombre del curso


            p.setFont('baske_negrita', 18)
            if curso.leyenda_2 != None:
                leyenda_2 = curso.leyenda_2
                leyenda_2_width = stringWidth(leyenda_2, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

            if curso.leyenda_3 != None:
                leyenda_3 = curso.leyenda_3
                leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 244, leyenda_nombre_curso)

            if curso.leyenda_4 != None:
                p.setFont('baske_negrita', 18)
                leyenda_4 = curso.leyenda_4
                leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_4_width )/2.0 , 222, leyenda_4)
            #if curso.leyenda_5 != None:
            #    leyenda_5 = curso.leyenda_5
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            #p.drawString((PAGE_HEIGHT)/2.0 + 160 , 190, leyenda_5)
        elif o.rol == 'DISERTANTE':
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            diser = o.rol
            leyenda_disertante_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_disertante_1 + ' ' + o.rol + ' del  '
            leyenda_disertante_1_width = stringWidth(leyenda_disertante_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_disertante_1_width )/2.0 , 310, leyenda_disertante_1)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            #leyenda_nombre_curso ='““13er. CURSO ANUAL  sobre CLINICA Y TRATAMIENTO EN DIABETES TIPO 2”  ” ' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 288, leyenda_nombre_curso)

            if curso.leyenda_disertante_2 != None:
                p.setFont('baske_negrita', 18)
                leyenda_disertante_2 = curso.leyenda_disertante_2
                leyenda_disertante_2width = stringWidth(leyenda_disertante_2, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_disertante_2width )/2.0 , 266, leyenda_disertante_2)

            if curso.leyenda_disertante_3 != None:
                p.setFont('baske_negrita', 14)
                leyenda_disertante_3 = curso.leyenda_disertante_3
                leyenda_disertante_3_width = stringWidth(leyenda_disertante_3, 'baske_negrita', 14)
                p.drawString((PAGE_HEIGHT - leyenda_disertante_3_width )/2.0 , 244, leyenda_disertante_3)
                # leyenda_horas_bomberos ='con 8 (ocho) hs. de carga horaria práctica.'
                # leyenda_horas_bomberos_width= stringWidth(leyenda_horas_bomberos, 'baske_negrita', 18)
                # p.drawString((PAGE_HEIGHT - leyenda_horas_bomberos_width )/2.0 , 222, leyenda_horas_bomberos)
            if curso.leyenda_disertante_4 != None:
                p.setFont('baske_normal', 12)
                leyenda_disertante_4 = curso.leyenda_disertante_4
                leyenda_disertante_5 = curso.leyenda_disertante_5
                leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 14)
                #p.drawString((PAGE_HEIGHT - leyenda_disertante_4_width )/2.0 , 223, leyenda_disertante_4)
                tema = leyenda_disertante_5
                tema_width = stringWidth(tema, 'baske_negrita', 12)
                leyenda_disertante_5_width = stringWidth(leyenda_disertante_5, 'baske_negrita', 12)
                leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 12)
                p.drawString((PAGE_HEIGHT )/2.0-310 , 220, leyenda_disertante_4)
                p.setFont('baske_normal', 12)
                p.drawString((PAGE_HEIGHT )/2.0-310 , 205, tema)
                p.rect((PAGE_HEIGHT )/2.0-315 , 195, leyenda_disertante_5_width + 5, 40, stroke=1, fill=0)
            
            p.setFont('baske_negrita', 14)
            leyenda_5 = curso.leyenda_5
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 +200, 178, leyenda_5)
            #p.drawString((PAGE_HEIGHT)/2.0 + 160 , 196, leyenda_3)
        elif (o.rol == 'DIRECTOR' or o.rol == 'DIRECTORA'):
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            leyenda_disertante_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_disertante_1 + ' ' + o.rol + ' en el '
            leyenda_disertante_1_width = stringWidth(leyenda_disertante_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_disertante_1_width )/2.0 , 310, leyenda_disertante_1)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 288, leyenda_nombre_curso)
            
            if curso.leyenda_director_1 != None:
                p.setFont('baske_negrita', 14)
                leyenda_director_1 = curso.leyenda_director_1
                leyenda_director_1_width = stringWidth(leyenda_director_1, 'baske_negrita', 14)
                p.drawString((PAGE_HEIGHT - leyenda_director_1_width )/2.0 , 266, leyenda_director_1)

            


            # p.setFont('baske_negrita', 12)
            # leyenda_disertante_4 = curso.leyenda_disertante_4
            # leyenda_disertante_5 = curso.leyenda_disertante_5

            # tema = leyenda_disertante_5
            # tema_width = stringWidth(tema, 'baske_negrita', 12)
            # leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 14)
            # p.drawString((PAGE_HEIGHT )/2.0-310 , 220, leyenda_disertante_4)
            # p.setFont('baske_normal', 12)
            # p.drawString((PAGE_HEIGHT )/2.0-310 , 205, tema)
            # p.rect((PAGE_HEIGHT )/2.0-315 , 195, leyenda_disertante_4_width + 5, 40, stroke=1, fill=0)
            
            p.setFont('baske_negrita', 14)
            leyenda_3 = curso.leyenda_3
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 190, leyenda_3)

        else:
            p.setFillColor(black)
            p.setStrokeColor(black)
            p.setFont('baske_negrita', 18)
            primera_linea = ''
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' en el'
            leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

            p.setFont('baske_normal', 18)
            leyenda_2 ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

            p.setFont('baske_negrita', 18)
            leyenda_3 = curso.leyenda_2
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

            if curso.leyenda_3 != None:
                leyenda_4 = curso.leyenda_3
                leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT)/2.0 + 160 , 188, leyenda_4)
            if curso.leyenda_4 != None:
                leyenda_5 = curso.leyenda_4
                leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_5_width)/2.0 , 244, leyenda_5)
        return p
    def cuerpo_ad(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        

        if (curso.leyenda_4 != None and curso.leyenda_5 !=None and o.rol == 'COORDINADOR'):
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido) #Nombre y apellido
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            #leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ','
            leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1
            leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1) #dni y nombre del curso


            p.setFont('baske_negrita', 18)
            if curso.leyenda_2 != None:
                leyenda_2 = curso.leyenda_2
                leyenda_2_width = stringWidth(leyenda_2, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

            if curso.leyenda_3 != None:
                leyenda_3 = curso.leyenda_3
                leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 244, leyenda_nombre_curso)

            if curso.leyenda_4 != None:
                p.setFont('baske_negrita', 18)
                leyenda_4 = curso.leyenda_4
                leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_4_width )/2.0 , 222, leyenda_4)
            #if curso.leyenda_5 != None:
            #    leyenda_5 = curso.leyenda_5
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            #p.drawString((PAGE_HEIGHT)/2.0 + 160 , 190, leyenda_5)
        elif o.rol == 'DISERTANTE':
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            diser = o.rol
            leyenda_disertante_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_disertante_1 + ' ' + o.rol + ' del  '
            leyenda_disertante_1_width = stringWidth(leyenda_disertante_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_disertante_1_width )/2.0 , 310, leyenda_disertante_1)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            #leyenda_nombre_curso ='““13er. CURSO ANUAL  sobre CLINICA Y TRATAMIENTO EN DIABETES TIPO 2”  ” ' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 288, leyenda_nombre_curso)

            if curso.leyenda_disertante_2 != None:
                p.setFont('baske_negrita', 18)
                leyenda_disertante_2 = curso.leyenda_disertante_2
                leyenda_disertante_2width = stringWidth(leyenda_disertante_2, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_disertante_2width )/2.0 , 266, leyenda_disertante_2)

            if curso.leyenda_disertante_3 != None:
                p.setFont('baske_negrita', 14)
                leyenda_disertante_3 = curso.leyenda_disertante_3
                leyenda_disertante_3_width = stringWidth(leyenda_disertante_3, 'baske_negrita', 14)
                p.drawString((PAGE_HEIGHT - leyenda_disertante_3_width )/2.0 , 244, leyenda_disertante_3)
                # leyenda_horas_bomberos ='con 8 (ocho) hs. de carga horaria práctica.'
                # leyenda_horas_bomberos_width= stringWidth(leyenda_horas_bomberos, 'baske_negrita', 18)
                # p.drawString((PAGE_HEIGHT - leyenda_horas_bomberos_width )/2.0 , 222, leyenda_horas_bomberos)
            if curso.leyenda_disertante_4 != None:
                p.setFont('baske_normal', 12)
                leyenda_disertante_4 = curso.leyenda_disertante_4
                leyenda_disertante_5 = curso.leyenda_disertante_5
                leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 14)
                #p.drawString((PAGE_HEIGHT - leyenda_disertante_4_width )/2.0 , 223, leyenda_disertante_4)
                tema = leyenda_disertante_5
                tema_width = stringWidth(tema, 'baske_negrita', 12)
                leyenda_disertante_5_width = stringWidth(leyenda_disertante_5, 'baske_negrita', 12)
                leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 12)
                p.drawString((PAGE_HEIGHT )/2.0-310 , 220, leyenda_disertante_4)
                p.setFont('baske_normal', 12)
                p.drawString((PAGE_HEIGHT )/2.0-310 , 205, tema)
                p.rect((PAGE_HEIGHT )/2.0-315 , 195, leyenda_disertante_5_width + 5, 40, stroke=1, fill=0)
            
            p.setFont('baske_negrita', 14)
            leyenda_5 = curso.leyenda_5
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 +200, 178, leyenda_5)
            #p.drawString((PAGE_HEIGHT)/2.0 + 160 , 196, leyenda_3)
        elif (o.rol == 'DIRECTOR' or o.rol == 'DIRECTORA'):
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            leyenda_disertante_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_disertante_1 + ' ' + o.rol + ' en el '
            leyenda_disertante_1_width = stringWidth(leyenda_disertante_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_disertante_1_width )/2.0 , 310, leyenda_disertante_1)

            p.setFont('baske_normal', 18)
            leyenda_nombre_curso ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
            leyenda_nombre_curso_width = stringWidth(leyenda_nombre_curso, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_nombre_curso_width )/2.0 , 288, leyenda_nombre_curso)
            
            if curso.leyenda_director_1 != None:
                p.setFont('baske_negrita', 14)
                leyenda_director_1 = curso.leyenda_director_1
                leyenda_director_1_width = stringWidth(leyenda_director_1, 'baske_negrita', 14)
                p.drawString((PAGE_HEIGHT - leyenda_director_1_width )/2.0 , 266, leyenda_director_1)

            


            # p.setFont('baske_negrita', 12)
            # leyenda_disertante_4 = curso.leyenda_disertante_4
            # leyenda_disertante_5 = curso.leyenda_disertante_5

            # tema = leyenda_disertante_5
            # tema_width = stringWidth(tema, 'baske_negrita', 12)
            # leyenda_disertante_4_width = stringWidth(leyenda_disertante_4, 'baske_negrita', 14)
            # p.drawString((PAGE_HEIGHT )/2.0-310 , 220, leyenda_disertante_4)
            # p.setFont('baske_normal', 12)
            # p.drawString((PAGE_HEIGHT )/2.0-310 , 205, tema)
            # p.rect((PAGE_HEIGHT )/2.0-315 , 195, leyenda_disertante_4_width + 5, 40, stroke=1, fill=0)
            
            p.setFont('baske_negrita', 14)
            leyenda_3 = curso.leyenda_3
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 190, leyenda_3)

        else:
            p.setFillColor(black)
            p.setStrokeColor(black)
            p.setFont('baske_negrita', 18)
            primera_linea = ''
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
            nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
            nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
            p.setFont('vivaldi', 44)
            p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
            dni = int(alumno_doc.nro_doc)
            dni_ = '{:,d}'.format(dni).replace(",", ".")
            #leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' en el'
            leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1
            leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
            p.setFont('baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

            p.setFont('baske_normal', 18)
            leyenda_2 ='"'+ curso.nombre + '"' 
            leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
            p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

            p.setFont('baske_negrita', 18)
            leyenda_3 = curso.leyenda_2
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

            if curso.leyenda_3 != None:
                leyenda_4 = curso.leyenda_3
                leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT)/2.0 + 160 , 188, leyenda_4)
            if curso.leyenda_4 != None:
                leyenda_5 = curso.leyenda_4
                leyenda_5_width = stringWidth(leyenda_5, 'baske_negrita', 18)
                p.drawString((PAGE_HEIGHT - leyenda_5_width)/2.0 , 244, leyenda_5)
        return p

    def firmas_coor(self, p, curso):
        ''' funcion que genera las firmas del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso

            return:
            ------------
            p: objeto canvas
        '''
        responsable = reversed(Responsable.objects.filter(cursos = curso.id_curso))
        responsable_cantidad = Responsable.objects.filter(cursos = curso.id_curso).count()
        nuevo_width = PAGE_HEIGHT/responsable_cantidad
        cont = responsable_cantidad - 1
        offset = 0
        e = 0
        for o in responsable:
            
            firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
            print(firma)
            p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 56 +e, width=90, height=90)


            p.setFont('baske_negrita', 15)
            p.setFillColorRGB(0.4,0.5,0.3)
            base_firma = '________________________'
            base_firma_width = stringWidth(base_firma, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - base_firma_width )/2.0 , 90, base_firma)

            p.setFillColorRGB(0,0,0)
            primera_linea = o.cargo + ' ' + o.nombre + ' ' + o.apellido
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - primera_linea_width )/2.0 , 70, primera_linea)
            
            
            p.setFont('baske_negrita', 10)
            segunda_linea = o.cargo_2
            segunda_linea_width = stringWidth(segunda_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - segunda_linea_width )/2.0 , 55, segunda_linea)

            p.setFont('baske_negrita', 10)
            tercera_linea = o.cargo_3
            tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 43, tercera_linea)


            e=24
            offset = offset + nuevo_width+ nuevo_width
        return p

    def firmas(self, p, curso):
        ''' funcion que genera las firmas del pdf para los diplomas de cursos '''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso

            return:
            ------------
            p: objeto canvas
        '''
        responsable = reversed(Responsable.objects.filter(cursos = curso.id_curso))
        responsable_cantidad = Responsable.objects.filter(cursos = curso.id_curso).count()
        nuevo_width = PAGE_HEIGHT/responsable_cantidad
        cont = responsable_cantidad - 1
        offset = 4
        e = 0
        for o in responsable:
            
            if (curso.firma):
            
                if (str(o.imagen_firma)=='static/firmas/firma_alico_usada.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 83, width=90, height=90)
                elif(str(o.imagen_firma)=='static/firmas/firma_fabiano_fhaH1x2.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 62, width=90, height=90)
                elif(str(o.imagen_firma)=='static/firmas/firma_bastide.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 90, width=90, height=90)
                elif(str(o.imagen_firma)=='static/firmas/firma_rafel_usada.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 30, width=90, height=90)
                else:
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 40 - e, width=90, height=90)

            p.setFont('baske_negrita', 15)
            p.setFillColorRGB(0.4,0.5,0.3)
            base_firma = '_______________________'
            base_firma_width = stringWidth(base_firma, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - base_firma_width )/2.0 , 100, base_firma)

            p.setFillColorRGB(0,0,0)
            primera_linea = o.cargo + ' ' + o.nombre + ' ' + o.apellido
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - primera_linea_width )/2.0 , 80, primera_linea)
            
            
            p.setFont('baske_negrita', 10)
            if o.cargo_2 != None:
                segunda_linea = o.cargo_2
                segunda_linea_width = stringWidth(segunda_linea, 'baske_negrita', 10)
                p.drawString((nuevo_width + offset - segunda_linea_width )/2.0 , 65, segunda_linea)

            p.setFont('baske_negrita', 10)
            tercera_linea = o.cargo_3
            if tercera_linea != None:
                tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 10)
                p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 53, tercera_linea)

            e=19
            offset = offset + nuevo_width + nuevo_width 
            
        return p
    
    def cabecera_web(self, p):
        ''' funcion que genera la cabecera del pdf para los diplomas de webinarios'''
        
        '''
            parametros:
            ------------
            p: objeto pdf

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        margen_web = 190
        p.setFillColor(black)
        p.setStrokeColor(black)
        
        

        


        logo_col_path='/home/cmsforg/djangox/static/images/logo_colegio_web.jpg'
        logo_prov_path='/home/cmsforg/djangox/static/images/Escudo_de_Santa_Fe.jpg'
        logo_fondo_path_1='/home/cmsforg/djangox/static/images/fondo_web_1.png'
        logo_fondo_path_2='/home/cmsforg/djangox/static/images/fondo_web_2.png'
        #p.setFont('Helvetica', 16)
        
        p.drawImage(logo_fondo_path_1, 1, 1, width=49, height=279)
        p.drawImage(logo_fondo_path_2, 390, 1, width=451, height=708)
        p.drawImage(logo_col_path, 30, 460, width=90, height=90)
        p.drawImage(logo_prov_path, 720 - margen_web, 445, width=84, height=99)
        
        p.setFont('brush_cursiva', 60)
        titulo_colegio = 'Colegio de Médicos'
        titulo_colegio_width = stringWidth(titulo_colegio, 'brush_cursiva', 60)
        p.drawString((PAGE_HEIGHT - titulo_colegio_width - margen_web)/2.0, 500, titulo_colegio)
        
        p.setFont('lucida_negrita', 12)
        segundo_texto = 'DE LA PROVINCIA DE SANTA FE'
        segundo_texto_width = stringWidth(segundo_texto, 'lucida_negrita', 12)
        p.drawString((PAGE_HEIGHT- segundo_texto_width - margen_web)/2.0, 475, segundo_texto)

        tercer_texto = '1° CIRCUNSCRIPCIÓN - LEY 3950'
        tercer_texto_width = stringWidth(tercer_texto, 'lucida_negrita', 12)

        p.drawString((PAGE_HEIGHT - tercer_texto_width - margen_web)/2.0, 460, tercer_texto)


        return p

    def cuerpo_web(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de webinarios'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        margen_web = 180
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Confiere el presente certificado a'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width - margen_web)/2.0, 410, primera_linea)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")

        nro_doc = ', D.N.I. ' + str(dni_) + ";"
        nro_doc_width = stringWidth(nro_doc, 'baske_negrita', 18)

        nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 36)
        p.setFont('vivaldi', 36)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width - margen_web - nro_doc_width)/2.0 , 355, nombre_y_apellido)
        p.setFont('baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - nro_doc_width - margen_web + nombre_y_apellido_width )/2.0 , 355, nro_doc)

        p.setFont('baske_negrita', 18)
        
        leyenda_1_width = stringWidth(curso.leyenda_1, 'baske_negrita', 18)

        
        if (o.rol == "DISERTANTE"):
            leyenda_4_width =  stringWidth(curso.leyenda_4, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_4_width - margen_web)/2.0 , 330, curso.leyenda_4)
            leyenda_5_width =  stringWidth(curso.leyenda_5, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - leyenda_5_width - margen_web)/2.0 , 310, curso.leyenda_5)
        else:
            p.drawString((PAGE_HEIGHT - leyenda_1_width - margen_web )/2.0 , 330, curso.leyenda_1)
            p.setFont('baske_negrita', 18)
            tema = '"' + curso.nombre + '"' # muchos disertantes
            #tema = 'sobre el Tema: "' + curso.nombre + '"' # un disertante
            tema_width = stringWidth(tema, 'baske_negrita', 18)
            p.drawString((PAGE_HEIGHT - tema_width - margen_web )/2.0 , 310, tema)


        leyenda_1_bis_width = stringWidth(curso.leyenda_1_bis, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_1_bis_width - margen_web )/2.0 , 290, curso.leyenda_1_bis)


        leyenda_2_width = stringWidth(curso.leyenda_2, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_2_width - margen_web)/2.0 , 270, curso.leyenda_2)
        
        leyenda_3_width = stringWidth(curso.leyenda_3, 'baske_negrita', 13)
        p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_web)/2.0 + 160 , 230, curso.leyenda_3)


        return p

    def firmas_web(self, p, curso):
        ''' funcion que genera las firmas del pdf para los diplomas de webinarios'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso

            return:
            ------------
            p: objeto canvas
        '''
        responsable = reversed(Responsable.objects.filter(cursos = curso.id_curso))
        responsable_cantidad = Responsable.objects.filter(cursos = curso.id_curso).count()
        nuevo_width = PAGE_HEIGHT/responsable_cantidad
        cont = responsable_cantidad - 1
        offset = 20
        for o in responsable:
            
            firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
            p.drawImage(firma, (nuevo_width + offset - 70 )/2.0 , 97, width=70, height=70)


            p.setFont('baske_negrita', 12)
            p.setFillColorRGB(0.4,0.5,0.3)
            base_firma = '___________________'
            base_firma_width = stringWidth(base_firma, 'baske_negrita', 12)
            p.drawString((nuevo_width + offset - base_firma_width )/2.0 , 100, base_firma)

            p.setFillColorRGB(0,0,0)
            primera_linea = o.cargo + ' ' + o.nombre + ' ' + o.apellido
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 12)
            p.drawString((nuevo_width + offset - primera_linea_width )/2.0 , 80, primera_linea)
            
            
            p.setFont('baske_negrita', 9)
            segunda_linea = o.cargo_2
            segunda_linea_width = stringWidth(segunda_linea, 'baske_negrita', 9)
            p.drawString((nuevo_width + offset - segunda_linea_width )/2.0 , 65, segunda_linea)

            p.setFont('baske_negrita', 9)
            tercera_linea = o.cargo_3
            tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 9)
            p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 53, tercera_linea)



            offset = offset + nuevo_width + 80
        return p    
    def cabecera_caf(self, p):
        ''' funcion que genera la cabecera del pdf para los diplomas de cafe filosoficos'''
        
        '''
            parametros:
            ------------
            p: objeto pdf

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        margen_cafe = 250
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        logo_col_path='/home/cmsforg/djangox/static/images/logo_colegio_web.jpg'
        logo_prov_path='/home/cmsforg/djangox/static/images/Escudo_de_Santa_Fe.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/cafe_filosofico.jpg'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_fondo_path, 12, 10, width=500, height=544)
        p.drawImage(logo_col_path, 6 + margen_cafe, 460, width=90, height=90)
        p.drawImage(logo_prov_path, 742, 445, width=84, height=99)

        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('brush_cursiva', 60)
        titulo_colegio = 'Colegio de Médicos'
        titulo_colegio_width = stringWidth(titulo_colegio, 'brush_cursiva', 60)
        p.drawString((PAGE_HEIGHT - titulo_colegio_width + margen_cafe)/2.0, 500, titulo_colegio)
        

        p.setFont('lucida_negrita', 12)
        segundo_texto = 'DE LA PROVINCIA DE SANTA FE'
        segundo_texto_width = stringWidth(segundo_texto, 'lucida_negrita', 12)
        p.drawString((PAGE_HEIGHT- segundo_texto_width + margen_cafe)/2.0, 475, segundo_texto)

        tercer_texto = '1° CIRCUNSCRIPCIÓN - LEY 3950'
        tercer_texto_width = stringWidth(tercer_texto, 'lucida_negrita', 12)

        p.drawString((PAGE_HEIGHT - tercer_texto_width + margen_cafe)/2.0, 460, tercer_texto)



        
        
        return p

    def cuerpo_caf(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de cafe filosófico'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director


            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        #PAGE_HEIGHT = PAGE_HEIGHT - 300
        margen_cafe = 22
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 16)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 16)
        p.drawString((PAGE_HEIGHT - primera_linea_width - margen_cafe), 390, primera_linea)
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")

        nro_doc = ', D.N.I. ' + str(dni_)
        nro_doc_width = stringWidth(nro_doc, 'baske_negrita', 16)

        nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        p.setFont('vivaldi', 44)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width - margen_cafe - nro_doc_width) , 350, nombre_y_apellido)
        p.setFont('baske_negrita', 16)
        p.drawString((PAGE_HEIGHT - nro_doc_width - margen_cafe), 350, nro_doc)


        p.setStrokeColorRGB(0.113, 0.603, 0.470)

        p.line((PAGE_HEIGHT - nombre_y_apellido_width - margen_cafe - nro_doc_width), 345, (PAGE_HEIGHT - margen_cafe ), 345)

        p.setFillColorRGB(0,0,0)
        leyenda_1 =  'ha participado en calidad de ' + o.rol + ' del'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 14)
        p.setFont('baske_negrita', 14)
        p.drawString((PAGE_HEIGHT - leyenda_1_width - margen_cafe) , 310, leyenda_1)

        p.setFont('baske_normal', 14)
        leyenda_2 ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
        leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 14)
        p.drawString((PAGE_HEIGHT - leyenda_2_width - margen_cafe) , 288, leyenda_2)

        tema = 'Tema: "' + curso.leyenda_1 + '"'
        #tema = tema.replace('\n','<br />\n')
        tema_width = stringWidth(tema, 'baske_negrita', 14)
        p.drawString((PAGE_HEIGHT - tema_width - margen_cafe) , 266, tema)

        if curso.leyenda_1_bis is None:
            p.setFont('baske_negrita', 14)
            leyenda_3 = curso.leyenda_2
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_cafe) , 244, leyenda_3)

            leyenda_4 = curso.leyenda_3
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT - leyenda_4_width - margen_cafe) , 200, leyenda_4)
        else:
            tema_bis ='"' + curso.leyenda_1_bis + '"'
            tema_bis_width = stringWidth(tema_bis, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT - tema_bis_width - margen_cafe) , 244, tema_bis)

            p.setFont('baske_negrita', 14)
            leyenda_3 = curso.leyenda_2
            leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_cafe) , 222, leyenda_3)

            leyenda_4 = curso.leyenda_3
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 14)
            p.drawString((PAGE_HEIGHT - leyenda_4_width - margen_cafe) , 182, leyenda_4)

        return p

    def firmas_caf(self, p, curso):
        ''' funcion que genera las firmas del pdf para los diplomas de cafe filosofico'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso

            return:
            ------------
            p: objeto canvas'''
        margen_cafe = 44
        responsable = reversed(Responsable.objects.filter(cursos = curso.id_curso))
        responsable_cantidad = Responsable.objects.filter(cursos = curso.id_curso).count()
        #print (responsable_cantidad)
        nuevo_width = PAGE_HEIGHT/responsable_cantidad
        cont = responsable_cantidad - 1
        offset = 674
        for o in responsable:
            
            firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
            p.drawImage(firma, (nuevo_width + offset - 70 )/2.0 , 87, width=70, height=70)


            p.setFont('baske_negrita', 13)
            p.setFillColorRGB(0.113, 0.603, 0.470)
            base_firma = '___________________'
            base_firma_width = stringWidth(base_firma, 'baske_negrita', 13)
            p.drawString((nuevo_width + offset - base_firma_width )/2.0 , 90, base_firma)

            p.setFillColorRGB(0,0,0)
            primera_linea = o.cargo + ' ' + o.nombre + ' ' + o.apellido
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 13)
            p.drawString((nuevo_width + offset - primera_linea_width )/2.0 , 70, primera_linea)
            
            
            p.setFont('baske_negrita', 10)
            segunda_linea = o.cargo_2
            segunda_linea_width = stringWidth(segunda_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - segunda_linea_width )/2.0 , 55, segunda_linea)

            p.setFont('baske_negrita', 10)
            tercera_linea = o.cargo_3
            tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 43, tercera_linea)



            offset = offset + nuevo_width
        return p

    def cabecera_cul(self, p):
        ''' funcion que genera la cabecera del pdf para los diplomas de noches culturales'''
        
        '''
            parametros:
            ------------
            p: objeto pdf

            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('brush_cursiva', 60)
        titulo_colegio = 'Colegio de Médicos'
        titulo_colegio_width = stringWidth(titulo_colegio, 'brush_cursiva', 60)
        p.drawString((PAGE_HEIGHT - titulo_colegio_width)/2.0, 500, titulo_colegio)
        

        p.setFont('lucida_negrita', 12)
        segundo_texto = 'DE LA PROVINCIA DE SANTA FE'
        segundo_texto_width = stringWidth(segundo_texto, 'lucida_negrita', 12)
        p.drawString((PAGE_HEIGHT- segundo_texto_width)/2.0, 475, segundo_texto)

        tercer_texto = '1° CIRCUNSCRIPCIÓN - LEY 3950'
        tercer_texto_width = stringWidth(tercer_texto, 'lucida_negrita', 12)

        p.drawString((PAGE_HEIGHT - tercer_texto_width)/2.0, 460, tercer_texto)


        logo_col_path='/home/cmsforg/djangox/static/images/logo_colegio_web.jpg'
        logo_prov_path='/home/cmsforg/djangox/static/images/Escudo_de_Santa_Fe.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 30, 400, width=150, height=150)
        p.drawImage(logo_prov_path, 676, 385, width=115, height=165)
        p.drawImage(logo_fondo_path, 1, 1, width=460, height=60)
        
        return p

    def cuerpo_cul(self, p, alumno, curso, alumno_doc, o):
        ''' funcion que genera el cuerpo del pdf para los diplomas de noches culturales'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            alumno: datos del alumno
            curso: datos del curso
            alumno_doc = número de documento del alumno
            o = rol del miembro asistente, disertante, director


            return:
            ------------
            p: objeto pdf con la cabecera
        '''
        
        #p.roundRect(inicio, 526, ancho, 100, 4, stroke=1, fill=0)
        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont('baske_negrita', 18)
        primera_linea = 'Certifica que'
        primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - primera_linea_width)/2.0, 390, primera_linea)
        
        nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'vivaldi', 44)
        p.setFont('vivaldi', 44)
        p.drawString((PAGE_HEIGHT - nombre_y_apellido_width )/2.0 , 350, nombre_y_apellido)
        
        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")

        leyenda_1 = 'D.N.I. ' + str(dni_) +', ' + curso.leyenda_1 + ' ' + o.rol + ' del'
        leyenda_1_width = stringWidth(leyenda_1, 'baske_negrita', 18)
        p.setFont('baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_1_width )/2.0 , 310, leyenda_1)

        p.setFont('baske_normal', 18)
        leyenda_2 ='"'+ curso.nombre + ' - ' + str(curso.anio) + '"' 
        leyenda_2_width = stringWidth(leyenda_2, 'baske_normal', 18)
        p.drawString((PAGE_HEIGHT - leyenda_2_width )/2.0 , 288, leyenda_2)

        p.setFont('baske_negrita', 18)
        leyenda_3 = curso.leyenda_2
        leyenda_3_width = stringWidth(leyenda_3, 'baske_negrita', 18)
        p.drawString((PAGE_HEIGHT - leyenda_3_width )/2.0 , 266, leyenda_3)

        leyenda_4 = curso.leyenda_3
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
        p.drawString((PAGE_HEIGHT)/2.0 + 160 , 222, leyenda_4)

        return p

    def firmas_cul(self, p, curso):
        ''' funcion que genera las firmas del pdf para los diplomas de noches culturales'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso

            return:
            ------------
            p: objeto canvas'''

        responsable = reversed(Responsable.objects.filter(cursos = curso.id_curso))
        responsable_cantidad = Responsable.objects.filter(cursos = curso.id_curso).count()
        #print (responsable_cantidad)
        nuevo_width = PAGE_HEIGHT/responsable_cantidad
        cont = responsable_cantidad - 1
        offset = 0
        for o in responsable:
            
            firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
            p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 97, width=90, height=90)


            p.setFont('baske_negrita', 15)
            p.setFillColorRGB(0.4,0.5,0.3)
            base_firma = '________________________'
            base_firma_width = stringWidth(base_firma, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - base_firma_width )/2.0 , 100, base_firma)

            p.setFillColorRGB(0,0,0)
            primera_linea = o.cargo + ' ' + o.nombre + ' ' + o.apellido
            primera_linea_width = stringWidth(primera_linea, 'baske_negrita', 15)
            p.drawString((nuevo_width + offset - primera_linea_width )/2.0 , 80, primera_linea)
            
            
            p.setFont('baske_negrita', 10)
            segunda_linea = o.cargo_2
            segunda_linea_width = stringWidth(segunda_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - segunda_linea_width )/2.0 , 65, segunda_linea)

            p.setFont('baske_negrita', 10)
            tercera_linea = o.cargo_3
            tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 10)
            p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 53, tercera_linea)



            offset = offset + nuevo_width+ nuevo_width
        return p


    def enviar_mail(self, p, curso, alumno, path, filename):
        ''' funcion que guarda el diploma en pdf en el path y opcionalmente enviar un mail al alumno con el diploma adjunto'''
        
        '''
            parametros:
            ------------
            p: objeto pdf
            curso: datos del curso
            alumno: datos del alumno
            path: destino donde se almacenan los diplomas

            return:
            ------------
            p: objeto canvas'''

        email = str(alumno.email)

        if curso.tipo == "WEBINARIO":

            #encabezado = "Colegio de Médicos - Certificado - " +curso.tipo.capitalize() + " - " +curso.nombre
            encabezado = "Colegio de Médicos - Certificado - " +curso.tipo.capitalize() + " - " +curso.nombre
            anio = str(curso.anio)
            contenido = "Estimado " + alumno.first_name + ' ' + alumno.last_name + "\nLe enviamos el certificado del "+ curso.tipo +" " + curso.nombre +"\n Si tiene inconvenientes para descargar el archivo, envie un correo a informatica@cmsf.org.ar \nPor favor confirmar recepción\nSaludos Cordiales. \nColegio de Médicos de Santa Fe - 1era Circunscripción"
            #contenido = " Estimado " + alumno.first_name + ' ' + alumno.last_name + "\nLe enviamos el diploma de  " + curso.nombre  +" \n Se envía también el link a la presentación en PDF: http://colmedicosantafe1.org.ar/images/webinario_dengue.pdf\nPor favor confirmar recepción\nSaludos Cordiales. \nColegio de Médicos de Santa Fe - 1era Circunscripción"        
        else:
            #encabezado = "Colegio de Médicos - Certificado - " +curso.tipo + " - " +curso.nombre
            encabezado = "Colegio de Médicos - Diploma  " + " - " +curso.nombre
            anio = str(curso.anio)
            #contenido = " Estimado " + alumno.first_name + ' ' + alumno.last_name + "\nLe enviamos el diploma de  " + curso.nombre + " \n"+ curso.leyenda_2 +' ' +curso.leyenda_3 +" \nPor favor confirmar recepción\nSaludos Cordiales. \nColegio de Médicos de Santa Fe - 1era Circunscripción"
            contenido = " Estimado/a " + alumno.first_name + ' ' + alumno.last_name + "\nLe enviamos el diploma de " + curso.nombre  +" \n Por favor confirmar recepción\n\nSaludos Cordiales. \nColegio de Médicos de Santa Fe - 1era Circunscripción"
            

        #msg_ = contenido.encode('utf-8')
        msg = MIMEMultipart()
        
        msg['Subject'] = encabezado
        msg.attach(MIMEText(contenido, 'plain'))
        #msg.attach(MIMEText(text))
        #nombre = alumno.last_name+'_'+curso.nombre+ '.pdf'
        #filename = nombre.encode('utf-8')
        attachment = open(path, "rb")
        curso = curso.nombre.replace(' ','_')
        curso = re.sub( r"([^n\u0300-\u036f]|n(?!\u0303(?![\u0300-\u036f])))[\u0300-\u036f]+", r"\1", normalize( "NFD", curso), 0, re.I)
        curso = re.sub('[^a-zA-Z0-9 \n\.]', '_', curso)
        # -> NFC
        curso= normalize( 'NFC', curso)
        nombre= alumno.first_name.replace(' ', '_')
        apellido = alumno.last_name.replace(' ', '_')
        filename = apellido+'_'+nombre+'_'+curso+'.pdf'
        print(filename)
        # instance of MIMEBase and named as p 
        p = MIMEBase('application', 'octet-stream') 
  
        # To change the payload into encoded form 
        p.set_payload((attachment).read()) 
  
        # encode into base64 
        encoders.encode_base64(p) 
       
        p.add_header('Content-Disposition', "attachment; filename= %s" % filename) 
  
        # attach the instance 'p' to instance 'msg' 
        msg.attach(p)         
        msg['From'] = "dario@cmsf.org.ar"
        server = smtplib.SMTP('mail.cmsf.org.ar', 25)
        server.starttls()
        server.login("dario@cmsf.org.ar", "M}zOII*]OXr8")
        #msg = "Help me with my math, please!"
        server.sendmail("dario@cmsf.org.ar", email, msg.as_string())
        server.quit()
        



        



        # texto = "echo  " + contenido + " | sudo mail -s Diplomas  -A "+ path + ' ' + email
        # print (texto)
        # proc = Popen(
     #                   texto,
     #                   shell=True,
     #                   stdout=PIPE, stderr=PIPE
        #         )
        # proc.wait()
        # res = proc.communicate() 
        # if proc.returncode:
        #     print(res[1])
        #     print('result:', res[0])
        #     answer = res[0]


admin.site.register(Curso, CursoAdmin)
admin.site.register(Alumno, AlumnoAdmin)
admin.site.register(Responsable, ResponsableAdmin)
admin.site.register(Miembro, MiembroAdmin)
