Exemplo n.º 1
0
    def convertImage(self, node):
        logger.warn("Adding box instead of image.")
        getAttr = node.getAttribute
        x, y, width, height = map(getAttr, ('x', 'y', "width", "height"))
        x, y, width, height = map(self.attrConverter.convertLength,
                                  (x, y, width, height))
        xlink_href = node.attrib.get('{http://www.w3.org/1999/xlink}href')

        magic = "data:image/jpeg;base64"
        if xlink_href[:len(magic)] == magic:
            pat = "data:image/(\w+?);base64"
            ext = re.match(pat, magic).groups()[0]
            jpeg_data = base64.decodestring(
                xlink_href[len(magic):].encode('ascii'))
            _, path = tempfile.mkstemp(suffix='.%s' % ext)
            with open(path, 'wb') as fh:
                fh.write(jpeg_data)
            img = Image(int(x), int(y + height), int(width), int(-height),
                        path)
            # this needs to be removed later, not here...
            # if exists(path): os.remove(path)
        else:
            xlink_href = os.path.join(os.path.dirname(self.svg_source_file),
                                      xlink_href)
            img = Image(int(x), int(y + height), int(width), int(-height),
                        xlink_href)
            try:
                # this will catch invalid image
                PDFImage(xlink_href, 0, 0)
            except IOError:
                logger.error("Unable to read the image %s. Skipping..." %
                             img.path)
                return None
        return img
Exemplo n.º 2
0
    def convertImage(self, node):
        getAttr = node.getAttribute
        x, y, width, height = map(getAttr, ('x', 'y', "width", "height"))
        x, y, width, height = map(self.attrConverter.convertLength, (x, y, width, height))
        xlink_href = node.attrib.get('{http://www.w3.org/1999/xlink}href')

        magic_re = r"^data:image/(jpeg|png);base64"
        match = re.match(magic_re, xlink_href)
        if match:
            img_format = match.groups()[0]
            image_data = base64.decodestring(xlink_href[(match.span(0)[1] + 1):].encode('ascii'))
            _, path = tempfile.mkstemp(suffix='.%s' % img_format)
            with open(path, 'wb') as fh:
                fh.write(image_data)
            img = Image(int(x), int(y + height), int(width), int(height), path)
            # this needs to be removed later, not here...
            # if exists(path): os.remove(path)
        else:
            xlink_href = os.path.join(os.path.dirname(self.svg_source_file), xlink_href)
            img = Image(int(x), int(y + height), int(width), int(height), xlink_href)
            try:
                # this will catch invalid image
                PDFImage(xlink_href, 0, 0)
            except IOError:
                logger.error("Unable to read the image %s. Skipping..." % img.path)
                return None
        group = Group(img)
        group.translate(0, (x + height) * 2)
        group.scale(1, -1)
        return group
Exemplo n.º 3
0
    def convertImage(self, node):
        getAttr = node.getAttribute
        x, y, width, height = map(getAttr, ('x', 'y', "width", "height"))
        x, y, width, height = map(self.attrConverter.convertLength,
                                  (x, y, width, height))
        xlink_href = node.getAttributeNS('http://www.w3.org/1999/xlink',
                                         'href')

        embedded = self.embedded_image_magic_re.match(xlink_href)
        if embedded:
            ext = embedded.groups()[0]
            data = base64.decodestring(
                xlink_href[len(embedded.group(0)):].encode('ascii'))
            _, path = tempfile.mkstemp(suffix='.%s' % ext)
            with open(path, 'wb') as fh:
                fh.write(data)
            img = Image(int(x), int(y + height), int(width), int(-height),
                        path)
            # this needs to be removed later, not here...
            # if exists(path): os.remove(path)
        else:
            xlink_href = os.path.join(os.path.dirname(self.svg_source_file),
                                      xlink_href)
            img = Image(int(x), int(y + height), int(width), int(-height),
                        xlink_href)
            try:
                # this will catch invalid image
                PDFImage(xlink_href, 0, 0)
            except IOError:
                logger.error("Unable to read the image %s. Skipping..." %
                             img.path)
                return None
        return img
def getDrawing14():
    '''test shapes.Image'''
    from reportlab.graphics.shapes import Image
    D = Drawing(400, 200)
    im0 = smallArrow()
    D.add(Image(x=0, y=0, width=None, height=None, path=im0))
    im1 = smallArrow()
    D.add(Image(x=400 - 20, y=200 - 14, width=20, height=14, path=im1))
    return D
Exemplo n.º 5
0
    def test4(self):
        "Test convert a greyscale bitmap file as Image shape into a tmp. PDF file."

        d = Drawing(110, 44)
        img = Image(0, 0, 110, 44, GSIMAGE)
        d.add(img)
        d.translate(0, 2 * 72)
        self.IMAGES.append(d)
Exemplo n.º 6
0
    def test5(self):
        "Test convert a greyscale +alpha bitmap file as Image shape into a tmp. PDF file."

        d = Drawing(48, 48)
        img = Image(0, 0, 48, 48, GAIMAGE)
        d.add(img)
        d.translate(72, 4 * 72)
        self.IMAGES.append(d)
Exemplo n.º 7
0
    def test0(self):
        "Test convert a bitmap file as Image shape into a tmp. PDF file."

        d = Drawing(110, 44)
        inPath = IMAGENAME
        img = Image(0, 0, 110, 44, inPath)
        d.add(img)
        self.IMAGES.append(img)
Exemplo n.º 8
0
def reporteContable(request):
    #suma = Pago.objects.all().aggregate(s = Sum('montoPago'))
    #valor = suma['s']
    cursor = connection.cursor()
    cursor.execute(
        " select SUM(p.\"montoPago\") as suma from conntabilidad_pago as p where TO_DATE(to_char(p.\"fechaPago\",'YYYY-MM-DD'),'YYYY-MM-DD') = current_date "
    )
    lista = cursor.fetchall()
    l = lista[0]
    valor = l[0]

    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = SimpleDocTemplate(
        buffer,
        pagesize=letter,
        title="Reporte de Ingresos",
    )

    style = getSampleStyleSheet()

    versuma = Paragraph('Total de Ingresos: ' + str(valor), style['Heading3'])
    elementos = []
    img1 = Image(0, 0, 200, 60, "CEM/imagenes/logo.PNG")
    dibujo = Drawing(30, 30)
    dibujo.add(img1)

    titulo = Paragraph('Reporte de Ingresos', style['Heading1'])
    #table
    encabezados = ('                             Doctor', '', 'Monto')
    #info_tabla = [(pago.idDoctor, pago.montoPago) for pago in Pago.objects.all()]
    #2da alternativa
    cursor2 = connection.cursor()
    cursor2.execute(
        " select d.\"primerNombreDoctor\",d.\"primerApellidoDoctor\",SUM(p.\"montoPago\") as total from \"CEM_doctor\" as d inner join conntabilidad_pago as p on d.id = p.\"idDoctor_id\" where TO_DATE(to_char(p.\"fechaPago\",'YYYY-MM-DD'),'YYYY-MM-DD') = current_date group by d.\"primerApellidoDoctor\",d.\"primerNombreDoctor\"  "
    )
    info_tabla = cursor2.fetchall()
    tabla = Table([encabezados] + info_tabla, colWidths=[100, 100, 150])
    tabla.setStyle(
        TableStyle([('GRID', (0, 0), (3, -1), 0.5, colors.dodgerblue),
                    ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
                    ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)]))
    """p=0   
    for i in Pago.objects.all():
        p = p + i.montoPago
    versuma = Paragraph(str(p),style['BodyText'])"""

    elementos.append(dibujo)
    elementos.append(titulo)
    elementos.append(Spacer(0, 15))
    elementos.append(tabla)
    elementos.append(Spacer(0, 15))
    elementos.append(versuma)
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()
    return response
Exemplo n.º 9
0
    def test2(self):
        "Test scaled Image shape adding it to a PDF page."

        inPath = IMAGENAME
        img = Image(0, 0, 110, 44, inPath)
        d = Drawing(110, 44)
        d.add(img)
        d.translate(120, 0)
        d.scale(2, 2)
        self.IMAGES.append(d)
Exemplo n.º 10
0
 def addImage(x, y, w, h):
     img = Image(x, y, w, h, IMAGENAME)
     d.add(Rect(img.x - 1,
                img.y - 1,
                img.width + 2,
                img.height + 2,
                strokeWidth=2,
                strokeColor=toColor('green'),
                fillColor=toColor('black')),
           name='bg1')
     d.add(img)
Exemplo n.º 11
0
    def test3(self):
        "Test rotated Image shape adding it to a PDF page."

        inPath = IMAGENAME
        img = Image(0, 0, 110, 44, inPath)
        d = Drawing(110, 44)
        d.add(img)
        d.translate(420, 0)
        d.scale(2, 2)
        d.rotate(45)
        IMAGES.append(d)

        IMAGES.append(None)  # used to indicate last test
Exemplo n.º 12
0
    def convertImage(self, node):
        if not haveImages:
            logger.warning(
                "Unable to handle embedded images. Maybe the pillow library is missing?"
            )
            return None

        getAttr = node.getAttribute
        x, y, width, height = map(getAttr, ('x', 'y', "width", "height"))
        x, y, width, height = map(self.attrConverter.convertLength,
                                  (x, y, width, height))

        image = node._resolved_target
        is_raster = isinstance(image, str)  # A path to a file
        if is_raster:
            image = Image(int(x), int(y + height), int(width), int(height),
                          image)

        group = Group(image)
        if is_raster:
            group.translate(0, (y + height) * 2)
            group.scale(1, -1)
        return group
Exemplo n.º 13
0
 def wrap(self, availWidth, availHeight):
     h, w = Image.wrap(self, availHeight, availWidth)
     return w, h
Exemplo n.º 14
0
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4

imaxes = []
imaxe = Image(150, 50, 589, 202, "/home/dam2a/Descargas/vaca-lechera.jpg")

debuxo = Drawing(500, 102)
debuxo.translate(0, 650)  #movelo de posición
debuxo.add(imaxe)

debuxo2 = Drawing(250, 51)
debuxo2.add(imaxe)
debuxo2.rotate(45)
debuxo2.scale(0.5, 1.5)
debuxo2.translate(150, -45)
imaxes.append(debuxo2)

imaxes.append(debuxo)
documento = Drawing(A4[0], A4[1])

for elemento in imaxes:
    documento.add(elemento)

renderPDF.drawToFile(documento, "segundoInforme.pdf")
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4

imaxes = []

imaxe = Image(400, 0, 596, 133, "/home/manuel/Imaxes/200.jpg")

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
debuxo.translate(0, 0)
imaxes.append(debuxo)

debuxo = Drawing(30, 30)
debuxo.add(imaxe)

debuxo.scale(1.5, 0.5)
debuxo.translate(-300, 300)
debuxo.rotate(45)
imaxes.append(debuxo)

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
debuxo.rotate(theta=60)
debuxo.translate(-400, 00)
imaxes.append(debuxo)

debuxo = Drawing(A4[0], A4[1])

for aux in imaxes:
    debuxo.add(aux)
Exemplo n.º 16
0
def reporteConsultas(request,pk):####################
    consulta = get_object_or_404(Consulta, pk=pk)
    if consulta.idDoctor != None:
        doctor_consulta = Doctor.objects.get(primerApellidoDoctor = consulta.idDoctor)
    else:
        doctor_consulta = Doctor.objects.none()
    if consulta.expediente != None:
        paciente_consulta = Paciente.objects.get(expediente = consulta.expediente)
    else:
        paciente_consulta = Doctor.objects.none()
    
    ##################################################
    response = HttpResponse(content_type='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename="Prueba.pdf"'
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title = "Constancia por Incapacidad")

    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment = TA_CENTER ))

    elementos = []
   # img = Image("CEM/imagenes/logo.PNG",width=200, height=50 )
   # img.hAlign = 'LEFT'
    img = Image(0,0,50,50,"CEM/imagenes/logoleft.png")#alineacion del  logo-> (rigth-moving, top-moving, weigh, heigh,"url")
    img1 = Image(350,0,100,50,"CEM/imagenes/logocem.png")
    img2 = Image(73,30,260,20,"CEM/imagenes/cemtext.jpg")
    img3 = Image(115,5,175,18,"CEM/imagenes/repconsultext.jpg")
       
    dibujo = Drawing(30,30)#margen superior e izquierdo de donde empieza el pdf
        
    dibujo.add(img)  
    dibujo.add(img1)
    dibujo.add(img2)
    dibujo.add(img3)               
    elementos.append(dibujo)

            #FORMATO  PARA UTILIZAR FECHA COMO  VARIABLES
    """meses = ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    dias = ("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo")
    ahora = datetime.now()
    #dia = ahora.strftime("%d")
    dia = dias[ahora.month-1]
    mes = meses[ahora.month-1]
    anio = ahora.strftime("%Y")"""
            #FORMATO PARA LA FECHA ACTUAL DE LA MAQUINA
    locale.setlocale(locale.LC_ALL, 'esp')#genera en espanol  la fecha 
    ahora = datetime.now()
    fecha = ahora.strftime("%A %d de %B del %Y")
    move = movText(275,-20,fecha) #move = movText(387,25,fecha) 
    elementos.append(move)
            #SE DIBUJA UNA LINEA DEBAJO DE LAS IMAGENES
    line = linea(450,0,0)
    elementos.append(line)
    elementos.append(Spacer(1,10))

            #ORDEN DE VARIABLES SEGUN consultaDatos.html
    f = consulta.fechaConsulta
    f2 = f.strftime("%d/%m/%Y")
    pacnom1 = paciente_consulta.primerNombrePaciente
    pacape1 = paciente_consulta.primerApellidoPaciente
    docnom1 = doctor_consulta.primerNombreDoctor
    docape1 = doctor_consulta.primerApellidoDoctor
    peso = paciente_consulta.pesoPaciente
    altura = paciente_consulta.alturaPaciente
    presion = consulta.presionConsulta
    temp = consulta.temperatura
    pulso = consulta.pulso
    regla = consulta.fechaUltimaRegla
    obs = consulta.observaciones
    receta = consulta.recetas
    exsol = consulta.examenesSolicitados
    repexa = consulta.reporteExamenes

                #FORMATO  PARA EL PARRAFO
    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    styleJ.fontSize = 15
    styleJ.fontName="Times-Roman"
    #styleJ.lineHeight= 1

                #PARRAFO CONCATENADO CON VARIABLES
    parrafo = "<br/><br/><br/><b>Fecha: </b>"+f2+"<br/><br/><b>Paciente: </b>"+pacnom1+" "+pacape1+"<br/><br/><b>Doctor: </b>"+docnom1+" "+docape1+"<br/><br/><b>Peso en libras: </b>"+str(peso)+"<br/><br/><b>Altura en centimetros: </b>"+str(altura)+"<br/><br/><b>Presion: </b>"+str(presion)+"<br/><br/><b>Tempreratura en grados centigrados: </b>"+str(temp)+"<br/><br/><b>Pulso: </b>"+str(pulso)+"<br/><br/><b>Observaciones: </b>"+obs+"<br/><br/><b>Recetas: </b>"+receta+"<br/><br/><b>Examenes solicitados: </b>"+exsol+"<br/><br/><b>Reporte de examenes: </b>"+repexa

    """styleC = style['Heading4']
    styleC.alignment = 1
    FYS = "firma""" #este texto es por si se usa la firma
    #elementos.append(Paragraph(FYS ,styleC)) 
   
    #elementos.append(titulo2)
    #elementos.append(Spacer(1,5))
    elementos.append(Paragraph(parrafo ,styleJ))
    elementos.append(Spacer(1,10))
    
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()  
    return response
Exemplo n.º 17
0
    def render(self, node, parent=None):
        if parent is None:
            parent = self.mainGroup

        # ignore if display = none
        display = node.get('display')
        if display == "none":
            return

        if node.tag == self.SVG_ROOT:
            self.level += 1

            if not self.drawing is None:
                raise SVGError('drawing already created!')

            self.root = node

            # default styles
            style = {
                'color': 'none',
                'fill': 'none',
                'stroke': 'none',
                'font-family': 'Helvetica',
                'font-size': '12'
            }

            self.styles[self.level] = style

            # iterate children
            for child in node:
                self.render(child, self.mainGroup)

            # create drawing
            width = node.get('width', '100%')
            height = node.get('height', '100%')

            if node.get("viewBox"):
                try:
                    minx, miny, width, height = node.get("viewBox").split()
                except ValueError:
                    raise SVGError("viewBox values not valid")

            if width.endswith('%') and height.endswith('%'):
                # handle relative size
                wscale = parseLength(width) / 100.
                hscale = parseLength(height) / 100.

                xL, yL, xH, yH = self.mainGroup.getBounds()
                self.drawing = Drawing(xH * wscale + xL, yH * hscale + yL)

            else:
                self.drawing = Drawing(parseLength(width), parseLength(height))

            height = self.drawing.height
            self.mainGroup.scale(1, -1)
            self.mainGroup.translate(0, -height)
            self.drawing.add(self.mainGroup)

            self.level -= 1

            return self.drawing

        elif node.tag in (self.SVG_G, self.SVG_A):
            self.level += 1

            # set this levels style
            style = self.styles[self.level - 1].copy()
            style = self.nodeStyle(node, style)
            self.styles[self.level] = style

            group = Group()

            # iterate children
            for child in node:
                self.render(child, group)

            parent.add(group)

            transforms = node.get('transform')
            if transforms:
                for op in parseTransform.iterparse(transforms):
                    self.applyTransformOnGroup(group, op)

            self.level -= 1

        elif node.tag == self.SVG_USE:
            self.level += 1

            # set this levels style
            style = self.styles[self.level - 1].copy()
            style = self.nodeStyle(node, style)
            self.styles[self.level] = style

            group = Group()

            # link id
            link_id = node.get(self.LINK).lstrip('#')

            # find linked node in defs or symbol section
            target = None
            for defs in self.root.getiterator(self.SVG_DEFS):
                for element in defs:
                    if element.get('id') == link_id:
                        target = element
                        break

            if target is None:
                for defs in self.root.getiterator(self.SVG_SYMBOL):
                    for element in defs:
                        if element.get('id') == link_id:
                            target = element
                            break

                if target is None:
                    msg = "Could not find use node '%s'" % link_id
                    raise SVGError(msg)

            self.render(target, group)

            parent.add(group)

            # apply transform
            transforms = node.get('transform')
            if transforms:
                for op in parseTransform.iterparse(transforms):
                    self.applyTransformOnGroup(group, op)

            # apply 'x' and 'y' attribute as translation of defs object
            if node.get('x') or node.get('y'):
                dx = parseLength(node.get('x', '0'))
                dy = parseLength(node.get('y', '0'))

                self.applyTransformOnGroup(group, ('translate', (dx, dy)))

            self.level -= 1

        elif node.tag == self.SVG_LINE:
            # get coordinates
            x1 = parseLength(node.get('x1', '0'))
            y1 = parseLength(node.get('y1', '0'))
            x2 = parseLength(node.get('x2', '0'))
            y2 = parseLength(node.get('y2', '0'))

            shape = Line(x1, y1, x2, y2)
            self.addShape(parent, node, shape)

        elif node.tag == self.SVG_RECT:
            # get coordinates
            x = parseLength(node.get('x', '0'))
            y = parseLength(node.get('y', '0'))
            width = parseLength(node.get('width'))
            height = parseLength(node.get('height'))

            rx = parseLength(node.get('rx', '0'))
            ry = parseLength(node.get('ry', '0'))

            shape = Rect(x, y, width, height, rx=rx, ry=ry)
            self.addShape(parent, node, shape)

        elif node.tag == self.SVG_CIRCLE:
            cx = parseLength(node.get('cx', '0'))
            cy = parseLength(node.get('cy', '0'))
            r = parseLength(node.get('r'))

            if r > 0.:
                shape = Circle(cx, cy, r)
                self.addShape(parent, node, shape)

        elif node.tag == self.SVG_ELLIPSE:
            cx = parseLength(node.get('cx', '0'))
            cy = parseLength(node.get('cy', '0'))
            rx = parseLength(node.get('rx'))
            ry = parseLength(node.get('ry'))

            if rx > 0. and ry > 0.:
                shape = Ellipse(cx, cy, rx, ry)
                self.addShape(parent, node, shape)

        elif node.tag == self.SVG_POLYLINE:
            # convert points
            points = node.get('points').strip()
            if len(points) == 0:
                return

            points = list(map(parseLength, re.split('[ ,]+', points)))

            # Need to use two shapes, because standard RLG polylines
            # do not support filling...
            group = Group()
            shape = Polygon(points)
            self.applyStyleToShape(shape, node)
            shape.strokeColor = None
            group.add(shape)

            shape = PolyLine(points)
            self.applyStyleToShape(shape, node)
            group.add(shape)

            self.addShape(parent, node, group)

        elif node.tag == self.SVG_POLYGON:
            # convert points
            points = node.get('points').strip()
            if len(points) == 0:
                return

            points = list(map(parseLength, re.split('[ ,]+', points)))

            shape = Polygon(points)
            self.addShape(parent, node, shape)

        elif node.tag == self.SVG_IMAGE:
            x = parseLength(node.get('x', '0'))
            y = parseLength(node.get('y', '0'))
            width = parseLength(node.get('width', '0'))
            height = parseLength(node.get('height', '0'))

            # link id
            link_id = node.get(self.LINK)

            filename = os.path.join(os.path.dirname(self.filename), link_id)
            shape = Image(x, y, width, height, filename)

            self.addShape(parent, node, shape)

        elif node.tag == self.SVG_TEXT:
            # Todo:
            # - rotation not handled
            # - baseshift not handled
            # - embedded span node not handled
            #
            def parsePos(node, subnode, name, default='0'):
                values = subnode.get(name)
                if values is None:
                    if node is not None:
                        values = node.get(name, default)
                    else:
                        values = default

                return list(map(parseLength, values.split()))

            def getPos(values, i, default=None):
                if i >= len(values):
                    if default is None:
                        return values[-1]
                    else:
                        return default
                else:
                    return values[i]

            def handleText(node, subnode, text):
                # get position variables
                xs = parsePos(node, subnode, 'x')
                dxs = parsePos(node, subnode, 'dx')
                ys = parsePos(node, subnode, 'y')
                dys = parsePos(node, subnode, 'dy')

                if sum(map(len, (xs, ys, dxs, dys))) == 4:
                    # single value
                    shape = String(xs[0] + dxs[0], -ys[0] - dys[0], text)
                    self.applyStyleToShape(shape, subnode)
                    group.add(shape)

                else:
                    # multiple values
                    for i, c in enumerate(text):
                        x = getPos(xs, i)
                        dx = getPos(dxs, i, 0)
                        y = getPos(ys, i)
                        dy = getPos(dys, i, 0)

                        shape = String(x + dx, -y - dy, c)
                        self.applyStyleToShape(shape, subnode)
                        group.add(shape)

            if node.text and node.text.strip():
                group = Group()

                handleText(None, node, node.text.strip())

                group.scale(1, -1)

                self.addShape(parent, node, group)

            if len(node) > 0:
                group = Group()

                self.level += 1

                # set this levels style
                style = self.styles[self.level - 1].copy()
                nodestylestyle = self.nodeStyle(node, style)
                self.styles[self.level] = nodestylestyle

                for subnode in node:
                    if subnode.tag == self.SVG_TSPAN:
                        handleText(node, subnode, subnode.text.strip())

                self.level -= 1

                group.scale(1, -1)
                self.addShape(parent, node, group)

        elif node.tag == self.SVG_PATH:

            def convertQuadratic(Q0, Q1, Q2):
                C1 = (Q0[0] + 2. / 3 * (Q1[0] - Q0[0]),
                      Q0[1] + 2. / 3 * (Q1[1] - Q0[1]))
                C2 = (C1[0] + 1. / 3 * (Q2[0] - Q0[0]),
                      C1[1] + 1. / 3 * (Q2[1] - Q0[1]))
                C3 = Q2
                return C1[0], C1[1], C2[0], C2[1], C3[0], C3[1]

            def prevCtrl(lastOp, lastArgs, currentX, currentY):
                # fetch last controll point
                if lastOp in 'CScsQqTt':
                    x, y = lastArgs[-2]

                    # mirror about current point
                    return currentX + (currentX - x), currentY + (currentY - y)

                else:
                    # defaults to current point
                    return currentX, currentY

            # store sub paths in 'paths' list
            shape = Path()

            # keep track of current point and path start point
            startX, startY = 0., 0.
            currentX, currentY = 0., 0.

            # keep track of last operation
            lastOp = None
            lastArgs = None

            # avoid empty path data
            data = node.get('d')
            if data is None or len(data) == 0:
                return

            for op, args in parsePath.iterparse(data):
                if op == 'z' or op == 'Z':
                    # close path or subpath
                    shape.closePath()

                    # next sub path starts at begining of current path
                    currentX, currentY = startX, startY

                elif op == 'M':
                    # moveto absolute
                    if lastOp is not None and lastOp not in ('z', 'Z'):
                        # close sub path
                        shape.closePath()

                    x, y = args[0]
                    shape.moveTo(x, y)

                    startX, startY = x, y

                    # multiple moveto arge result in line
                    for x, y in args[1:]:
                        shape.lineTo(x, y)

                    currentX, currentY = x, y

                elif op == 'm':
                    if lastOp is not None and lastOp not in ('z', 'Z'):
                        # close sub path
                        shape.closePath()

                    # moveto relative
                    rx, ry = args[0]
                    x, y = currentX + rx, currentY + ry
                    shape.moveTo(x, y)

                    startX, startY = x, y
                    currentX, currentY = x, y

                    # multiple moveto arge result in line
                    for rx, ry in args[1:]:
                        x, y = currentX + rx, currentY + ry
                        shape.lineTo(x, y)
                        currentX, currentY = x, y

                elif op == 'L':
                    # lineto absolute
                    for x, y in args:
                        shape.lineTo(x, y)

                    currentX, currentY = x, y

                elif op == 'l':
                    # lineto relative
                    for rx, ry in args:
                        x, y = currentX + rx, currentY + ry
                        shape.lineTo(x, y)
                        currentX, currentY = x, y

                elif op == 'V':
                    # vertical line absolute
                    for y in args:
                        shape.lineTo(currentX, y)

                    currentY = y

                elif op == 'v':
                    # vertical line relative
                    for ry in args:
                        y = currentY + ry
                        shape.lineTo(currentX, y)
                        currentY = y

                elif op == 'H':
                    # horisontal line absolute
                    for x in args:
                        shape.lineTo(x, currentY)
                    currentX = x

                elif op == 'h':
                    # horisontal line relative
                    for rx in args:
                        x = currentX + rx
                        shape.lineTo(x, currentY)
                    currentX = x

                elif op == 'C':
                    # cubic bezier absolute
                    for p1, p2, p3 in zip(*([iter(args)] * 3)):
                        shape.curveTo(*(p1 + p2 + p3))
                        currentX, currentY = p3

                elif op == 'c':
                    # cubic bezier relative
                    for pnts in zip(*([iter(args)] * 3)):
                        (x1, y1), (x2, y2), (x3, y3) = pnts
                        pnts = tuple(
                            (p[0] + currentX, p[1] + currentY) for p in pnts)
                        shape.curveTo(*(pnts[0] + pnts[1] + pnts[2]))
                        currentX, currentY = pnts[2]
                        lastOp = op
                        lastArgs = pnts
                    continue

                elif op == 'S':
                    # shorthand cubic bezier absolute
                    for p2, p3 in zip(*([iter(args)] * 2)):
                        x1, y1 = prevCtrl(lastOp, lastArgs, currentX, currentY)
                        x2, y2 = p2
                        x3, y3 = p3
                        shape.curveTo(x1, y1, x2, y2, x3, y3)
                        lastOp = op
                        lastArgs = (x2, y2), (x3, y3)
                        currentX, currentY = x3, y3
                    continue

                elif op == 's':
                    # shorthand cubic bezier relative
                    for p2, p3 in zip(*([iter(args)] * 2)):
                        x1, y1 = prevCtrl(lastOp, lastArgs, currentX, currentY)
                        x2, y2 = p2
                        x2, y2 = x2 + currentX, y2 + currentY
                        x3, y3 = p3
                        x3, y3 = x3 + currentX, y3 + currentY
                        shape.curveTo(x1, y1, x2, y2, x3, y3)
                        currentX, currentY = x3, y3
                        lastOp = op
                        lastArgs = (x1, y1), (x2, y2), (x3, y3)
                    continue

                elif op == 'Q':
                    # quadratic bezier absolute
                    for p2, p3 in zip(*([iter(args)] * 2)):
                        x1, y1 = currentX, currentY
                        x2, y2 = p2
                        x3, y3 = p3
                        ctrls = convertQuadratic((x1, y1), (x2, y2), (x3, y3))
                        shape.curveTo(*ctrls)
                        currentX, currentY = x3, y3
                    lastOp = op
                    lastArgs = (x2, y2), (x3, y3)
                    continue

                elif op == 'q':
                    # quadratic bezier relative
                    for p2, p3 in zip(*([iter(args)] * 2)):
                        x1, y1 = currentX, currentY
                        x2, y2 = p2
                        x2, y2 = x2 + currentX, y2 + currentY
                        x3, y3 = p3
                        x3, y3 = x3 + currentX, y3 + currentY
                        ctrls = convertQuadratic((x1, y1), (x2, y2), (x3, y3))
                        shape.curveTo(*ctrls)
                        currentX, currentY = x3, y3

                    lastOp = op
                    lastArgs = (x2, y2), (x3, y3)
                    continue

                elif op == 'T':
                    # shorthand quadratic bezier absolute
                    for i in range(len(args)):
                        x1, y1 = currentX, currentY
                        x2, y2 = prevCtrl(lastOp, lastArgs, currentX, currentY)
                        x3, y3 = args[i]
                        ctrls = convertQuadratic((x1, y1), (x2, y2), (x3, y3))
                        shape.curveTo(*ctrls)
                        currentX, currentY = x3, y3
                        lastOp = op
                        lastArgs = (x2, y2), (x3, y3)

                    continue

                elif op == 't':
                    # shorthand quadratic bezier relative
                    for i in range(len(args)):
                        x1, y1 = currentX, currentY
                        x2, y2 = prevCtrl(lastOp, lastArgs, currentX, currentY)
                        x3, y3 = args[i]
                        x3, y3 = x3 + currentX, y3 + currentY
                        ctrls = convertQuadratic((x1, y1), (x2, y2), (x3, y3))
                        shape.curveTo(*ctrls)
                        currentX, currentY = x3, y3
                        lastOp = op
                        lastArgs = (x2, y2), (x3, y3)

                    continue

                elif op == 'A' or op == 'a':
                    # elliptic arc missing
                    continue

                lastOp = op
                lastArgs = args

            # check if fill applies to path
            fill = None
            if node.get('fill'):
                # inline style
                fill = node.get('fill')
            else:
                # try local style
                if node.get('style'):
                    style = parseStyle.parse(node.get('style'))

                    if 'fill' in style:
                        fill = style['fill']

                # try global style
                if fill is None:
                    style = self.styles[self.level]

                    if 'fill' in style:
                        fill = style['fill']
                    else:
                        fill = 'none'

            # hack because RLG has no "semi-closed" paths...
            if lastOp == 'z' or lastOp == 'Z' or fill == 'none':
                self.addShape(parent, node, shape)

            else:
                group = Group()
                strokeshape = shape.copy()
                self.addShape(group, node, strokeshape, fill='none')
                shape.closePath()
                self.addShape(group, node, shape, stroke='none')
                self.addShape(parent, node, group)

        elif node.tag == self.SVG_TITLE or node.tag == self.SVG_DESC:
            # Skip non-graphics elements
            return
Exemplo n.º 18
0
def reporteDoctores(request, pk):
    doctor = get_object_or_404(Doctor, pk=pk)
    

    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title = "")

    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment = TA_CENTER ))

    elementos = []
    
    img = Image(0,0,50,50,"CEM/imagenes/logoleft.png")
    img1 = Image(350,0,100,50,"CEM/imagenes/logocem.png")
    img2 = Image(73,30,260,20,"CEM/imagenes/cemtext.png")
    img3 = Image(115,5,175,18,"CEM/imagenes/repdoctortext.png")
    #img.hAlign = 'LEFT'
    dibujo = Drawing(30,30)
    #dibujo.translate(10,10)
    styleC = style['Heading1']
    styleC.alignment = 1
    t1 = Paragraph("Reporte de Doctor",styleC)

    dibujo.add(img)
    dibujo.add(img1)
    dibujo.add(img2)
    dibujo.add(img3)                 #1
    elementos.append(dibujo)

      #FORMATO  PARA UTILIZAR FECHA COMO  VARIABLES
    """meses = ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    dias = ("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo")
    ahora = datetime.now()
    #dia = ahora.strftime("%d")
    dia = dias[ahora.month-1]
    mes = meses[ahora.month-1]
    anio = ahora.strftime("%Y")"""
    
            #FORMATO PARA LA FECHA ACTUAL DE LA MAQUINA
    locale.setlocale(locale.LC_ALL, 'esp')#genera en espanol  la fecha 
    ahora = datetime.now()
    fecha = ahora.strftime("%A %d de %B del %Y")
    move = movText(275,-20,fecha) #move = movText(387,25,fecha) 
    elementos.append(move)
            #SE DIBUJA UNA LINEA DEBAJO DE LAS IMAGENES
    line = linea(450,0,0)
    elementos.append(line)
    elementos.append(Spacer(1,10))
        
             #ORDEN DE VARIABLES SEGUN consultaDatos.html
    drnom1 = doctor.primerNombreDoctor
    drnom2 = doctor.segundoNombreDoctor
    drape1 = doctor.primerApellidoDoctor
    drape2 = doctor.segundoApellidoDoctor
    dresp = doctor.especialidad
    drsex = doctor.sexoDoctor
    drfecha = doctor.fechaNacimientoDoctor
    drtele = doctor.telefonoDoctor
    email = doctor.correoElectronico
    dui = doctor.duiDoctor
    nit = doctor. nitDoctor
    nc = doctor.ncfDoctor
    foto = doctor.fotografiaDoctor
   

   #FORMATO  PARA EL PARRAFO
    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    styleJ.fontSize = 15
    styleJ.fontName="Times-Roman"
    #styleJ.lineHeight= 1

                #PARRAFO CONCATENADO CON VARIABLES
    parrafo = "<br/><br/><br/><b>DATOS DE DOCTOR </b><br/><br/><br/><br/><b>Nombre: </b>"+drnom1+" "+drape1+"<br/><br/><br/><b>Especialidad: </b>"+dresp+"<br/><br/><br/><b>Fecha de Nacimiento: </b>"+str(drfecha)+"<br/><br/><br/><b>Telefono: </b>"+drtele+"<br/><br/><br/><b>Correo electronico: </b>"+email+"<br/><br/><br/><b>DUI: </b>"+dui+"<br/><br/><br/><b>NIT: </b>"+nit+"<br/><br/><br/><b>NCF: </b>"+nc

    """styleC = style['Heading4']
    styleC.alignment = 1
    FYS = "firma""" #este texto es por si se usa la firma
    #elementos.append(Paragraph(FYS ,styleC)) 
   
    elementos.append(Paragraph(parrafo ,styleJ))
    elementos.append(Spacer(1,10))
    
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()  
    return response
Exemplo n.º 19
0
    def test1(self):
        "Test Image shape, adding it to a PDF page."

        inPath = IMAGENAME
        img = Image(0, 0, 110, 44, inPath)
        self.IMAGES.append(img)
Exemplo n.º 20
0
def reporteDoctorConstancia(request,pk):
    consulta = get_object_or_404(Consulta, pk=pk)
    if consulta.idDoctor != None:
        doctor_consulta = Doctor.objects.get(primerApellidoDoctor = consulta.idDoctor)
    else:
        doctor_consulta = Doctor.objects.none()
    if consulta.expediente != None:
        paciente_consulta = Paciente.objects.get(expediente = consulta.expediente)
    else:
        paciente_consulta = Doctor.objects.none()

    response = HttpResponse(content_type='application/pdf')
    #response['Content-Disposition'] = 'filename="Prueba.pdf"'
    #response['Content-Disposition'] = 'filename="{}"'.format(file_name)
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title="Constancia Medica",
                            leftMargin=2*cm,
                            )

    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment = TA_CENTER ))
    nomApe = paciente_consulta.primerNombrePaciente +" "+ paciente_consulta.primerApellidoPaciente 
    nomApeD = doctor_consulta.primerNombreDoctor +" "+ doctor_consulta.primerApellidoDoctor
    #meses = ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    ahora = datetime.now()
    dia = ahora.strftime("%d")
    #mesLetra = meses[ahora.month-1]
    mesNumero = ahora.strftime("%m")
    anio = ahora.strftime("%Y")
    locale.setlocale(locale.LC_ALL,'esp')
    fech = ahora.strftime("%A %d de %B del  %Y.")
    elementos = []
    titulo1=Paragraph('<para align=center>CLINICA DE ESPECIALIDADES MEDICAS</para>',style['Heading3'])
    titulo2=Paragraph('<para align=center>CONSTANCIA MEDICA</para>',style['Heading3'])
    #img1 = Image("CEM/imagenes/logo1.PNG",width=70, height=70 )
    img1 = Image(0,25,90,60,"CEM/imagenes/logo1RepDoc.PNG")

    img2 = Image(375,25,135,60,"CEM/imagenes/logo2RepDoc.PNG")
    dibujo = Drawing(30,30)
    dibujo.add(img1)
    dibujo2 = Drawing(0,0)
    dibujo2.add(img2)
    line= lineaRD(15,-15,488)
 
    #title = Paragraph('<para align=center><b>Industry Earnings Call Transcripts Report</b></para>',style['Normal'])
    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    parrafo = "A quien el interese <br/><br/><br/> Por medio de la presente se hace constar que el (la) paciente: <b>"+nomApe+"</b> paso consulta con el Doctor(a) <b>"+ nomApeD + "</b> el dia " + dia +"/"+ mesNumero +"/"+ anio+"."                        
    styleC = style['Heading3']
    styleC.alignment = 1
    doc = "Dr.(a) "+ nomApeD +" "
    line2 = lineaRD(100,0,372)
    #texInferior1=Paragraph("<para color=red >Hospital &emsp; instituto de ojos local 2-40<br/>Boulevard Tutunichapa Sas Salvador</para>",style['BodyText'])
    #texInferior2=Paragraph("<para color=red >Telefono:2517-9097/2556-5236 Celular. 7237-1722 <br/>[email protected]</para>",style['BodyText'])

    
    elementos.append(titulo1)
    elementos.append(titulo2)
    elementos.append(Spacer(1,15))
    elementos.append(line)    
    elementos.append(dibujo)
    elementos.append(dibujo2)
    elementos.append(Spacer(1,20))
    elementos.append(Paragraph("<para align=right >"+fech+"</para>",style['BodyText']))
    elementos.append(Spacer(1,20))
    elementos.append(Paragraph(parrafo,styleJ))
    elementos.append(Spacer(1,80))
    elementos.append(line2)
    elementos.append(Paragraph(doc,styleC))
    #elementos.append(Spacer(1,290))
    #elementos.append(texInferior1)
    #elementos.append(texInferior2)
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()  
    return response
Exemplo n.º 21
0
def reporteDoctorIncapacidad(request,pk):
    consulta = get_object_or_404(Consulta, pk=pk)
    if consulta.idDoctor != None:
        doctor_consulta = Doctor.objects.get(primerApellidoDoctor = consulta.idDoctor)
    else:
        doctor_consulta = Doctor.objects.none()
    if consulta.expediente != None:
        paciente_consulta = Paciente.objects.get(expediente = consulta.expediente)
    else:
        paciente_consulta = Doctor.objects.none()

    ##################################################
    response = HttpResponse(content_type='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename="Prueba.pdf"'
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title = "Constancia por Incapacidad",
                            leftMargin=2*cm)

    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment = TA_CENTER ))

    elementos = []
    titulo1=Paragraph('<para align=center>CLINICA DE ESPECIALIDADES MEDICAS</para>',style['Heading3'])
    titulo2=Paragraph('<para align=center>CONSTANCIA MEDICA POR INCAPACIDAD </para>',style['Heading3'])
    #img1 = Image("CEM/imagenes/logo1.PNG",width=70, height=70 )
    img1 = Image(0,25,90,60,"CEM/imagenes/logo1RepDoc.PNG")
    img2 = Image(375,25,135,60,"CEM/imagenes/logo2RepDoc.PNG")

    dibujo = Drawing(30,30)
    dibujo.add(img1)
    dibujo2 = Drawing(0,0)
    dibujo2.add(img2)
    line= lineaRD(15,-15,488)
    #styleC = style['Heading3']
    #styleC.alignment = 0
    #titulo2 = Paragraph("A quien Corresponda",styleC)

    f = consulta.fechaConsulta
    f2 = f.strftime("%d/%m/%Y")
    nom1P = paciente_consulta.primerNombrePaciente
    ape1P = paciente_consulta.primerApellidoPaciente
    exp = paciente_consulta.expediente
    nom1D = doctor_consulta.primerNombreDoctor
    ape1D = doctor_consulta.primerApellidoDoctor
    especialidad = doctor_consulta.especialidad
    observaciones = consulta.observaciones
    meses = ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    ahora = datetime.now()
    dia = ahora.strftime("%d")
    mes = meses[ahora.month-1]
    anio = ahora.strftime("%Y")

    locale.setlocale(locale.LC_ALL,'esp')
    fech = ahora.strftime("%A %d de %B del  %Y.")

    ######
    incapCant = consulta.incapacidadCantidad
    incapTiempo = consulta.incapacidadTiempo

    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    parrafo = "<b>A quien le interese</b><br/><br/><br/>El infrascrito Medico "+ especialidad +" "+ nom1D + " "+ ape1D +" de la Clinica de Especialidades Medicas CEM, por medio de la presente hago constar que el señor(a) <b>" + nom1P + " " + ape1P + "</b> con expediente clinico numero <b>"+exp+"</b> quien presenta: "+ observaciones +" Se le indicó tratamiento y reposo por " + str(incapCant) + " "+ str(incapTiempo) +" a partir de la presente fecha "+ f2+""
    
    
    line2 = lineaRD(100,0,372)
    styleC = style['Heading4']
    styleC.alignment = 1
    FYS = "Firma y Sello"
    elementos.append(titulo1)
    elementos.append(titulo2)
    elementos.append(Spacer(1,15))
    elementos.append(line)    
    elementos.append(dibujo)
    elementos.append(dibujo2)
    elementos.append(Spacer(1,20))
    elementos.append(Paragraph("<para align=right >"+fech+"</para>",style['BodyText']))
    elementos.append(Spacer(1,20))
    elementos.append(Paragraph(parrafo ,styleJ))
    elementos.append(Spacer(1,70))
    elementos.append(line2)
    elementos.append(Paragraph(FYS ,styleC))
    elementos.append(Paragraph("Dr.(a) "+ nom1D+ " "+ape1D +" " ,styleC))


    #atr1 = Paragraph(Doctor.primerNombreDoctor,style['Heading2'])
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()  
    return response	
Exemplo n.º 22
0
def reportePacientes(request, pk):
    paciente = get_object_or_404(Paciente, pk=pk)
   
    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title = "")

    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment = TA_CENTER ))

    elementos = []
    
    img = Image(0,0,50,50,"CEM/imagenes/logoleft.png")
    img1 = Image(350,0,100,50,"CEM/imagenes/logocem.png")
    img2 = Image(73,30,260,20,"CEM/imagenes/cemtext.png")
    img3 = Image(115,5,175,18,"CEM/imagenes/reppacientetext.png")
    #img.hAlign = 'LEFT'
    dibujo = Drawing(30,30)
    #dibujo.translate(10,10)
    styleC = style['Heading1']
    styleC.alignment = 1
    t1 = Paragraph("Reporte de Doctor",styleC)

    dibujo.add(img)
    dibujo.add(img1)
    dibujo.add(img2)
    dibujo.add(img3)                 #1
    elementos.append(dibujo)

      #FORMATO  PARA UTILIZAR FECHA COMO  VARIABLES
    """meses = ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    dias = ("Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo")
    ahora = datetime.now()
    #dia = ahora.strftime("%d")
    dia = dias[ahora.month-1]
    mes = meses[ahora.month-1]
    anio = ahora.strftime("%Y")"""
    
            #FORMATO PARA LA FECHA ACTUAL DE LA MAQUINA
    locale.setlocale(locale.LC_ALL, 'esp')#genera en espanol  la fecha 
    ahora = datetime.now()
    fecha = ahora.strftime("%A %d de %B del %Y")
    move = movText(275,-20,fecha) #move = movText(387,25,fecha) 
    elementos.append(move)
            #SE DIBUJA UNA LINEA DEBAJO DE LAS IMAGENES
    line = linea(450,0,0)
    elementos.append(line)
    elementos.append(Spacer(1,10))
        
             #ORDEN DE VARIABLES SEGUN consultaDatos.html
    pexp=paciente.expediente
    dres=paciente.doctores
    pnom1=paciente.primerNombrePaciente
    pnom2=paciente.segundoNombrePaciente
    pape1=paciente.primerApellidoPaciente
    pape2=paciente.segundoApellidoPaciente
    psexo=paciente.sexoPaciente
    pfnac=paciente.fechaNacimientoPaciente
    paltura=paciente.alturaPaciente
    ppeso=paciente.pesoPaciente
    ptel=paciente.telefonoPaciente
    pfoto=paciente.fotografiaPaciente
    pinst=paciente.institucion
    pase=paciente.aseguradora
    paler=paciente.alergias
    pprov=paciente.lugarProveniencia
    """ptaba=paciente.tabquista
    peti=paciente.etilista
    phiper=paciente.hipertenso
    pdiab=paciente.diabetico
    ptuber=paciente.tuberculosis
    pane=paciente.anemia
    pconvul=paciente.convulsiones
    pcanc=paciente.cancer
    plugcanc=paciente.lugarCancer
    ptratcanc=paciente.tratamientoCancer"""
    pantec=paciente.antecedentes
   

   #FORMATO  PARA EL PARRAFO
    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    styleJ.fontSize = 15
    styleJ.fontName="Times-Roman"
    #styleJ.lineHeight= 1

                #PARRAFO CONCATENADO CON VARIABLES
    parrafo = "<br/><br/><br/><b>DATOS DE PACIENTE </b><br/><br/><br/><br/><b>Numero de expediente:    </b>"+str(pexp)+"<br/><br/><br/><b>Nombre:</b>"+pnom1+" "+pape1+"<br/><br/><br/><b>Fecha de Nacimiento: </b>"+str(pfnac)+"<br/><br/><br/><b>Altura: </b>"+str(paltura)+"<br/><br/><br/><b>Peso: </b>"+str(ppeso)+"<br/><br/><br/><b>Telefono: </b>"+str(ptel)+"<br/><br/><br/><b>Institucion de proveniencia: </b>"+str(pinst)+"<br/><br/><br/><b>Aseguradora: </b>"+str(pase)+"<br/><br/><br/><b>Alergias: </b>"+str(paler)+"<br/><br/><br/><b>Domicilio: </b>"+str(pprov)+"<br/><br/><br/><b>Antecedentes: </b>"+str(pantec)

    """styleC = style['Heading4']
    styleC.alignment = 1
    FYS = "firma""" #este texto es por si se usa la firma
    #elementos.append(Paragraph(FYS ,styleC)) 
   
    elementos.append(Paragraph(parrafo ,styleJ))
    elementos.append(Spacer(1,10))

    
    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()  
    return response
Exemplo n.º 23
0
 def draw(self):
     self.canv.rotate(90)
     Image.draw(self)
Exemplo n.º 24
0
 def drawChart(self, xSize, ySize, pieName):
     d = Drawing(xSize, ySize)
     im = Image(0, 0, xSize, ySize, pieName)
     d.add(im)
     return d
Exemplo n.º 25
0
    def __init__(self, specification, drawing_callable, pages_to_draw=None,
            border=False, shade_missing=False, direction="across"):
        """
        Parameters
        ----------
        specification: labels.Specification instance
            The sizes etc of the label sheets.
        drawing_callable: callable
            A function (or other callable object) to call to draw an individual
            label. It will be given four parameters specifying the label. In
            order, these are a `reportlab.graphics.shapes.Drawing` instance to
            draw the label on, the width of the label, the height of the label,
            and the object to draw. The dimensions will be in points, the unit
            of choice for ReportLab.
        pages_to_draw: list of positive integers, default None
            The list pages to actually draw labels on. This is intended to be
            used with the preview methods to avoid drawing labels that will
            never be displayed. A value of None means draw all pages.
        border: Boolean, default False
            Whether or not to draw a border around each label.
        shade_missing: Boolean or ReportLab colour, default False
            Whether or not to shade missing labels (those specified through the
            partial_pages method). False means leave the labels unshaded. If a
            ReportLab colour is given, the labels will be shaded in that colour.
            A value of True will result in the missing labels being shaded in
            the hex colour 0xBBBBBB (a medium-light grey).
        direction: String, either "across" or "down" to indication the order
            labels will be assigned. Default is across.

        Notes
        -----
        If you specify a pages_to_draw list, pages not in that list will be
        blank since the drawing function will not be called on that page. This
        could have a side-affect if you rely on the drawing function modifying
        some global values. For example, in the nametags.py and preview.py demo
        scripts, the colours for each label are picked by a pseduo-random number
        generator. However, in the preview script, this generator is not
        advanced and so the colours on the last page differ between the preview
        and the actual output.

        """
        # Save our arguments.
        specification._calculate()
        self.specs = deepcopy(specification)
        self.drawing_callable = drawing_callable
        self.pages_to_draw = pages_to_draw
        self.border = border
        if shade_missing == True:
            self.shade_missing = colors.HexColor(0xBBBBBB)
        else:
            self.shade_missing = shade_missing

        # Set up some internal variables.
        self._lw = self.specs.label_width * mm
        self._lh = self.specs.label_height * mm
        self._cr = self.specs.corner_radius * mm
        self._dw = (self.specs.label_width - self.specs.left_padding - self.specs.right_padding) * mm
        self._dh = (self.specs.label_height - self.specs.top_padding - self.specs.bottom_padding) * mm
        self._lp = self.specs.left_padding * mm
        self._bp = self.specs.bottom_padding * mm
        self._pr = self.specs.padding_radius * mm
        self._used = {}
        self._pages = []
        self._current_page = None

        # Page information.
        self._pagesize = (float(self.specs.sheet_width*mm), float(self.specs.sheet_height*mm))
        self._numlabels = (self.specs.rows, self.specs.columns)
        self._position = None
        self.label_count = 0
        self.page_count = 0
        if direction == "vertical":
            self._positionIteratorFunc = specification.verticalPosIterator
        else:
            self._positionIteratorFunc = specification.horizontalPosIterator

        # Background image.
        if self.specs.background_image:
            self._bgimage = deepcopy(self.specs.background_image)

            # Different classes are scaled in different ways...
            if isinstance(self._bgimage, Image):
                self._bgimage.x = 0
                self._bgimage.y = 0
                self._bgimage.width = self._pagesize[0]
                self._bgimage.height = self._pagesize[1]
            elif isinstance(self._bgimage, Drawing):
                self._bgimage.shift(0, 0)
                self._bgimage.scale(self._pagesize[0]/self._bgimage.width, self._pagesize[1]/self._bgimage.height)
            else:
                raise ValueError("Unhandled background type.")

        # Background from a filename.
        elif self.specs.background_filename:
            self._bgimage = Image(0, 0, self._pagesize[0], self._pagesize[1], self.specs.background_filename)

        # No background.
        else:
            self._bgimage = None

        # Borders and clipping paths. We need two clipping paths; one for the
        # label as a whole (which is identical to the border), and one for the
        # available drawing area (i.e., after taking the padding into account).
        # This is necessary because sometimes the drawing area can extend
        # outside the border at the corners, e.g., if there is left padding
        # only and no padding radius, then the 'available' area corners will be
        # square and go outside the label corners if they are rounded.

        # Copy some properties to a local scope.
        h, w, r = float(self._lh), float(self._lw), float(self._cr)

        # Create the border from a path. If the corners are not rounded, skip
        # adding the arcs.
        border = ArcPath()
        if r:
            border.moveTo(w - r, 0)
            border.addArc(w - r, r, r, -90, 0)
            border.lineTo(w, h - r)
            border.addArc(w - r, h - r, r, 0, 90)
            border.lineTo(r, h)
            border.addArc(r, h - r, r, 90, 180)
            border.lineTo(0, r)
            border.addArc(r, r, r, 180, 270)
            border.closePath()
        else:
            border.moveTo(0, 0)
            border.lineTo(w, 0)
            border.lineTo(w, h)
            border.lineTo(0, h)
            border.closePath()

        # Set the properties and store.
        border.isClipPath = 0
        border.strokeWidth = 1
        border.strokeColor = colors.black
        border.fillColor = None
        self._border = border

        # Clip path for the label is the same as the border.
        self._clip_label = deepcopy(border)
        self._clip_label.isClipPath = 1
        self._clip_label.strokeColor = None
        self._clip_label.fillColor = None

        # If there is no padding (i.e., the drawable area is the same as the
        # label area) then we can just use the label clip path for the drawing
        # clip path.
        if (self._dw == self._lw) and (self._dh == self._lh):
            self._clip_drawing = self._clip_label

        # Otherwise we have to generate a separate path.
        else:
            h, w, r = float(self._dh), float(self._dw), float(self._pr)
            clip = ArcPath()
            if r:
                clip.moveTo(w - r, 0)
                clip.addArc(w - r, r, r, -90, 0)
                clip.lineTo(w, h - r)
                clip.addArc(w - r, h - r, r, 0, 90)
                clip.lineTo(r, h)
                clip.addArc(r, h - r, r, 90, 180)
                clip.lineTo(0, r)
                clip.addArc(r, r, r, 180, 270)
                clip.closePath()
            else:
                clip.moveTo(0, 0)
                clip.lineTo(w, 0)
                clip.lineTo(w, h)
                clip.lineTo(0, h)
                clip.closePath()

            # Set the clipping properties.
            clip.isClipPath = 1
            clip.strokeColor = None
            clip.fillColor = None
            self._clip_drawing = clip
Exemplo n.º 26
0
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4

# Lista de objetos
guion = []

# Similar al anterior ejercicio, introducir una imagen
# Se le pasa en este orden
# Posicion x, posicion y , ancho y alto de la imagen y path de la imagen
imaxe = Image(0, 00, 300, 300, "/home/dam2/Imágenes/bed14325-5a43-48d4-a1d9-8c1b3541a5d3-profile_image-300x300.jpeg")

# Ahora a partir de la imagen se crea el dibujo
debuxo = Drawing(30, 30)
# Al dibujo se le ha añadido la imagen
debuxo.add(imaxe)
debuxo.translate(0, 600)
# A nuestra lista de objetos se le ha añadido un nuevo objeto
guion.append(debuxo)

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
# Esto rota la imagen 45 grados
debuxo.rotate(45)
guion.append(debuxo)
# Escala para X e Y
debuxo.scale(1.5, 0.5)
guion.append(debuxo)
# Se mueve de sitio la imagen
debuxo.translate(-90, 300)
guion.append(debuxo)
Exemplo n.º 27
0
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4

guion = []

imaxe = Image(400, 10, 596, 133, "ruta")

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
debuxo.translate(0, 600)
guion.append(debuxo)

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
debuxo.rotate(45)
debuxo.scale(1.5, 0.5)
debuxo.translate(-90, 300)
guion.append(debuxo)

debuxo = Drawing(30, 30)
debuxo.add(imaxe)
debuxo.rotate(90)
debuxo.translate(-20, -100)
guion.append(debuxo)

debuxo = Drawing(A4[0], A4[1])  # ancho y alto a4
for deb in guion:
    debuxo.add(deb)

renderPDF.drawToFile(debuxo, "proba2.pdf")
Exemplo n.º 28
0
def generaServicios():
    """Xeramos o informe dos Servizos usando as librerias de reportlab

            Crease unha lista 'paxina' a que lle engadiremos os elementos seguintes:

            imaxe -- engadimos unha imaxe cos parametros(desplazamentoX,desplazamentoY,ancho,alto)

            debuxo -- indicaremos a posicion na que situaremos a imaxe cos parametros (ancho,alto)

            debuxo.add(imaxe) -- engade a imaxe ao noso debuxo

            paxina.append(debuxo) -- engade o debuxo a nosa paxina
            -------------------------------------------------------------------------------------------
            A continuación crearemos a conexion a nosa base de datos:

            bbdd = dbapi.connect("Clinica.dat") -- conecta a base de datos "Clinica.dat"

            cursor = bbdd.cursor() -- creamos un cursor para executar ordes sobre as taboas
            -------------------------------------------------------------------------------------------
            Pasamos a xerar a tabla no noso informe:

            columnas -- Creamos as columnas da nosa taboa

            cursor.execute -- executa a operacion sql deseada

            taboa -- creamos unha taboa a que lle pasamos as columnas e o resultado da nosa consulta

            taboa.setStyle -- define o estilo da nosa taboa

            paxina.append(taboa) -- engade a taboa a nosa paxina
            --------------------------------------------------------------------------------------------
            Por ultimo xeramos o documento pdf para iso debemos realizar o seguinte:

            *SimpleDocTemplate -- ao que lle pasamos(nome do pdf a xerar,formato da paxina,e borde)

            *debemos pasarlle unha referencia

             doc.build(paxina) -- Xera o informe coa configuracion anterior

         """
    try:
        paxina = []

        imaxe = Image(80, 50, 280, 150,
                      "logo.png")  # x lateral y horizontal ancho y alto
        debuxo = Drawing(300, 200)
        debuxo.add(imaxe)
        paxina.append(debuxo)  # añadimos dibujo a la lista

        bbdd = dbapi.connect("Clinica.dat")
        cursor = bbdd.cursor()

        columnas = [["Servicio", "Precio"]]

        cursor.execute("select * from servicios")
        taboa = Table(columnas + cursor.fetchall())  # recupera los datos

        taboa.setStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("BACKGROUND", (0, 0), (-1, -1), colors.lightcyan),
            ("BACKGROUND", (0, 0), (5, 0), colors.lightgreen),
        ])

        paxina.append(taboa)

        doc = SimpleDocTemplate("informeServicio.pdf",
                                pagesize=A4,
                                showBoundary=1)  # boundary linea a4
        doc.build(paxina)

    except dbapi.OperationalError as e:
        print("problema " + str(e))
Exemplo n.º 29
0
def reporteCM(request):
    evento = get_object_or_404(Event)
    if evento.idDoctor != None:
        doctor_consulta = Doctor.objects.get(
            primerApellidoDoctor=evento.idDoctor)
    else:
        doctor_consulta = Doctor.objects.none()
    if evento.expediente != None:
        paciente_consulta = Paciente.objects.get(expediente=evento.expediente)
    else:
        paciente_consulta = Doctor.objects.none()
    ##################################################
    response = HttpResponse(content_type='application/pdf')
    buffer = BytesIO()
    pdf = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            title="AVISO DE CITA MEDICA")
    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='centro', alignment=TA_CENTER))

    elementos = []
    img = Image(
        0, 0, 50, 50, "CEM/imagenes/logoleft.png"
    )  #alineacion del  logo-> (rigth-moving, top-moving, weigh, heigh,"url")
    img1 = Image(350, 0, 100, 50, "CEM/imagenes/logocem.png")
    img2 = Image(73, 30, 260, 20, "CEM/imagenes/cemtext.jpg")
    img3 = Image(115, 5, 175, 18, "CEM/imagenes/citamedica.jpg")

    dibujo = Drawing(30,
                     30)  #margen superior e izquierdo de donde empieza el pdf
    dibujo.add(img)
    dibujo.add(img1)
    dibujo.add(img2)
    dibujo.add(img3)
    elementos.append(dibujo)
    #FORMATO PARA LA FECHA ACTUAL DE LA MAQUINA
    locale.setlocale(locale.LC_ALL, 'esp')  #genera en espanol  la fecha
    ahora = datetime.now()
    fecha = ahora.strftime("%A %d de %B del %Y")
    move = movText(275, -20, fecha)  #move = movText(387,25,fecha)
    elementos.append(move)
    #SE DIBUJA UNA LINEA DEBAJO DE LAS IMAGENES
    line = linea(450, 0, 0)
    elementos.append(line)
    elementos.append(Spacer(1, 10))
    #ORDEN DE VARIABLES SEGUN consultaDatos.html
    pacnom1 = paciente_consulta.primerNombrePaciente
    pacape1 = paciente_consulta.primerApellidoPaciente
    docnom1 = doctor_consulta.primerNombreDoctor
    docape1 = doctor_consulta.primerApellidoDoctor
    titulo = evento.title
    desc = evento.description
    fstar = evento.start_time
    fend = evento.end_time
    #FORMATO  PARA EL PARRAFO
    styleJ = style['BodyText']
    styleJ.alignment = TA_JUSTIFY
    styleJ.fontSize = 11
    styleJ.fontName = "Times-Roman"
    #styleJ.lineHeight= 1
    #PARRAFO CONCATENADO CON VARIABLES
    parrafo = "<br/><br/><br/><b>EL PACIENTE: </b>" + pacnom1 + " " + pacape1 + "<br/><br/><br/><b>TIENE UNA CITA CON EL DOCTOR: </b>" + docnom1 + " " + docape1 + "<br/><br/><br/><b>CON TITULO DE: </b> " + titulo + "<br/><br/><br/><b>DETALLADA CON: </b>" + desc + "<br/><br/><br/><b>QUE COMIENZA EN: </b>" + str(
        fstar) + " <br/><br/><br/><b>Y TERMINA: </b>" + str(fend)

    elementos.append(Paragraph(parrafo, styleJ))
    elementos.append(Spacer(1, 10))

    pdf.build(elementos)
    response.write(buffer.getvalue())
    buffer.close()
    return response
from reportlab.graphics.shapes import Image, Drawing
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4
guion = []
imaxe = Image(400,10,596,133,"hackerman.png")
debuxo = Drawing(30,30)
debuxo.add(imaxe)
debuxo.translate(0, 600)
guion.append(debuxo)
debuxo = Drawing(30,30)
debuxo.add(imaxe)
debuxo.rotate(45)
debuxo.scale(1.5, 0.5)
debuxo.translate(-90, 300)
guion.append(debuxo)
debuxo = Drawing(30,30)
debuxo.add(imaxe)
debuxo.rotate(90)
debuxo.translate(-20, -100)
guion.append(debuxo)
debuxo = Drawing(A4[0], A4[1])
for deb in guion:
    debuxo.add(deb)
renderPDF.drawToFile(debuxo, "proba2.pdf")