import os
import tempfile
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, DetailView
from .models import Curso, Miembro, Alumno, Responsable
from users.models import CustomUser
# Create your views here.
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 django.contrib import admin
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 gender_guesser.detector as gender
import requests
from PIL import Image as PILImage
from urllib.parse import quote

PAGE_WIDTH  = defaultPageSize[0]
PAGE_HEIGHT = defaultPageSize[1]
render_cursos = []
def draw_wrapped_text(p, text, x, y_start, max_width, font_name='libre_franklin_light', font_size=16, line_height=20):
    """Dibuja texto con quiebre de línea dentro de un ancho máximo"""
    from reportlab.pdfbase.pdfmetrics import stringWidth
    words = text.split()
    lines = []
    current_line = ""
    for word in words:
        test_line = current_line + (" " if current_line else "") + word
        if stringWidth(test_line, font_name, font_size) <= max_width:
            current_line = test_line
        else:
            lines.append(current_line)
            current_line = word
    if current_line:
        lines.append(current_line)
    
    y = y_start
    for line in lines:
        p.setFont(font_name, font_size)
        p.drawString(x, y, line)
        y -= line_height
    return y

def safe_text(x):
    if x is None:
        return ""
    # ReportLab en Py3 quiere str (unicode)
    return str(x)
    
class DiplomasPageView(TemplateView):
    '''Funcion que carga la plantilla chequeras''' 
    
    def get(self, request, *args, **kwargs):
        template_name = 'diplomas/diplomas.html'
        status = 200
        context = request
        current_user = request.user
        aux_prof = Miembro.objects.filter(alumno_id=current_user.id)

        print (aux_prof)
        # aux = Pago.objects.filter(usuario_codigo_id=current_user.id)
        # anio = date.today().year
        # mes = date.today().month

        render_cursos[:]=[]

        if aux_prof.exists():
            for w in aux_prof.all():
                curso = Curso.objects.get(id_curso__exact= w.curso_id)
                render_cursos.append(curso)

        # if aux_prof[0].activo_col == 1:
        #     for i in aux.all():
        #         if i.tipo_pago == 'C':
        #             render_pagos.append(i) 
        # if aux_prof[0].activo_seg == 1:
        #     for i in aux.all():
        #         if i.tipo_pago == 'S':
        #             render_pagos.append(i)
        
        return render(request, template_name, {'obj': render_cursos},context, status=status)


class DiplomasSearch(TemplateView):
    '''Funcion que carga la plantilla chequeras''' 
    
    # def get(self, request, *args, **kwargs):
    #     template_name = 'diplomas/diplomas_buscar.html'
    #     status = 200
    #     context = request
    #     current_user = request.user
    #     aux_prof = Miembro.objects.filter(alumno_id=current_user.id)

    #     print (aux_prof)
    #     # aux = Pago.objects.filter(usuario_codigo_id=current_user.id)
    #     # anio = date.today().year
    #     # mes = date.today().month

    #     render_cursos[:]=[]

    #     if aux_prof.exists():
    #         for w in aux_prof.all():
    #             curso = Curso.objects.get(id_curso__exact= w.curso_id)
    #             render_cursos.append(curso)

    #     # if aux_prof[0].activo_col == 1:
    #     #     for i in aux.all():
    #     #         if i.tipo_pago == 'C':
    #     #             render_pagos.append(i) 
    #     # if aux_prof[0].activo_seg == 1:
    #     #     for i in aux.all():
    #     #         if i.tipo_pago == 'S':
    #     #             render_pagos.append(i)
        
    #     return render(request, template_name, {'obj': render_cursos},context, status=status)

    def get(self, request, *args, **kwargs):
        template_name = 'diplomas/diplomas_buscar.html'
        status = 200
        context = request
        current_user = request.user
        search_query = request.GET.get('search_box', None)
        aux_prof = Alumno.objects.filter(nro_doc__exact=search_query)
        #
        alumno_aux = 0
        for a in aux_prof.all():
            alumno_aux =(int(a.id_alumno))
        aux_prof = Miembro.objects.filter(alumno_id=alumno_aux)
        #print (aux_prof)
        # aux = Pago.objects.filter(usuario_codigo_id=current_user.id)
        # anio = date.today().year
        # mes = date.today().month

        render_cursos = []
        nombre_alumno = ''
        id_alumno = 0
        if aux_prof.exists():
            for w in aux_prof.all():
                nombre_alumno = w.alumno
                id_alumno = w.alumno_id
            #render_cursos.append(nombre_alumno)
            for w in aux_prof.all():
                curso = Curso.objects.get(id_curso__exact= w.curso_id)          
                render_cursos.append(curso)
                #print(render_cursos)
        render_cursos = list(reversed(render_cursos))        
        # if aux_prof[0].activo_col == 1:
        #     for i in aux.all():
        #         if i.tipo_pago == 'C':
        #             render_pagos.append(i) 
        # if aux_prof[0].activo_seg == 1:
        #     for i in aux.all():
        #         if i.tipo_pago == 'S':
        #             render_pagos.append(i)
        
        return render(request, template_name, {'obj': render_cursos, 'nombre':nombre_alumno, 'id_alumno':id_alumno},context, status=status)



class generar_diploma(TemplateView):
    global ancho
    global inicio
    ancho = 554
    inicio = 22
    def get(self, request, id_curso, id_alumno):
        ''' funcion que genera el pdf '''
 
        '''
            parametros:
            ------------
            id_pago: numero que identifica al pago
        
        '''
           
        current_user = request.user
        #Miembro = Miembro.objects.filter(alumno_id=current_user.id)

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename="somefilename.pdf"'
        result_curso = Curso.objects.get(id_curso__exact=id_curso)
        o = Miembro.objects.get(alumno_id__exact = id_alumno , curso_id__exact = id_curso)
        #print (o)
        alumno = CustomUser.objects.get(id__exact = id_alumno)
        curso =  Curso.objects.get(id_curso__exact = id_curso)
        alumno_doc = Alumno.objects.get(id_alumno__exact = id_alumno)
        #response = HttpResponse(content_type='application/pdf')
        #response['Content-Disposition'] = 'filename="somefilename.pdf"'
        if curso.leyenda_7!=None:
            filename = str(alumno.last_name) + '_' + str(alumno.first_name)+ '_'+ str(curso.nombre) + '_' + str(curso.leyenda_7) +'.pdf'
        else:
            filename = str(alumno.last_name) + '_' + str(alumno.first_name)+ '_'+ str(curso.nombre) + '.pdf'
        #print(filename)
        #print(str(alumno.last_name))
        #filename = str(curso.nombre) + '.pdf'
        filename = filename.replace(',', '_')
        filename = filename.replace('“', '_')
        filename = filename.replace(' ', '_')
        filename = filename.replace('”', '_')
        filename = filename.replace('ú', 'u')
        filename = filename.replace('í', 'i')
        filename = filename.replace('é', 'e')
        filename = filename.replace('á', 'a')
        filename = filename.replace('ó', 'o')
        #print(filename)
        p = canvas.Canvas(response, pagesize=landscape(A4))

        if curso.tipo == 'CURSO':
            #print("hola")
            if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA'):
                    p = self.cabecera(p)
                    #print("hola")
                    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 == 'CURSO NUEVO':
            p = self.cabecera_web_nuevo(p)  # Usar la nueva cabecera
            p = self.cursos_nuevo(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(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 == 'WEBINARIO NUEVO':
            p = self.cabecera_web_nuevo(p)
            p = self.cuerpo_web_nuevo(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(p, curso)
        elif curso.tipo == 'INVESTIGACIÓN':
            p = self.cabecera_inv(p)
            p = self.cuerpo_web_nuevo(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(p, curso)
        elif curso.tipo == 'ECG':
            p = self.cabecera_ecg(p)
            p = self.cuerpo_web_nuevo(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(p, curso)
        elif curso.tipo == 'SALUD MENTAL 2025':
            p = self.cabecera_salud_mental_2025(p)
            p = self.cuerpo_web_nuevo(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(p, curso)
        elif curso.tipo == 'CIRUGIA 2025':
            p = self.cabecera_cirugia_2025(p)
            p = self.cuerpo_cirugia_2026(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_cirugia_2025(p, curso)
        elif curso.tipo == 'URGENCIAS_2025':
            p = self.cabecera_web_nuevo(p)
            p = self.cuerpo_urgencias_2025(p, alumno, curso, alumno_doc, o)
            p = self.firmas_web_nuevo(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)
        elif curso.tipo == 'DIA ASMA 2026': # Noches culturales
            p = self.cabecera_dia_asma_2026(p)
            p = self.cuerpo_asma(p, alumno, curso, alumno_doc, o)
            p = self.firmas_asma(p, curso)
        elif curso.tipo == 'LESIONES': # Lesiones dermicas
            #print("hola")
            if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA' or o.rol == 'COORDINADORA'):
                p = self.cabecera_lesiones(p)
                #print("holaSASASASAS")
                #print (o.rol)
                p = self.cuerpo_coor(p, alumno, curso, alumno_doc, o )
                p = self.firmas(p, curso)
            else:
                p = self.cabecera_lesiones(p)
                p = self.cuerpo(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
        elif curso.tipo == 'NEUROLOGÍA': # Lesiones dermicas
            #print("hola")
            if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA' or o.rol == 'COORDINADORA'):
                p = self.cabecera_neurologia(p)
                #print("holaSASASASAS")
                #print (o.rol)
                p = self.cuerpo_coor(p, alumno, curso, alumno_doc, o )
                p = self.firmas(p, curso)
            else:
                p = self.cabecera_neurologia(p)
                p = self.cuerpo(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
        elif curso.tipo == 'SALUD_MENTAL': # Salud Mental
            #print("hola")
            if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA' or o.rol == 'COORDINADORA'):
                p = self.cabecera_salud_mental(p)
                #print("holaSASASASAS")
                #print (o.rol)
                p = self.cuerpo_coor(p, alumno, curso, alumno_doc, o )
                p = self.firmas(p, curso)
            else:
                p = self.cabecera_salud_mental(p)
                p = self.cuerpo(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)
        elif curso.tipo == 'ENDOCRINOLOGÍA': # Endocrinologia
            #print("hola")
            if (o.rol == 'COORDINADOR' or o.rol == 'DISERTANTE' or o.rol == 'DIRECTOR' or o.rol=='DIRECTORA' or o.rol == 'COORDINADORA'):
                p = self.cabecera_endo(p)
                #print("holaSASASASAS")
                #print (o.rol)
                p = self.cuerpo_coor(p, alumno, curso, alumno_doc, o )
                p = self.firmas(p, curso)
            else:
                p = self.cabecera_endo(p)
                p = self.cuerpo(p, alumno, curso, alumno_doc, o)
                p = self.firmas(p, curso)            


        else: # ad-honoren
            #print("hola")
            p = self.cabecera(p)
            p = self.cuerpo_ad(p, alumno, curso, alumno_doc, o)
            p = self.firmas_coor(p, curso)

        #response['Content-Disposition'] = 'attachment; filename=' + filename 
        #response['Content-Disposition'] = 'attachment; filename="filename,with,commas.txt"'
        response['Content-Disposition'] = "attachment; filename*=UTF-8''" + quote(filename)
        #response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        p.setTitle(filename)
        p.showPage()
        p.save()
        return response




    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 cabecera_lesiones(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-40, 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-40, 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-40, 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_derm_path='/home/cmsforg/djangox/static/images/logo_lesiones_dermicas_sub.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 45, 450, width=110, height=110)
        #p.drawImage(logo_prov_path, 760, 450, width=60, height=81)
        
        p.drawImage(logo_prov_path, 600, 450, width=80, height=108)
        #p.drawImage(logo_derm_path, 650, 450)
        p.drawImage(logo_derm_path, 690, 450, width=127, height=108)
        p.drawImage(logo_fondo_path, 1, 1, width=460, height=60)
        
        return p

    def cabecera_inv(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma_investigacion.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, width=845, height=600)
        #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 cabecera_ecg(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma_ecg.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, width=845, height=600)
        #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 cabecera_salud_mental_2025(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma_salud_mental_2025.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, width=845, height=600)
        #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 cabecera_dia_asma_2026(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma_dia_asma_2026.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, width=845, height=600)
        #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 cabecera_cirugia_2025(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma_cirugia_2025.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, width=845, height=600)
        #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 cabecera_neurologia(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-40, 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-40, 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-40, 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_neuro_path='/home/cmsforg/djangox/static/images/logo_neurologia.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 45, 450, width=110, height=110)
        #p.drawImage(logo_prov_path, 760, 450, width=60, height=81)
        
        p.drawImage(logo_prov_path, 600, 450, width=80, height=108)
        #p.drawImage(logo_derm_path, 650, 450)
        p.drawImage(logo_neuro_path, 690, 450, width=127, height=108)
        p.drawImage(logo_fondo_path, 1, 1, width=460, height=60)
        
        return p
    def cabecera_salud_mental(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-40, 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-40, 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-40, 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_neuro_path='/home/cmsforg/djangox/static/images/logo_salud_mental.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 45, 450, width=110, height=110)
        #p.drawImage(logo_prov_path, 760, 450, width=60, height=81)
        
        p.drawImage(logo_prov_path, 600, 450, width=80, height=108)
        #p.drawImage(logo_derm_path, 650, 450)
        p.drawImage(logo_neuro_path, 690, 475, width=126, height=51)
        p.drawImage(logo_fondo_path, 1, 1, width=460, height=60)
        
        return p

    def cabecera_endo(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-40, 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-40, 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-40, 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_endo_path='/home/cmsforg/djangox/static/images/logo_endo.jpg'
        logo_fondo_path='/home/cmsforg/djangox/static/images/fondo_diploma.png'
        #p.setFont('Helvetica', 16)
        p.drawImage(logo_col_path, 45, 450, width=110, height=110)
        #p.drawImage(logo_prov_path, 760, 450, width=60, height=81)
        
        p.drawImage(logo_prov_path, 600, 450, width=80, height=108)
        #p.drawImage(logo_derm_path, 650, 450)
        p.drawImage(logo_endo_path, 700, 450, width=82, height=106)
        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)
        articulo = alumno.first_name[0:4]
        #print(articulo)
        if articulo == "Dra. ":
            primera_linea = 'Certifica que la'
        elif articulo == "Dr. ":
            primera_linea = 'Certifica que el'
        else:
            primera_linea = 'Certifica que'
            #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 ='"'+ 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_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_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  , 222, leyenda_6)

        leyenda_4 = curso.leyenda_3
        if leyenda_4 != None:    
            leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
        if leyenda_6 != None:    
            p.drawString((PAGE_HEIGHT)/2.0 + 160 , 200, leyenda_4)
        else:
            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_asma(self, p, alumno, curso, alumno_doc, o):
            """
            Genera el cuerpo del PDF. 
            DNI a la misma altura que el nombre y última leyenda desplazada hacia abajo.
            """
            from reportlab.pdfbase.pdfmetrics import stringWidth

            MARGEN_IZQ   = 140  
            MARGEN_DER   = 50                   
            ancho_util   = PAGE_HEIGHT - MARGEN_IZQ - MARGEN_DER 
            
            T_GRANDE     = 22  
            T_NORMAL     = 14  
            
            INTERLINEADO = 18                   
            FUENTE_LIGHT = "libre_franklin_light"
            FUENTE_BOLD  = "libre_franklin_bold"

            def _wrap(texto, fuente, tamanio, ancho_especifico=None):
                ancho = ancho_especifico if ancho_especifico else ancho_util
                if not texto: return []
                lineas, linea = [], ""
                for palabra in texto.split():
                    candidata = f"{linea} {palabra}".strip() if linea else palabra
                    if stringWidth(candidata, fuente, tamanio) <= ancho:
                        linea = candidata
                    else:
                        if linea: lineas.append(linea)
                        linea = palabra
                if linea: lineas.append(linea)
                return lineas

            def _dibujar(lineas, fuente, tamanio, y_inicio, inter=None, x_offset=0):
                y = y_inicio
                distancia = inter if inter else INTERLINEADO
                p.setFont(fuente, tamanio)
                for linea in lineas:
                    p.drawString(MARGEN_IZQ + x_offset, y, linea)
                    y -= distancia
                return y

            p.setFillColor(black)

            # 1. TÍTULO
            y_cursor = _dibujar(["Certificado de Asistencia"], FUENTE_BOLD, T_GRANDE, 400)

            # 2. Leyenda 1
            y_cursor -= 10
            y_cursor = _dibujar(_wrap(curso.leyenda_1, FUENTE_LIGHT, T_NORMAL), FUENTE_LIGHT, T_NORMAL, y_cursor)

            # 3. NOMBRE Y DNI (Misma altura)
            y_cursor -= 10
            nombre_completo = f"{alumno.first_name} {alumno.last_name}".upper()
            p.setFont(FUENTE_BOLD, T_GRANDE)
            p.drawString(MARGEN_IZQ, y_cursor, nombre_completo)
            
            # Calculamos el ancho del nombre para poner el DNI a continuación
            ancho_nombre = stringWidth(nombre_completo, FUENTE_BOLD, T_GRANDE)
            dni_formateado = "{:,d}".format(int(alumno_doc.nro_doc)).replace(",", ".")
            texto_dni = f" - D.N.I. N°: {dni_formateado}"
            
            p.setFont(FUENTE_LIGHT, T_NORMAL)
            p.drawString(MARGEN_IZQ + ancho_nombre + 10, y_cursor, texto_dni)
            
            y_cursor -= INTERLINEADO # Bajamos el cursor después de la línea compartida

            # 4. Leyenda 2 (Si queda algo pendiente de la leyenda original)
            if curso.leyenda_2:
                y_cursor = _dibujar(_wrap(curso.leyenda_2, FUENTE_LIGHT, T_NORMAL), FUENTE_LIGHT, T_NORMAL, y_cursor)

            # 5. TÍTULO DEL CURSO
            y_cursor -= 10
            curso_texto = f'"{curso.nombre} - {curso.anio}"'
            y_cursor = _dibujar(_wrap(curso_texto, FUENTE_BOLD, T_GRANDE), FUENTE_BOLD, T_GRANDE, y_cursor)

            # 6. Leyendas 3 y 4
            y_cursor -= 8
            for ley in [curso.leyenda_3, curso.leyenda_4]:
                if ley:
                    lineas_ley = _wrap(ley, FUENTE_LIGHT, T_NORMAL)
                    y_cursor = _dibujar(lineas_ley, FUENTE_LIGHT, T_NORMAL, y_cursor, inter=16)
                    y_cursor -= 5 

            # 7. Fecha y lugar (Bajado de 190 a 170 para evitar solapamiento)
            if curso.leyenda_5:
                _dibujar(_wrap(curso.leyenda_5, FUENTE_LIGHT, T_NORMAL), FUENTE_LIGHT, T_NORMAL, 170)

            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)
        articulo = alumno.first_name[0:4]
        #print(articulo)
        if articulo == "Dra.":
            primera_linea = 'Certifica que la'
        elif articulo == "Dr. ":
            primera_linea = 'Certifica que el'
        else:
            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 , 316, 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 , 294, 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 , 272, 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 , 250, 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, 228, 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 , 206, leyenda_6)
        else:
            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 , 272, 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, 250, 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 , 228, 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)

        articulo = alumno.first_name[0:4]
        #print(articulo)
        if articulo == "Dra.":
            primera_linea = 'Certifica que la'
        elif articulo == "Dr. ":
            primera_linea = 'Certifica que el'
        else:
            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)
        articulo = alumno.first_name[0:4]
        #print(articulo)
        if articulo == "Dra.":
            primera_linea = 'Certifica que la'
        elif articulo == "Dr. ":
            primera_linea = 'Certifica que el'
        else:
            primera_linea = 'Certifica que'

        #primera_linea = 'Certifica que el'
        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'or o.rol == 'DIRECTOR' or o.rol == 'COORDINADORA'):
            #print("hola holassss")
            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', 16)
                leyenda_disertante_3 = curso.leyenda_disertante_3
                leyenda_disertante_3_width = stringWidth(leyenda_disertante_3, 'baske_negrita', 16)
                p.drawString((PAGE_HEIGHT - leyenda_disertante_3_width )/2.0 + 160 , 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_negrita', 14)
                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', 14)
                leyenda_disertante_5_width = stringWidth(leyenda_disertante_5, 'baske_negrita', 14)
                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_negrita', 14)
                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', 16)
            if curso.leyenda_5!= None:
                leyenda_5 = curso.leyenda_5
                #print(leyenda_5)
        #leyenda_4_width = stringWidth(leyenda_4, 'baske_negrita', 20)
                p.drawString((PAGE_HEIGHT)/2.0 +160, 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', 18)
            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)
            #print('holassss')
            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)
        articulo = alumno.first_name[0:5]
        #print(articulo)
        if articulo == "Dra. ":
            primera_linea = 'Certifica que la'
        elif articulo == "Dr. ":
            primera_linea = 'Certifica que el'
        else:
            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(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 , 86, 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 , 90, width=90, height=90)
                elif(str(o.imagen_firma)=='static/firmas/iribas.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 90, width=90, height=90)
                if (str(o.imagen_firma)=='static/firmas/firma_galluccio.jpg'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)

                else:
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 90 - 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 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:


            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 , 86, width=90, height=90)
                elif (str(o.imagen_firma)=='static/firmas/MALACHEVSKY_MARIA_VERONICA.png'):
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 86, 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 , 86, width=90, height=90)
                else:
                    firma = '/home/cmsforg/djangox/' + str(o.imagen_firma)
                    #print(firma)
                    p.drawImage(firma, (nuevo_width + offset - 90 )/2.0 , 86 - 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
            if tercera_linea != None:
                
                tercera_linea_width = stringWidth(tercera_linea, 'baske_negrita', 10)
                p.drawString((nuevo_width + offset - tercera_linea_width )/2.0 , 43, 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 cabecera_web_nuevo(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_fondo_path ='/home/cmsforg/djangox/static/images/fondo_diploma.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, width=845, height=600)
        #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"):
            if curso.leyenda_4 != None:
                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)
            if curso.leyenda_5 != None:
                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', 20)
            tema = '"' + curso.nombre + '"' # muchos disertantes
            #tema = 'sobre el Tema: "' + curso.nombre + '"' # un disertante
            tema_width = stringWidth(tema, 'baske_negrita', 20)
            p.drawString((PAGE_HEIGHT - tema_width - margen_web )/2.0 , 310, tema)
            p.setFont('baske_negrita', 18)

        if curso.leyenda_1_bis !=None:    
            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)

        if curso.leyenda_2 != None:
            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)


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

        if curso.leyenda_4 != None:
            leyenda_3_width = stringWidth(curso.leyenda_3, 'baske_negrita', 13)
            p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_web)/2.0 + 160 , 210, curso.leyenda_3)
        else:
            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 cuerpo_web_nuevo(self, p, alumno, curso, alumno_doc, o):
    #     """Genera el cuerpo del PDF para diplomas de webinarios."""

    #     import requests
    #     from reportlab.lib.colors import black
    #     from reportlab.pdfbase.pdfmetrics import stringWidth

    #     # ── Helpers ───────────────────────────────────────────────────────────────

    #     def obtener_genero(nombre, api_key=None):
    #         try:
    #             r = requests.get(
    #                 "https://api.genderize.io",
    #                 params={"name": nombre},
    #                 timeout=2,
    #             )
    #             data = r.json()
    #             if data.get("gender") == "male":
    #                 return "masculino"
    #             if data.get("gender") == "female":
    #                 return "femenino"
    #         except Exception:
    #             pass
    #         return "indefinido"

    #     def wrap_text_by_width(text, font_name, font_size, max_width):
    #         """Parte un texto en líneas que entren en max_width, cortando por palabras."""
    #         words = text.split()
    #         lines = []
    #         current = ""

    #         for w in words:
    #             candidate = (current + " " + w).strip()
    #             if stringWidth(candidate, font_name, font_size) <= max_width:
    #                 current = candidate
    #             else:
    #                 if current:
    #                     lines.append(current)
    #                 if stringWidth(w, font_name, font_size) <= max_width:
    #                     current = w
    #                 else:
    #                     chunk = ""
    #                     for ch in w:
    #                         cand2 = chunk + ch
    #                         if stringWidth(cand2, font_name, font_size) <= max_width:
    #                             chunk = cand2
    #                         else:
    #                             if chunk:
    #                                 lines.append(chunk)
    #                             chunk = ch
    #                     current = chunk

    #         if current:
    #             lines.append(current)
    #         return lines

    #     # ── Constantes de layout ──────────────────────────────────────────────────
    #     FONT_BODY  = ("libre_franklin_light", 16)  # texto corriente — tamaño único
    #     FONT_BOLD  = ("libre_franklin_bold",  18)  # nombre del alumno y título del curso
    #     MARGEN_IZQ = 180
    #     MARGEN_DER = 120
    #     MAX_WIDTH  = PAGE_HEIGHT - (MARGEN_IZQ + MARGEN_DER)  # landscape: ancho útil

    #     # ── Género y texto de apertura ─────────────────────────────────────────────
    #     genero = obtener_genero(alumno.first_name)

    #     if alumno.prefix:
    #         if genero == "masculino":
    #             texto_certificado = "Se otorga el presente certificado al"
    #         elif genero == "femenino":
    #             texto_certificado = "Se otorga el presente certificado a la"
    #         else:
    #             texto_certificado = "Se otorga el presente certificado a"
    #     else:
    #         texto_certificado = "Se otorga el presente certificado a"

    #     p.setFillColor(black)
    #     p.setStrokeColor(black)
    #     p.setFont(*FONT_BODY)
    #     p.drawString(MARGEN_IZQ, 380, texto_certificado)

    #     # ── DNI ───────────────────────────────────────────────────────────────────
    #     dni    = int(alumno_doc.nro_doc)
    #     dni_   = "{:,d}".format(dni).replace(",", ".")
    #     nro_doc = ", D.N.I. " + str(dni_) + ";"

    #     # ── Nombre + prefijo + DNI ────────────────────────────────────────────────
    #     nombre_y_apellido = f"{alumno.first_name.title()} {alumno.last_name.title()}"

    #     if alumno.prefix and len(alumno.prefix) < 10:
    #         # Prefijo corto: todo en la misma línea
    #         p.setFont(*FONT_BOLD)
    #         p.drawString(MARGEN_IZQ, 335, alumno.prefix)
    #         ancho_prefijo = stringWidth(alumno.prefix, *FONT_BOLD)

    #         p.drawString(MARGEN_IZQ + ancho_prefijo + 10, 335, nombre_y_apellido)
    #         ancho_nombre = stringWidth(nombre_y_apellido, *FONT_BOLD)

    #         p.setFont(*FONT_BODY)
    #         p.drawString(MARGEN_IZQ + ancho_prefijo + ancho_nombre + 20, 335, nro_doc)

    #     elif alumno.prefix:
    #         # Prefijo largo: en línea aparte
    #         p.setFont(*FONT_BOLD)
    #         p.drawString(MARGEN_IZQ, 355, alumno.prefix)
    #         p.drawString(MARGEN_IZQ, 335, nombre_y_apellido)

    #         p.setFont(*FONT_BODY)
    #         p.drawString(
    #             MARGEN_IZQ + stringWidth(nombre_y_apellido, *FONT_BOLD) + 10,
    #             335,
    #             nro_doc,
    #         )
    #     else:
    #         # Sin prefijo
    #         p.setFont(*FONT_BOLD)
    #         p.drawString(MARGEN_IZQ, 335, nombre_y_apellido)

    #         p.setFont(*FONT_BODY)
    #         p.drawString(
    #             MARGEN_IZQ + stringWidth(nombre_y_apellido, *FONT_BOLD) + 10,
    #             335,
    #             nro_doc,
    #         )

    #     # ── Leyendas / Título ─────────────────────────────────────────────────────
    #     posicion_vertical = 260

    #     if o.rol == "DISERTANTE":
    #         p.setFont(*FONT_BODY)
    #         if curso.leyenda_4:
    #             w4 = stringWidth(curso.leyenda_4, *FONT_BODY)
    #             p.drawString((PAGE_HEIGHT - w4 - MARGEN_IZQ) / 2.0, 310, curso.leyenda_4)
    #         if curso.leyenda_5:
    #             w5 = stringWidth(curso.leyenda_5, *FONT_BODY)
    #             p.drawString((PAGE_HEIGHT - w5 - MARGEN_IZQ) / 2.0, 280, curso.leyenda_5)

    #     else:
    #         p.setFont(*FONT_BODY)
    #         p.drawString(MARGEN_IZQ, 310, curso.leyenda_1)

    #         # Título del curso con auto-wrap
    #         p.setFont(*FONT_BOLD)
    #         tema        = f'"{curso.nombre}"'
    #         line_height = 24

    #         lineas_tema = wrap_text_by_width(tema, FONT_BOLD[0], FONT_BOLD[1], MAX_WIDTH)[:3]

    #         y = 275
    #         for linea in lineas_tema:
    #             p.drawString(MARGEN_IZQ, y, linea)
    #             y -= line_height

    #         posicion_vertical = y + (line_height - 5)
    #         p.setFont(*FONT_BODY)

    #     # ── Leyendas adicionales ───────────────────────────────────────────────────
    #     if curso.leyenda_1_bis and curso.leyenda_1_bis.strip():
    #         p.setFont(*FONT_BODY)
    #         p.drawString(MARGEN_IZQ, posicion_vertical - 25, curso.leyenda_1_bis)
    #         posicion_vertical -= 25

    #     if curso.leyenda_2:
    #         posicion_vertical = draw_wrapped_text(
    #             p,
    #             curso.leyenda_2,
    #             x=MARGEN_IZQ,
    #             y_start=posicion_vertical - 25,
    #             max_width=PAGE_WIDTH,
    #             font_name=FONT_BODY[0],
    #             font_size=FONT_BODY[1],
    #             line_height=20,
    #         )

    #     if curso.leyenda_4 and str(curso.leyenda_4).strip():
    #         p.setFont(*FONT_BODY)
    #         p.drawString(MARGEN_IZQ, posicion_vertical - 10, curso.leyenda_4)
    #         posicion_vertical -= 15

    #     # ── Fecha — encima de la firma derecha, sin superponerse ─────────────────────
    #     if curso.leyenda_3 and str(curso.leyenda_3).strip():
    #         p.setFont(*FONT_BODY)
    #         w3 = stringWidth(curso.leyenda_3, *FONT_BODY)

    #         # Alineada a la derecha del área útil (espejo del margen izquierdo)
    #         x_fecha = PAGE_HEIGHT - MARGEN_DER - w3   # empuja el texto al margen derecho
    #         FECHA_Y = 165                              # encima de la firma; subir si sigue pisando

    #         p.drawString(x_fecha, FECHA_Y, curso.leyenda_3)

    #     return p
    def cuerpo_web_nuevo(self, p, alumno, curso, alumno_doc, o):
        """Genera el cuerpo del PDF para diplomas de webinarios."""

        import requests
        from reportlab.lib.colors import black
        from reportlab.pdfbase.pdfmetrics import stringWidth

        # ── Helpers ───────────────────────────────────────────────────────────────

        def obtener_genero(nombre, api_key=None):
            try:
                r = requests.get(
                    "https://api.genderize.io",
                    params={"name": nombre},
                    timeout=2,
                )
                data = r.json()
                if data.get("gender") == "male":
                    return "masculino"
                if data.get("gender") == "female":
                    return "femenino"
            except Exception:
                pass
            return "indefinido"

        def wrap_text_by_width(text, font_name, font_size, max_width):
            """Parte un texto en líneas que entren en max_width, cortando por palabras."""
            words = text.split()
            lines = []
            current = ""

            for w in words:
                candidate = (current + " " + w).strip()
                if stringWidth(candidate, font_name, font_size) <= max_width:
                    current = candidate
                else:
                    if current:
                        lines.append(current)
                    if stringWidth(w, font_name, font_size) <= max_width:
                        current = w
                    else:
                        chunk = ""
                        for ch in w:
                            cand2 = chunk + ch
                            if stringWidth(cand2, font_name, font_size) <= max_width:
                                chunk = cand2
                            else:
                                if chunk:
                                    lines.append(chunk)
                                chunk = ch
                        current = chunk

            if current:
                lines.append(current)
            return lines

        # ── Constantes de layout ──────────────────────────────────────────────────
        FONT_BODY     = ("libre_franklin_light", 16)
        FONT_BOLD     = ("libre_franklin_bold",  18)
        MARGEN_IZQ    = 180
        MARGEN_DER    = 120
        MARGEN_TITULO = 180
        MAX_WIDTH_TITULO = PAGE_HEIGHT - (MARGEN_TITULO + 40)   # ~622pt

        # ── Género y texto de apertura ────────────────────────────────────────────
        genero = obtener_genero(alumno.first_name)

        if alumno.prefix:
            if genero == "masculino":
                texto_certificado = "Se otorga el presente certificado al"
            elif genero == "femenino":
                texto_certificado = "Se otorga el presente certificado a la"
            else:
                texto_certificado = "Se otorga el presente certificado a"
        else:
            texto_certificado = "Se otorga el presente certificado a"

        p.setFillColor(black)
        p.setStrokeColor(black)
        p.setFont(*FONT_BODY)
        p.drawString(MARGEN_IZQ, 400, texto_certificado)

        # ── DNI ───────────────────────────────────────────────────────────────────
        dni    = int(alumno_doc.nro_doc)
        dni_   = "{:,d}".format(dni).replace(",", ".")
        nro_doc = ", D.N.I. " + str(dni_) + ";"

        # ── Nombre + prefijo + DNI ────────────────────────────────────────────────
        nombre_y_apellido = f"{alumno.first_name.title()} {alumno.last_name.title()}"

        if alumno.prefix and len(alumno.prefix) < 10:
            # Prefijo corto: todo en la misma línea
            p.setFont(*FONT_BOLD)
            p.drawString(MARGEN_IZQ, 375, alumno.prefix)
            ancho_prefijo = stringWidth(alumno.prefix, *FONT_BOLD)

            p.drawString(MARGEN_IZQ + ancho_prefijo + 10, 375, nombre_y_apellido)
            ancho_nombre = stringWidth(nombre_y_apellido, *FONT_BOLD)

            p.setFont(*FONT_BODY)
            p.drawString(MARGEN_IZQ + ancho_prefijo + ancho_nombre + 20, 375, nro_doc)

        elif alumno.prefix:
            # Prefijo largo: en línea aparte
            p.setFont(*FONT_BOLD)
            p.drawString(MARGEN_IZQ, 375, alumno.prefix)
            p.drawString(MARGEN_IZQ, 355, nombre_y_apellido)

            p.setFont(*FONT_BODY)
            p.drawString(
                MARGEN_IZQ + stringWidth(nombre_y_apellido, *FONT_BOLD) + 10,
                355,
                nro_doc,
            )
        else:
            # Sin prefijo
            p.setFont(*FONT_BOLD)
            p.drawString(MARGEN_IZQ, 375, nombre_y_apellido)

            p.setFont(*FONT_BODY)
            p.drawString(
                MARGEN_IZQ + stringWidth(nombre_y_apellido, *FONT_BOLD) + 10,
                375,
                nro_doc,
            )

        # ── Leyendas / Título ─────────────────────────────────────────────────────
        posicion_vertical = 260

        if o.rol == "DISERTANTE":
            p.setFont(*FONT_BODY)
            if curso.leyenda_4:
                w4 = stringWidth(curso.leyenda_4, *FONT_BODY)
                p.drawString((PAGE_HEIGHT - w4 - MARGEN_IZQ) / 2.0, 330, curso.leyenda_4)
            if curso.leyenda_5:
                w5 = stringWidth(curso.leyenda_5, *FONT_BODY)
                p.drawString((PAGE_HEIGHT - w5 - MARGEN_IZQ) / 2.0, 305, curso.leyenda_5)

        else:
            # Leyenda 1
            p.setFont(*FONT_BODY)
            p.drawString(MARGEN_IZQ, 330, curso.leyenda_1)

            # Título del curso con auto-wrap y ancho extendido
            p.setFont(*FONT_BOLD)
            tema        = f'"{curso.nombre}"'
            line_height = 24

            lineas_tema = wrap_text_by_width(
                tema, FONT_BOLD[0], FONT_BOLD[1], MAX_WIDTH_TITULO
            )[:3]

            y = 305
            for linea in lineas_tema:
                p.drawString(MARGEN_TITULO, y, linea)
                y -= line_height

            posicion_vertical = y + (line_height - 5)
            p.setFont(*FONT_BODY)

        # ── Leyendas adicionales ───────────────────────────────────────────────────
        if curso.leyenda_1_bis and curso.leyenda_1_bis.strip():
            p.setFont(*FONT_BODY)
            p.drawString(MARGEN_IZQ, posicion_vertical - 20, curso.leyenda_1_bis)
            posicion_vertical -= 20

        if curso.leyenda_2:
            posicion_vertical = draw_wrapped_text(
                p,
                curso.leyenda_2,
                x=MARGEN_IZQ,
                y_start=posicion_vertical - 20,
                max_width=MAX_WIDTH_TITULO,
                font_name=FONT_BODY[0],
                font_size=FONT_BODY[1],
                line_height=22,
            )

        if curso.leyenda_4 and str(curso.leyenda_4).strip():
            p.setFont(*FONT_BODY)
            p.drawString(MARGEN_IZQ, posicion_vertical - 10, curso.leyenda_4)
            posicion_vertical -= 20

        # ── Fecha — alineada a la izquierda, debajo del último bloque ─────────────
        if curso.leyenda_3 and str(curso.leyenda_3).strip():
            p.setFont(*FONT_BODY)

            # Siempre debajo del último texto, con un mínimo de 30pt de separación.
            # max(130,...) evita entrar en zona de firmas.
            FECHA_Y = max(130, posicion_vertical - 30)

            p.drawString(MARGEN_IZQ, FECHA_Y, curso.leyenda_3)

        return p
    def cuerpo_cirugia_2026(self, p, alumno, curso, alumno_doc, o):
        """ función que genera el cuerpo del pdf para los diplomas de webinarios """

        import requests
        from reportlab.lib.colors import black
        from reportlab.pdfbase.pdfmetrics import stringWidth

        def obtener_genero(nombre, api_key=None):
            try:
                r = requests.get(
                    "https://api.genderize.io",
                    params={"name": nombre},
                    timeout=2
                )
                data = r.json()
                if data.get("gender") == "male":
                    return "masculino"
                if data.get("gender") == "female":
                    return "femenino"
            except Exception:
                pass
            return "indefinido"

        def wrap_text_by_width(text, font_name, font_size, max_width):
            """Parte un texto en líneas que entren en max_width, cortando por palabras."""
            words = (text or "").split()
            lines, current = [], ""

            for w in words:
                candidate = (current + " " + w).strip()
                if stringWidth(candidate, font_name, font_size) <= max_width:
                    current = candidate
                else:
                    if current:
                        lines.append(current)
                    if stringWidth(w, font_name, font_size) <= max_width:
                        current = w
                    else:
                        chunk = ""
                        for ch in w:
                            cand2 = chunk + ch
                            if stringWidth(cand2, font_name, font_size) <= max_width:
                                chunk = cand2
                            else:
                                if chunk:
                                    lines.append(chunk)
                                chunk = ch
                        current = chunk

            if current:
                lines.append(current)

            return lines

        # Obtener género
        genero = obtener_genero(alumno.first_name, api_key=None)

        # Ajustar texto según género
        if genero == "masculino":
            texto_certificado = "Se otorga el presente certificado al"
        elif genero == "femenino":
            texto_certificado = "Se otorga el presente certificado a la"
        else:
            texto_certificado = "Se otorga el presente certificado a"

        margen_web = 180
        margen_derecho = 120  # margen para cálculo de ancho usable (apaisado)

        p.setFillColor(black)
        p.setStrokeColor(black)

        # Encabezado certificado
        p.setFont("libre_franklin_light", 16)
        if alumno.prefix:
            p.drawString(margen_web, 380, texto_certificado)
        else:
            p.drawString(margen_web, 380, "Se otorga el presente certificado a")

        # Documento
        dni = int(alumno_doc.nro_doc)
        dni_ = "{:,d}".format(dni).replace(",", ".")
        nro_doc = ", D.N.I. " + str(dni_) + ";"

        # Nombre completo
        nombre_y_apellido = f"{alumno.first_name.title()} {alumno.last_name.title()}"

        # Nombre + prefijo + DNI
        if alumno.prefix and len(alumno.prefix) < 10:
            p.setFont("libre_franklin_bold", 18)
            p.drawString(margen_web, 335, alumno.prefix)

            ancho_prefijo = stringWidth(alumno.prefix, "libre_franklin_bold", 18)

            p.setFont("libre_franklin_bold", 18)
            p.drawString(margen_web + ancho_prefijo + 10, 335, nombre_y_apellido)

            ancho_total = ancho_prefijo + stringWidth(nombre_y_apellido, "libre_franklin_bold", 18) + 10

            p.setFont("libre_franklin_light", 16)
            p.drawString(margen_web + ancho_total + 10, 335, nro_doc)

        else:
            if alumno.prefix:
                p.setFont("libre_franklin_bold", 18)
                p.drawString(margen_web, 355, alumno.prefix)

            p.setFont("libre_franklin_bold", 18)
            p.drawString(margen_web, 335, nombre_y_apellido)

            p.setFont("libre_franklin_light", 16)
            p.drawString(
                margen_web + stringWidth(nombre_y_apellido, "libre_franklin_bold", 18) + 10,
                335,
                nro_doc
            )

        # --- Leyendas / Título ---
        posicion_vertical = 260  # default

        if o.rol == "DISERTANTE":
            # Mantengo tu lógica para disertantes
            if curso.leyenda_4:
                p.setFont("libre_franklin_light", 14)
                w4 = stringWidth(curso.leyenda_4, "libre_franklin_light", 14)
                p.drawString((PAGE_HEIGHT - w4 - margen_web) / 2.0, 310, curso.leyenda_4)

            if curso.leyenda_5:
                p.setFont("libre_franklin_light", 14)
                w5 = stringWidth(curso.leyenda_5, "libre_franklin_light", 14)
                p.drawString((PAGE_HEIGHT - w5 - margen_web) / 2.0, 280, curso.leyenda_5)

            posicion_vertical = 260

        else:
            # Leyenda 1 (texto previo al título)
            p.setFont("libre_franklin_light", 16)
            if curso.leyenda_1:
                p.drawString(margen_web, 310, curso.leyenda_1)

            # Ancho usable real (apaisado: PAGE_HEIGHT actúa como ancho)
            max_width = PAGE_HEIGHT - (margen_web + margen_derecho)

            # ✅ TÍTULO PRINCIPAL: curso.nombre
            titulo = (curso.nombre or "").strip()
            if titulo:
                p.setFont("libre_franklin_bold", 20)
                line_height_title = 24

                lineas_titulo = wrap_text_by_width(
                    titulo,
                    font_name="libre_franklin_bold",
                    font_size=20,
                    max_width=max_width
                )[:3]

                y = 282
                for linea in lineas_titulo:
                    p.drawString(margen_web, y, linea)
                    y -= line_height_title

                posicion_vertical = y + 6
            else:
                posicion_vertical = 260

            # ✅ SUBTÍTULO: curso.leyenda_1_bis (debajo del título)
            subtitulo = (curso.leyenda_1_bis or "").strip()
            if subtitulo:
                p.setFont("libre_franklin_light", 16)
                line_height_sub = 18

                lineas_sub = wrap_text_by_width(
                    subtitulo,
                    font_name="libre_franklin_light",
                    font_size=16,
                    max_width=max_width
                )[:2]

                y = posicion_vertical - 8
                for linea in lineas_sub:
                    p.drawString(margen_web, y, linea)
                    y -= line_height_sub

                posicion_vertical = y + 4

            # volver a fuente normal
            p.setFont("libre_franklin_light", 16)

        # --- Leyendas adicionales ---
        # ⚠️ OJO: ya NO dibujamos leyenda_1_bis acá (porque ahora es subtítulo real)

        if curso.leyenda_2:
            posicion_vertical = draw_wrapped_text(
                p,
                curso.leyenda_2,
                x=margen_web,
                y_start=posicion_vertical - 18,
                max_width=PAGE_WIDTH,  # si querés lo ajustamos igual que max_width
                font_name="libre_franklin_light",
                font_size=14,
                line_height=18
            )

        if curso.leyenda_4 and o.rol != "DISERTANTE":
            p.setFont("libre_franklin_light", 16)
            p.drawString(margen_web, posicion_vertical - 10, curso.leyenda_4)
            posicion_vertical -= 15

        if curso.leyenda_3:
            p.setFont("libre_franklin_light", 16)
            w3 = stringWidth(curso.leyenda_3, "libre_franklin_light", 16)
            p.drawString((PAGE_HEIGHT - w3 - margen_web) / 2.0 + 340, posicion_vertical - 25, curso.leyenda_3)

        return p

    def cuerpo_urgencias_2025(self, p, alumno, curso, alumno_doc, o):
        ''' Función que genera el cuerpo del PDF para diplomas de urgencias en A4 apaisado '''

        # ------------- DETECCIÓN DE GÉNERO (igual que antes) ----------------
        def obtener_genero(nombre, api_key=None):
            url = f"https://api.genderize.io?name={nombre}"
            if api_key:
                url += f"&apikey={api_key}"

            response = requests.get(url)
            data = response.json()

            if data.get('gender') == 'male':
                return 'masculino'
            elif data.get('gender') == 'female':
                return 'femenino'
            return 'indefinido'

        genero = obtener_genero(alumno.first_name)

        if genero == 'masculino':
            texto_certifica = "Certifica que "
        elif genero == 'femenino':
            texto_certifica = "Certifica que "
        else:
            texto_certifica = "Certifica que "

        margen_web = 180

        # ============================================================
        #  CERTIFICA QUE + NOMBRE + DNI EN LA MISMA LÍNEA (PEDIDO)
        # ============================================================
        dni = int(alumno_doc.nro_doc)
        dni_fmt = "{:,d}".format(dni).replace(",", ".")
        texto_dni = f", D.N.I. {dni_fmt}"

        nombre_y_apellido = f"{alumno.first_name.title()} {alumno.last_name.title()}"

        # Generamos el texto completo en una sola línea
        linea_completa = texto_certifica + nombre_y_apellido + texto_dni

        p.setFont("libre_franklin_light", 16)
        p.drawString(margen_web, 365, linea_completa)

        # ============================================================
        #  (NO IMPRIME MÁS NOMBRE + DNI DEBAJO — YA ESTÁ EN UNA LÍNEA)
        # ============================================================

        # ------------- SOLO EL CURSO MÁS GRANDE ----------------
        titulo = f"ASISTENTE en el Curso de {curso.nombre}"

        p.setFont('libre_franklin_bold', 20)  # más grande SOLO aquí

        max_width = PAGE_WIDTH - 40  # margen derecho en hoja apaisada

        # ¿Cabe en una sola línea?
        if stringWidth(titulo, 'libre_franklin_bold', 20) <= max_width:
            p.drawString(margen_web, 340, titulo)
            posicion_vertical = 285
        else:
            palabras = titulo.split(" ")
            linea = ""
            y_actual = 340

            for palabra in palabras:
                if stringWidth(linea + " " + palabra, 'libre_franklin_bold', 20) <= max_width:
                    linea += " " + palabra
                else:
                    p.drawString(margen_web, y_actual, linea.strip())
                    y_actual -= 25
                    linea = palabra

            p.drawString(margen_web, y_actual, linea.strip())
            posicion_vertical = y_actual - 25

        # Volver a tamaño normal
        p.setFont('libre_franklin_light', 16)

        # ---------------------------------------------------------
        # RESTO DEL TEXTO IGUAL QUE ANTES (NO SE TOCA NADA)
        # ---------------------------------------------------------

        # p.drawString(margen_web, posicion_vertical,
        #              "Finalizó y aprobó con una carga horaria: 150 horas (incluye 20 horas de práctica).")
        p.drawString(margen_web, posicion_vertical,
                     safe_text(curso.leyenda_2))
        posicion_vertical -= 30

        # p.drawString(margen_web, posicion_vertical,
        #              'Pasantía en la Guardia Central del Hospital "Dr. José María Cullen".')
        p.drawString(margen_web, posicion_vertical,
                     safe_text(curso.leyenda_4))
        posicion_vertical -= 30

        # p.drawString(margen_web, posicion_vertical,
        #              "Práctica total de 144 hs; de Julio a Septiembre de 2025, c/ 12 hs de guardias semanales.")
        p.drawString(margen_web, posicion_vertical,
                     safe_text(curso.leyenda_5))
        posicion_vertical -= 40

        # ------------- FECHA A LA DERECHA REAL ----------------
        fecha_texto = safe_text(curso.leyenda_3)
        p.setFont('libre_franklin_light', 16)

        ancho_fecha = stringWidth(fecha_texto, "libre_franklin_light", 16)
        x_fecha = PAGE_WIDTH   # margen derecho

        p.drawString(x_fecha, posicion_vertical, fecha_texto)

        return p

    def cuerpo_urgencias_2025_(self, p, alumno, curso, alumno_doc, o):
        ''' función que genera el cuerpo del pdf para los diplomas de webinarios '''
        
        '''
            parámetros:
            ------------
            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
        '''
        def obtener_genero(nombre, api_key=None):
            """Detecta el género usando la API de Genderize.io"""
            url = f"https://api.genderize.io?name={nombre}"
            if api_key:
                url += f"&apikey={api_key}"
            
            response = requests.get(url)
            data = response.json()

            # Analizar respuesta de la API
            if data.get('gender') == 'male':
                return 'masculino'
            elif data.get('gender') == 'female':
                return 'femenino'
            else:
                return 'indefinido'

        # Obtener género usando la API Genderize
        genero = obtener_genero(alumno.first_name, api_key=None)

        # Ajustar el texto del certificado en función del género
        if genero == 'masculino':
            texto_certificado = 'Certifica que el'
        elif genero == 'femenino':
            texto_certificado = 'Certifica que la'
        else:
            texto_certificado = 'Certifica que'
        margen_web = 180
        p.setFont('libre_franklin_light', 16)
        if alumno.prefix:
             p.drawString(margen_web, 380, texto_certificado)
        else:
             texto_certificado = 'Certifica que'
             p.drawString(margen_web, 380, texto_certificado)      

        dni = int(alumno_doc.nro_doc)
        dni_ = '{:,d}'.format(dni).replace(",", ".")
        nro_doc = ', D.N.I. ' + str(dni_) + ";"
        
        p.setFillColor(black)
        p.setStrokeColor(black)

        # Texto del certificado con tamaño uniforme
        p.setFont('libre_franklin_light', 16)

        # Obtener el nombre completo formateado
        nombre_y_apellido = f"{alumno.first_name.title()} {alumno.last_name.title()}"

        # Verificar si el prefijo tiene menos de 10 caracteres
        if alumno.prefix and len(alumno.prefix) < 10:
            # Mostrar el prefijo en la misma línea que el nombre y el documento
            p.setFont('libre_franklin_bold', 18)  # Fuente y tamaño para el prefijo
            p.drawString(margen_web, 335, alumno.prefix)

            # Calcular el ancho del prefijo para ajustar la posición del nombre
            ancho_prefijo = stringWidth(alumno.prefix, 'libre_franklin_bold', 18)

            # Imprimir nombre y apellido junto al prefijo
            p.setFont('libre_franklin_bold', 18)
            p.drawString(margen_web + ancho_prefijo + 10, 335, nombre_y_apellido)

            # Calcular el ancho total del prefijo y el nombre completo
            ancho_total = ancho_prefijo + stringWidth(nombre_y_apellido, 'libre_franklin_bold', 18) + 10

            # Imprimir el número de documento al final
            p.setFont('libre_franklin_light', 16)
            p.drawString(margen_web + ancho_total + 10, 335, nro_doc)

        else:
            # Si el prefijo no existe o tiene 10 o más caracteres, mostrarlo en una línea separada
            if alumno.prefix:
                p.setFont('libre_franklin_bold', 18)
                p.drawString(margen_web, 355, alumno.prefix)

                # Imprimir nombre y apellido en la línea inferior
                p.setFont('libre_franklin_bold', 18)
                p.drawString(margen_web, 335, nombre_y_apellido)

                # Imprimir el número de documento junto al nombre
                p.setFont('libre_franklin_light', 16)
                p.drawString(margen_web + stringWidth(nombre_y_apellido, 'libre_franklin_bold', 18) + 10, 335, nro_doc)
            else:
                # Imprimir nombre y apellido en la línea inferior
                p.setFont('libre_franklin_bold', 18)
                p.drawString(margen_web, 335, nombre_y_apellido)

                # Imprimir el número de documento junto al nombre
                p.setFont('libre_franklin_light', 16)
                p.drawString(margen_web + stringWidth(nombre_y_apellido, 'libre_franklin_bold', 18) + 10, 335, nro_doc)


        p.setFont('libre_franklin_light', 16)  # Tamaño uniforme para el resto del texto
        leyenda_1_width = stringWidth(curso.leyenda_1, 'libre_franklin_light', 14)

        if o.rol == "DISERTANTE":
            # Imprimir leyendas específicas para disertantes
            if curso.leyenda_4 is not None:
                leyenda_4_width = stringWidth(curso.leyenda_4, 'libre_franklin_light', 14)
                p.drawString((PAGE_HEIGHT - leyenda_4_width - margen_web) / 2.0, 310, curso.leyenda_4)
            if curso.leyenda_5 is not None:
                leyenda_5_width = stringWidth(curso.leyenda_5, 'libre_franklin_light', 14)
                p.drawString((PAGE_HEIGHT - leyenda_5_width - margen_web) / 2.0, 280, curso.leyenda_5)
        else:
            # Imprimir leyenda 1 y el título del webinario
            p.drawString(margen_web, 310, curso.leyenda_1)
            
            # Ajustar formato del título del curso
            p.setFont('libre_franklin_bold', 18)  # Título en negrita y tamaño diferente
            tema = f'"{curso.nombre}"'
            
            # Agregar espaciado antes del tema
            p.drawString(margen_web, 295, "")  # Espacio vacío antes del título

            if len(tema) > 74:
                last_space_index = tema.rfind(' ', 0, 74)
                if last_space_index == -1:
                    last_space_index = 74
                p.drawString(margen_web, 275, tema[:last_space_index])  # Primera línea del tema
                p.drawString(margen_web, 255, tema[last_space_index:].strip())  # Segunda línea del tema
                posicion_vertical = 255
            else:
                p.drawString(margen_web, 275, tema)  # Línea única
                posicion_vertical = 260

            p.setFont('libre_franklin_light', 16)  # Volver al tamaño uniforme

        # Espaciado después del título del curso
        p.drawString(margen_web, posicion_vertical, "")  # Espacio vacío después del título

        # Imprimir leyendas adicionales si existen
        if curso.leyenda_1_bis is not None:    
            leyenda_1_bis_width = stringWidth(curso.leyenda_1_bis, 'libre_franklin_light', 16)
            p.drawString(margen_web, posicion_vertical - 25, curso.leyenda_1_bis)
            posicion_vertical -= 25  # Ajustamos la posición vertical

        if curso.leyenda_2:
            posicion_vertical = draw_wrapped_text(
                p,
                curso.leyenda_2,
                x=margen_web,
                y_start=posicion_vertical - 25,
                max_width=PAGE_WIDTH ,
                font_name='libre_franklin_light',
                font_size=14,
                line_height=18
            )
        if curso.leyenda_4 is not None:
            leyenda_4_width = stringWidth(curso.leyenda_4, 'libre_franklin_light', 16)
            p.drawString(margen_web, posicion_vertical - 10, curso.leyenda_4)
            posicion_vertical -= 15

        if curso.leyenda_3 is not None:
            leyenda_3_width = stringWidth(curso.leyenda_3, 'libre_franklin_light', 16)
            p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_web) / 2.0 + 340, posicion_vertical - 25, curso.leyenda_3)
            posicion_vertical -= 5

        # Devolver el objeto PDF modificado
        return p


    def cuerpo_web_nuevo_2(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('libre_franklin_light', 16)
        primera_linea = 'Confiere el presente certificado a'
        primera_linea_width = stringWidth(primera_linea, 'libre_franklin_light', 16)
        p.drawString(margen_web, 400, 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, 'libre_franklin_light', 16)

        nombre_y_apellido = alumno.first_name.title() + ' ' + alumno.last_name.title()        
        nombre_y_apellido_width = stringWidth(nombre_y_apellido, 'libre_franklin_bold', 18)
        p.setFont('libre_franklin_bold', 18)
        p.drawString(margen_web , 355, nombre_y_apellido)
        p.setFont('libre_franklin_bold', 16)
        p.drawString((margen_web + nombre_y_apellido_width + 2 ) , 355, nro_doc)

        p.setFont('libre_franklin_light', 16)
        
        leyenda_1_width = stringWidth(curso.leyenda_1, 'libre_franklin_light', 14)

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

            if len(tema) > 74:
                # Encontrar la última posición de un espacio antes de 74 caracteres
                last_space_index = tema.rfind(' ', 0, 74)
                
                # Si no se encuentra un espacio, cortamos en 74 caracteres (aunque esto es raro)
                if last_space_index == -1:
                    last_space_index = 74
                
                # Dividir en dos líneas en el último espacio encontrado
                p.drawString(margen_web, 305, tema[:last_space_index])            # Primera línea
                p.drawString(margen_web, 285, tema[last_space_index:].strip())    # Segunda línea
                posicion_vertical = 260  # Ajustamos la posición para las siguientes leyendas
            else:
                # Si es menor o igual a 74 caracteres, se imprime en una sola línea
                p.drawString(margen_web, 305, tema)
                posicion_vertical = 280  # Ajustamos la posición para las siguientes leyendas


            p.setFont('libre_franklin_light', 14)

# Leyenda 1 bis
        if curso.leyenda_1_bis is not None:    
            leyenda_1_bis_width = stringWidth(curso.leyenda_1_bis, 'libre_franklin_light', 16)
            p.drawString(margen_web, posicion_vertical, curso.leyenda_1_bis)
            posicion_vertical -= 25  # Ajustamos la posición vertical

        # Leyenda 2
        if curso.leyenda_2 is not None:
            leyenda_2_width = stringWidth(curso.leyenda_2, 'libre_franklin_light', 16)
            p.drawString(margen_web, posicion_vertical, curso.leyenda_2)
            posicion_vertical -= 25  # Ajustamos la posición vertical

        # Leyenda 4
        if curso.leyenda_4 is not None:
            leyenda_4_width = stringWidth(curso.leyenda_4, 'libre_franklin_light', 16)
            p.drawString(margen_web, posicion_vertical, curso.leyenda_4)
            posicion_vertical -= 25  # Ajustamos la posición vertical

        # Leyenda 3
        if curso.leyenda_3 is not None:
            leyenda_3_width = stringWidth(curso.leyenda_3, 'libre_franklin_light', 16)
            p.drawString((PAGE_HEIGHT - leyenda_3_width - margen_web) / 2.0 + 360, posicion_vertical, curso.leyenda_3)
            posicion_vertical -= 25  # Ajustamos la posición vertical

        return p
    # def cursos_nuevo(self, p, alumno, curso, alumno_doc, o):
    #     '''Función que genera diplomas de cursos con diseño moderno similar a webinarios_nuevo'''
        
    #     # Configuración de márgenes y estilos
    #     margen_izquierdo = 180
    #     color_principal = black
    #     color_secundario = (0.2, 0.2, 0.2)
        
    #     # Fondo del diploma (opcional - descomentar si se usa)
    #     # logo_fondo_path = '/home/cmsforg/djangox/static/images/fondo_diploma_curso.jpg'
    #     # p.drawImage(logo_fondo_path, 1, 1, width=845, height=600)
        
    #     # Texto inicial con detección de género
    #     articulo = alumno.first_name[0:4]
    #     if articulo == "Dra.":
    #         texto_certificacion = 'Certifica que la'
    #     elif articulo == "Dr. ":
    #         texto_certificacion = 'Certifica que el'
    #     else:
    #         texto_certificacion = 'Certifica que'
        
    #     # Encabezado
    #     p.setFont('libre_franklin_light', 16)
    #     p.setFillColor(color_principal)
    #     p.drawString(margen_izquierdo, 400, texto_certificacion)
        
    #     # Nombre del alumno y DNI
    #     nombre_completo = f"{alumno.first_name.title()} {alumno.last_name.title()}"
    #     dni = int(alumno_doc.nro_doc)
    #     dni_formateado = '{:,d}'.format(dni).replace(",", ".")
        
    #     # Manejo de prefijos (Dr./Dra.)
    #     if hasattr(alumno, 'prefix') and alumno.prefix:
    #         p.setFont('libre_franklin_bold', 18)
    #         p.drawString(margen_izquierdo, 370, alumno.prefix)
            
    #         # Nombre en línea separada
    #         p.setFont('libre_franklin_bold', 18)
    #         p.drawString(margen_izquierdo, 350, nombre_completo)
            
    #         # DNI al lado del nombre
    #         texto_dni = f", D.N.I. {dni_formateado}"
    #         p.setFont('libre_franklin_light', 16)
    #         p.drawString(margen_izquierdo + stringWidth(nombre_completo, 'libre_franklin_bold', 18) + 5, 350, texto_dni)
    #         posicion_actual = 330
    #     else:
    #         # Sin prefijo
    #         p.setFont('libre_franklin_bold', 18)
    #         p.drawString(margen_izquierdo, 370, nombre_completo)
            
    #         # DNI al lado del nombre
    #         texto_dni = f", D.N.I. {dni_formateado}"
    #         p.setFont('libre_franklin_light', 16)
    #         p.drawString(margen_izquierdo + stringWidth(nombre_completo, 'libre_franklin_bold', 18) + 5, 370, texto_dni)
    #         posicion_actual = 350
        
    #     # Rol en el curso
    #     p.setFont('libre_franklin_light', 16)
    #     texto_rol = f"{curso.leyenda_1} {o.rol} en el Curso de"
    #     p.drawString(margen_izquierdo, posicion_actual, texto_rol)
    #     posicion_actual -= 25
        
    #     # Nombre del curso (destacado)
    #     p.setFont('libre_franklin_bold', 20)
    #     nombre_curso = f'"{curso.nombre}"'
        
    #     # Manejo de texto largo para el nombre del curso
    #     if len(nombre_curso) > 60:
    #         # Dividir en dos líneas si es muy largo
    #         ultimo_espacio = nombre_curso.rfind(' ', 0, 60)
    #         if ultimo_espacio == -1:
    #             ultimo_espacio = 60
            
    #         p.drawString(margen_izquierdo, posicion_actual, nombre_curso[:ultimo_espacio])
    #         p.drawString(margen_izquierdo, posicion_actual - 20, nombre_curso[ultimo_espacio:].strip())
    #         posicion_actual -= 40
    #     else:
    #         p.drawString(margen_izquierdo, posicion_actual, nombre_curso)
    #         posicion_actual -= 25
        
    #     # Leyendas adicionales del curso
    #     p.setFont('libre_franklin_light', 16)
        
    #     if curso.leyenda_2:
    #         p.drawString(margen_izquierdo, posicion_actual, curso.leyenda_2)
    #         posicion_actual -= 25
        
    #     if curso.leyenda_3:
    #         p.drawString(margen_izquierdo, posicion_actual, curso.leyenda_3)
    #         posicion_actual -= 25
        
    #     if curso.leyenda_4:
    #         p.drawString(margen_izquierdo, posicion_actual, curso.leyenda_4)
    #         posicion_actual -= 25
        
    #     # Fecha y lugar (alineado a la derecha)
    #     if curso.leyenda_5:
    #         p.setFont('libre_franklin_light', 14)
    #         ancho_leyenda = stringWidth(curso.leyenda_5, 'libre_franklin_light', 14)
    #         p.drawString(PAGE_HEIGHT - ancho_leyenda - 50, posicion_actual, curso.leyenda_5)
        
    #     return p
    def cursos_nuevo(self, p, alumno, curso, alumno_doc, o):
        '''Función que genera diplomas de cursos con diseño moderno similar a webinarios_nuevo'''

        from reportlab.pdfbase.pdfmetrics import stringWidth
        from reportlab.lib.colors import black

        def wrap_text_by_width(text, font_name, font_size, max_width):
            """Parte un texto en líneas que entren en max_width, cortando por palabras."""
            words = text.split()
            lines = []
            current = ""
            for w in words:
                candidate = (current + " " + w).strip()
                if stringWidth(candidate, font_name, font_size) <= max_width:
                    current = candidate
                else:
                    if current:
                        lines.append(current)
                    if stringWidth(w, font_name, font_size) <= max_width:
                        current = w
                    else:
                        chunk = ""
                        for ch in w:
                            cand2 = chunk + ch
                            if stringWidth(cand2, font_name, font_size) <= max_width:
                                chunk = cand2
                            else:
                                if chunk:
                                    lines.append(chunk)
                                chunk = ch
                        current = chunk
            if current:
                lines.append(current)
            return lines

        # ── Constantes de layout ──────────────────────────────────────────────────
        FONT_BODY        = ("libre_franklin_light", 16)
        FONT_BOLD_NAME   = ("libre_franklin_bold",  18)
        FONT_BOLD_CURSO  = ("libre_franklin_bold",  20)
        MARGEN_IZQ       = 180
        MARGEN_DER       = 50
        MAX_WIDTH        = PAGE_HEIGHT - (MARGEN_IZQ + 40)   # ~622pt
        LINE_HEIGHT_BOLD = 26
        LINE_HEIGHT_BODY = 22

        p.setFillColor(black)
        p.setStrokeColor(black)

        # ── Texto inicial con detección de género ─────────────────────────────────
        articulo = alumno.first_name[0:4]
        if articulo == "Dra.":
            texto_certificacion = 'Certifica que la'
        elif articulo == "Dr. ":
            texto_certificacion = 'Certifica que el'
        else:
            texto_certificacion = 'Certifica que'

        p.setFont(*FONT_BODY)
        p.drawString(MARGEN_IZQ, 400, texto_certificacion)

        # ── Nombre del alumno y DNI ───────────────────────────────────────────────
        nombre_completo = f"{alumno.first_name.title()} {alumno.last_name.title()}"
        dni = int(alumno_doc.nro_doc)
        dni_formateado = '{:,d}'.format(dni).replace(",", ".")
        texto_dni = f", D.N.I. {dni_formateado}"

        if hasattr(alumno, 'prefix') and alumno.prefix:
            p.setFont(*FONT_BOLD_NAME)
            p.drawString(MARGEN_IZQ, 375, alumno.prefix)

            p.setFont(*FONT_BOLD_NAME)
            p.drawString(MARGEN_IZQ, 355, nombre_completo)

            p.setFont(*FONT_BODY)
            p.drawString(
                MARGEN_IZQ + stringWidth(nombre_completo, *FONT_BOLD_NAME) + 5,
                355,
                texto_dni
            )
            posicion_actual = 330

        else:
            p.setFont(*FONT_BOLD_NAME)
            p.drawString(MARGEN_IZQ, 375, nombre_completo)

            p.setFont(*FONT_BODY)
            p.drawString(
                MARGEN_IZQ + stringWidth(nombre_completo, *FONT_BOLD_NAME) + 5,
                375,
                texto_dni
            )
            posicion_actual = 350

        # ── Rol en el curso ───────────────────────────────────────────────────────
        p.setFont(*FONT_BODY)
        texto_rol = f"{curso.leyenda_1} {o.rol} al Curso "
        p.drawString(MARGEN_IZQ, posicion_actual, texto_rol)
        posicion_actual -= LINE_HEIGHT_BODY

        # ── Nombre del curso con wrap real por ancho ──────────────────────────────
        p.setFont(*FONT_BOLD_CURSO)
        nombre_curso = f'"{curso.nombre}"'

        lineas_curso = wrap_text_by_width(
            nombre_curso, FONT_BOLD_CURSO[0], FONT_BOLD_CURSO[1], MAX_WIDTH
        )

        for linea in lineas_curso:
            p.drawString(MARGEN_IZQ, posicion_actual, linea)
            posicion_actual -= LINE_HEIGHT_BOLD

        # recuperar un poco el espacio extra del último salto
        posicion_actual += (LINE_HEIGHT_BOLD - LINE_HEIGHT_BODY)

        # ── Leyendas del cuerpo (leyenda_2 y leyenda_3) ───────────────────────────
        p.setFont(*FONT_BODY)

        if curso.leyenda_2:
            lineas_l2 = wrap_text_by_width(
                curso.leyenda_2, FONT_BODY[0], FONT_BODY[1], MAX_WIDTH
            )
            for linea in lineas_l2:
                p.drawString(MARGEN_IZQ, posicion_actual, linea)
                posicion_actual -= LINE_HEIGHT_BODY

        if curso.leyenda_3:
            lineas_l3 = wrap_text_by_width(
                curso.leyenda_3, FONT_BODY[0], FONT_BODY[1], MAX_WIDTH
            )
            for linea in lineas_l3:
                p.drawString(MARGEN_IZQ, posicion_actual, linea)
                posicion_actual -= LINE_HEIGHT_BODY

        # ── Fecha/lugar — leyenda_4 y leyenda_5 alineadas a la derecha ────────────
        FECHA_Y = max(130, posicion_actual - 15)

        if curso.leyenda_4:
            p.setFont(*FONT_BODY)
            ancho_l4 = stringWidth(curso.leyenda_4, *FONT_BODY)
            p.drawString(PAGE_HEIGHT - ancho_l4 - MARGEN_DER, FECHA_Y, curso.leyenda_4)
            FECHA_Y -= LINE_HEIGHT_BODY

        if curso.leyenda_5:
            p.setFont(*FONT_BODY)
            ancho_l5 = stringWidth(curso.leyenda_5, *FONT_BODY)
            p.drawString(PAGE_HEIGHT - ancho_l5 - MARGEN_DER, FECHA_Y, curso.leyenda_5)

        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 firmas_web_nuevo(self, p, curso):
        """
        Genera las firmas del PDF para diplomas de webinarios.

        Parámetros
        ----------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas del PDF.
        curso : Curso
            Objeto del curso.

        Retorna
        -------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas modificado.
        """
        import os
        from django.conf import settings
        from PIL import Image as PILImage
        from reportlab.pdfbase.pdfmetrics import stringWidth

        # Traer responsables una sola vez
        responsables = list(Responsable.objects.filter(cursos=curso.id_curso))
        responsable_cantidad = len(responsables)

        # Evitar división por cero
        if responsable_cantidad == 0:
            return p

        # Recorremos en orden inverso como tu versión original
        responsables = list(reversed(responsables))

        nuevo_width = PAGE_HEIGHT / responsable_cantidad
        offset = 80

        # Helpers internos
        def _resolver_path_firma(responsable_obj):
            """
            Devuelve path absoluto a la firma si existe y es archivo.
            Si no se puede resolver, devuelve None.
            """
            img = getattr(responsable_obj, "imagen_firma", None)
            if not img:
                return None

            # Caso típico: ImageField/FileField
            try:
                path = img.path
            except Exception:
                # Caso string/relativo
                path = os.path.join(settings.MEDIA_ROOT, str(img))

            # Validar que sea archivo (no carpeta)
            if path and os.path.isfile(path):
                return path
            return None

        def _asegurar_jpg_rgb(path_img):
            """
            Convierte a JPG RGB si hace falta (para evitar problemas con alfa),
            y devuelve el path del JPG resultante.
            """
            base, _ext = os.path.splitext(path_img)
            path_jpg = base + "_rgb.jpg"

            # Si ya existe, reutilizar (evita trabajo)
            if os.path.isfile(path_jpg):
                return path_jpg

            im = PILImage.open(path_img)

            # Convertir a RGB (aplana alfa sobre blanco si corresponde)
            if im.mode in ("RGBA", "LA", "P"):
                im = im.convert("RGBA")
                bg = PILImage.new("RGB", im.size, (255, 255, 255))
                alpha = im.split()[-1]  # canal alfa
                bg.paste(im, mask=alpha)
                bg.save(path_jpg, "JPEG")
            else:
                im.convert("RGB").save(path_jpg, "JPEG")

            return path_jpg

        for o in responsables:
            # --- Dibujo de la imagen de firma (si existe) ---
            firma_path = _resolver_path_firma(o)

            if firma_path:
                try:
                    firma_rgb = _asegurar_jpg_rgb(firma_path)
                    p.drawImage(
                        firma_rgb,
                        (nuevo_width + offset - 70) / 2.0,
                        87,
                        width=70,
                        height=70
                    )
                except Exception as e:
                    # No rompas la generación del PDF por una firma malformada
                    print("Error procesando firma:", firma_path, "->", e)

            # --- Línea de firma ---
            p.setFont("baske_negrita", 11)
            p.setFillColorRGB(0, 0, 0)

            base_firma = "___________________"
            base_firma_width = stringWidth(base_firma, "libre_franklin_light", 11)
            p.drawString((nuevo_width + offset - base_firma_width) / 2.0, 90, base_firma)

            # --- Nombre y cargos ---
            p.setFillColorRGB(0, 0, 0)

            primera_linea = f"{o.cargo} {o.nombre} {o.apellido}".strip()
            primera_linea_width = stringWidth(primera_linea, "libre_franklin_light", 11)
            p.drawString((nuevo_width + offset - primera_linea_width) / 2.0, 70, primera_linea)

            p.setFont("libre_franklin_light", 8)

            segunda_linea = (o.cargo_2 or "").strip()
            if segunda_linea:
                segunda_linea_width = stringWidth(segunda_linea, "libre_franklin_light", 8)
                p.drawString((nuevo_width + offset - segunda_linea_width) / 2.0, 60, segunda_linea)

            tercera_linea = (o.cargo_3 or "").strip()
            if tercera_linea:
                tercera_linea_width = stringWidth(tercera_linea, "libre_franklin_light", 8)
                p.drawString((nuevo_width + offset - tercera_linea_width) / 2.0, 50, tercera_linea)

            # --- Avanzar offset ---
            offset = offset + nuevo_width + 300

        return p
    def firmas_asma(self, p, curso):
        """
        Genera las firmas del PDF para diplomas de webinarios.
        Soporta hasta 4 firmas distribuidas equitativamente en el ancho útil
        de la página (respetando el margen izquierdo de la franja verde).

        Parámetros
        ----------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas del PDF.
        curso : Curso
            Objeto del curso.

        Retorna
        -------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas modificado.
        """
        import os
        from django.conf import settings
        from PIL import Image as PILImage
        from reportlab.pdfbase.pdfmetrics import stringWidth

        responsables = list(Responsable.objects.filter(cursos=curso.id_curso))
        responsable_cantidad = len(responsables)

        if responsable_cantidad == 0:
            return p

        responsables = list(reversed(responsables))

        # ── Layout ───────────────────────────────────────────────────────────────
        MARGEN_IZQ = 100                                # franja verde vertical
        ancho_util = PAGE_HEIGHT - MARGEN_IZQ           # espacio disponible para firmas
        zona_width = ancho_util / responsable_cantidad  # ancho de cada celda
        firma_w    = 70
        firma_h    = 70
        y_imagen   = 87
        y_linea    = 90
        y_nombre   = 70
        y_cargo2   = 60
        y_cargo3   = 50

        # ── Helpers internos ─────────────────────────────────────────────────────

        def _resolver_path_firma(responsable_obj):
            img = getattr(responsable_obj, "imagen_firma", None)
            if not img:
                return None
            try:
                path = img.path
            except Exception:
                path = os.path.join(settings.MEDIA_ROOT, str(img))
            return path if path and os.path.isfile(path) else None

        def _asegurar_jpg_rgb(path_img):
            base, _ext = os.path.splitext(path_img)
            path_jpg = base + "_rgb.jpg"
            if os.path.isfile(path_jpg):
                return path_jpg
            im = PILImage.open(path_img)
            if im.mode in ("RGBA", "LA", "P"):
                im = im.convert("RGBA")
                bg = PILImage.new("RGB", im.size, (255, 255, 255))
                bg.paste(im, mask=im.split()[-1])
                bg.save(path_jpg, "JPEG")
            else:
                im.convert("RGB").save(path_jpg, "JPEG")
            return path_jpg

        def _centrar_x(texto, fuente, tamanio, zona_inicio):
            """Devuelve la X para centrar texto dentro de su zona."""
            ancho_texto = stringWidth(texto, fuente, tamanio)
            return zona_inicio + (zona_width - ancho_texto) / 2.0

        # ── Dibujar cada firma ───────────────────────────────────────────────────

        for i, o in enumerate(responsables):
            zona_x = MARGEN_IZQ + (i * zona_width)     # inicio X de esta zona

            # Imagen de firma
            firma_path = _resolver_path_firma(o)
            if firma_path:
                try:
                    firma_rgb = _asegurar_jpg_rgb(firma_path)
                    img_x = zona_x + (zona_width - firma_w) / 2.0
                    p.drawImage(firma_rgb, img_x, y_imagen, width=firma_w, height=firma_h)
                except Exception as e:
                    print("Error procesando firma:", firma_path, "->", e)

            # Línea separadora
            p.setFont("baske_negrita", 11)
            p.setFillColorRGB(0, 0, 0)
            base_firma = "___________________"
            p.drawString(_centrar_x(base_firma, "libre_franklin_light", 11, zona_x), y_linea, base_firma)

            # Nombre y cargo principal
            p.setFont("libre_franklin_light", 11)
            primera_linea = f"{o.cargo} {o.nombre} {o.apellido}".strip()
            p.drawString(_centrar_x(primera_linea, "libre_franklin_light", 11, zona_x), y_nombre, primera_linea)

            # Cargo 2
            p.setFont("libre_franklin_light", 8)
            segunda_linea = (o.cargo_2 or "").strip()
            if segunda_linea:
                p.drawString(_centrar_x(segunda_linea, "libre_franklin_light", 8, zona_x), y_cargo2, segunda_linea)

            # Cargo 3
            tercera_linea = (o.cargo_3 or "").strip()
            if tercera_linea:
                p.drawString(_centrar_x(tercera_linea, "libre_franklin_light", 8, zona_x), y_cargo3, tercera_linea)

        return p
    def firmas_web_cirugia_2025(self, p, curso):
        """
        Genera las firmas del PDF para diplomas de webinarios.
        Se adapta automáticamente a 1..4 firmas (A4 apaisado).

        Parámetros
        ----------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas del PDF.
        curso : Curso
            Objeto del curso.

        Retorna
        -------
        p : reportlab.pdfgen.canvas.Canvas
            Canvas modificado.
        """
        import os
        from django.conf import settings
        from PIL import Image as PILImage
        from reportlab.pdfbase.pdfmetrics import stringWidth

        # Traer responsables una sola vez
        responsables = list(Responsable.objects.filter(cursos=curso.id_curso))

        if not responsables:
            return p

        # Mantener tu lógica: orden inverso
        responsables = list(reversed(responsables))

        # ✅ Limitar a 4 firmas (layout 1 fila)
        responsables = responsables[:4]
        n = len(responsables)

        # --- Layout horizontal (A4 apaisado) ---
        # En tu proyecto usás PAGE_HEIGHT como "ancho" horizontal del documento.
        page_w = PAGE_HEIGHT

        left_margin = 80
        right_margin = 80
        usable_w = page_w - left_margin - right_margin

        col_w = usable_w / float(n)

        # Coordenadas base (mantengo tus Y originales)
        y_img = 87
        y_line = 90
        y_name = 70
        y_cargo2 = 60
        y_cargo3 = 50

        img_w = 70
        img_h = 70

        def _resolver_path_firma(responsable_obj):
            img = getattr(responsable_obj, "imagen_firma", None)
            if not img:
                return None
            try:
                path = img.path
            except Exception:
                path = os.path.join(settings.MEDIA_ROOT, str(img))

            if path and os.path.isfile(path):
                return path
            return None

        def _asegurar_jpg_rgb(path_img):
            base, _ext = os.path.splitext(path_img)
            path_jpg = base + "_rgb.jpg"

            if os.path.isfile(path_jpg):
                return path_jpg

            im = PILImage.open(path_img)

            if im.mode in ("RGBA", "LA", "P"):
                im = im.convert("RGBA")
                bg = PILImage.new("RGB", im.size, (255, 255, 255))
                alpha = im.split()[-1]
                bg.paste(im, mask=alpha)
                bg.save(path_jpg, "JPEG")
            else:
                im.convert("RGB").save(path_jpg, "JPEG")

            return path_jpg

        # --- Dibujo de las firmas ---
        for idx, o in enumerate(responsables):
            # Centro X de la columna actual
            col_left = left_margin + (idx * col_w)
            col_center = col_left + (col_w / 2.0)

            # --- Imagen de firma ---
            firma_path = _resolver_path_firma(o)
            if firma_path:
                try:
                    firma_rgb = _asegurar_jpg_rgb(firma_path)
                    p.drawImage(
                        firma_rgb,
                        col_center - (img_w / 2.0),
                        y_img,
                        width=img_w,
                        height=img_h
                    )
                except Exception as e:
                    print("Error procesando firma:", firma_path, "->", e)

            # --- Línea de firma ---
            p.setFillColorRGB(0, 0, 0)
            p.setFont("baske_negrita", 11)

            base_firma = "___________________"
            base_firma_width = stringWidth(base_firma, "libre_franklin_light", 11)
            p.drawString(col_center - (base_firma_width / 2.0), y_line, base_firma)

            # --- Nombre y cargos ---
            primera_linea = f"{(o.cargo or '').strip()} {(o.nombre or '').strip()} {(o.apellido or '').strip()}".strip()
            p.setFillColorRGB(0, 0, 0)
            p.setFont("libre_franklin_light", 11)
            primera_linea_width = stringWidth(primera_linea, "libre_franklin_light", 11)
            p.drawString(col_center - (primera_linea_width / 2.0), y_name, primera_linea)

            p.setFont("libre_franklin_light", 8)

            segunda_linea = (o.cargo_2 or "").strip()
            if segunda_linea:
                w2 = stringWidth(segunda_linea, "libre_franklin_light", 8)
                p.drawString(col_center - (w2 / 2.0), y_cargo2, segunda_linea)

            tercera_linea = (o.cargo_3 or "").strip()
            if tercera_linea:
                w3 = stringWidth(tercera_linea, "libre_franklin_light", 8)
                p.drawString(col_center - (w3 / 2.0), y_cargo3, tercera_linea)

        return p

    # def firmas_web_nuevo(self, p, curso):
    #     """
    #     Genera las firmas del PDF para diplomas web.
    #     No pierde funcionalidades: dibuja imagen + línea + textos como antes.
    #     """

    #     responsables_qs = Responsable.objects.filter(cursos=curso.id_curso).order_by('-id')
    #     responsable_cantidad = responsables_qs.count()

    #     if responsable_cantidad == 0:
    #         return p  # sin responsables no dibuja nada, pero no rompe

    #     nuevo_width = PAGE_HEIGHT / responsable_cantidad
    #     offset = 80

    #     for o in responsables_qs:
    #         # --- firma (si corresponde)
    #         if getattr(curso, 'firma', None) and getattr(o, 'imagen_firma', None):
    #             # Construir path absoluto real (evita "/home/.../" pelado)
    #             firma_rel = str(o.imagen_firma).lstrip('/')
    #             firma_abs = os.path.join(settings.BASE_DIR, firma_rel) if not firma_rel.startswith('/home/') else firma_rel

    #             if os.path.isfile(firma_abs):
    #                 # Convertir a JPG sin alfa en temp file (evita pisadas concurrentes)
    #                 with PILImage.open(firma_abs) as im:
    #                     if im.mode in ("RGBA", "LA", "P"):
    #                         im = im.convert("RGBA")
    #                         bg = PILImage.new("RGB", im.size, (255, 255, 255))
    #                         bg.paste(im, mask=im.split()[3])
    #                         out = bg
    #                     else:
    #                         out = im.convert("RGB")

    #                     fd, tmpjpg = tempfile.mkstemp(suffix=".jpg")
    #                     os.close(fd)
    #                     try:
    #                         out.save(tmpjpg, "JPEG", quality=90)
    #                         p.drawImage(
    #                             tmpjpg,
    #                             (nuevo_width + offset - 70) / 2.0,
    #                             87,
    #                             width=70,
    #                             height=70
    #                         )
    #                     finally:
    #                         try:
    #                             os.remove(tmpjpg)
    #                         except Exception:
    #                             pass

    #         # --- línea + textos (igual que antes)
    #         p.setFont('baske_negrita', 11)
    #         p.setFillColorRGB(0, 0, 0)

    #         base_firma = '___________________'
    #         base_firma_width = stringWidth(base_firma, 'libre_franklin_light', 11)
    #         p.drawString((nuevo_width + offset - base_firma_width) / 2.0, 90, base_firma)

    #         primera_linea = f"{o.cargo} {o.nombre} {o.apellido}".strip()
    #         primera_linea_width = stringWidth(primera_linea, 'libre_franklin_light', 11)
    #         p.drawString((nuevo_width + offset - primera_linea_width) / 2.0, 70, primera_linea)

    #         p.setFont('libre_franklin_light', 8)

    #         if o.cargo_2:
    #             segunda_linea = o.cargo_2
    #             w = stringWidth(segunda_linea, 'libre_franklin_light', 8)
    #             p.drawString((nuevo_width + offset - w) / 2.0, 60, segunda_linea)

    #         if o.cargo_3:
    #             tercera_linea = o.cargo_3
    #             w = stringWidth(tercera_linea, 'libre_franklin_light', 8)
    #             p.drawString((nuevo_width + offset - w) / 2.0, 50, tercera_linea)

    #         offset = offset + nuevo_width + 300

    #     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
        


    pass