Esempio n. 1
0
   def __addTable( self ):
      tt    = list()

      if self.tipo == "ganancia":
         data  = self.DBM.getCuentas(self.data[0], self.data[1])
         total = 0
         tt.append( ['Fecha', 'Descripción', 'Cantidad', 'Precio'] )

         for producto in data:
            tt.append( [producto[0], producto[1], producto[2], "$ %.2f" % float( producto[4] ) ] )
            total += float( producto[4] )

         tt.append( ["TOTAL" , "", "", "$ %.2f" % total] )
      elif self.tipo == "stock":
         total = 0
         tt.append( ['Código', 'Descripción', 'Marca', 'Precio', 'Punto Pedido', 'Stock'] )

         for producto in self.data:
            if producto[1] != '1000':
               tt.append( [ producto[1], producto[2], producto[3], "$ %.2f" % float( producto[4] ), producto[5], producto[6] ] )
               total += float( producto[4] * producto[6] )

      tabla = Table(tt)

      if self.tipo == "ganancia":
          tabla.setStyle( TableStyle([
                                     ('ALIGN', (1,1), (-2, -2), 'RIGHT'),
                                     ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                                     ('BOX', (0,0), (-1,-1), 0.55, colors.black),
                                     ('TEXTCOLOR',(0,-1),(-1,-1),colors.yellow),
                                     ('BACKGROUND',(0,-1),(-1,-1),colors.red),
                                     ('BACKGROUND',(0,0),(-1,0),colors.gray)
                                    ]))
      elif self.tipo == "stock":
          tabla.setStyle( TableStyle([
                                     ('ALIGN', (1,1), (-1, -1), 'RIGHT'),
                                     ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                                     ('BOX', (0,0), (-1,-1), 0.55, colors.black),
                                     ('BACKGROUND',(0,0),(-1,0),colors.gray)
                                    ]))

      self.elements.append( tabla )

      if self.tipo == "ganancia":
         styles = getSampleStyleSheet()
         ptext  = '<font size=10>Total de ventas: %s </font>' % len( data )
         self.elements.append(Spacer(1, 12))
         styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
         self.elements.append( Paragraph(ptext, styles["Normal"]) )
      elif self.tipo == "stock":
         styles = getSampleStyleSheet()
         ptext  = '<font size=10>Productos en Stock: %s </font>' % len( self.data )
         self.elements.append(Spacer(1, 12))
         styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
         self.elements.append( Paragraph(ptext, styles["Normal"]) )
      
         styles = getSampleStyleSheet()
         ptext  = '<font size=10>Dinero en Stock: $ %.2f </font>' % total
         styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
         self.elements.append( Paragraph(ptext, styles["Normal"]) )
Esempio n. 2
0
    def _createStyles(self):
        """Método que cria um dicionário de estilos que serão utilizados para imprimir as informações"""
        stylesDict = {}
        styles = getSampleStyleSheet()

        style = styles["Normal"]
        style.fontName = "Helvetica"
        style.leftIndent = 30
        style.spaceAfter = 2
        stylesDict.__setitem__("normal", style)

        styles = getSampleStyleSheet()
        stylesub = styles["Normal"]
        stylesub.fontName = "Helvetica"
        stylesub.leftIndent = 45
        stylesub.spaceAfter = 2
        stylesDict.__setitem__("subitem", stylesub)

        styleh2 = styles["Heading2"]
        styleh2.fontName = "Helvetica-Bold"
        styleh2.textColor = "grey"
        styleh2.spaceAfter = 2
        stylesDict.__setitem__("category", styleh2)

        styleh3 = styles["Heading3"]
        styleh3.leftIndent = 15
        styleh3.fontName = "Helvetica-Bold"
        styleh3.spaceAfter = 2
        stylesDict.__setitem__("device", styleh3)

        return stylesDict
    def renderPDF(self, data):
        buff = StringIO.StringIO()
        doc = SimpleDocTemplate(buff, pagesize=letter,
                                rightMargin=72, leftMargin=72,
                                topMargin=72, bottomMargin=18)
        finished = data['finished']
        running = data['running']
        ready = data['ready']

        Report = []
        styles = getSampleStyleSheet()
        style = getSampleStyleSheet()['Normal']
        style.leading = 24

        Report.append(Paragraph('Report on Campaign: ' + "MC16a", styles["Heading1"]))
        Report.append(Paragraph('Build on ' + time.ctime() + " by BigPanDA", styles["Bullet"]))
        Report.append(Paragraph('Progress and loads', styles["Heading2"]))
        Report.append(Paragraph('Done events: ' + humanize.intcomma(int(finished/1000000)) +' M', styles["Normal"]))
        Report.append(Paragraph('Running events: ' + humanize.intcomma(int(running)/1000000) +' M', styles["Normal"]))
        Report.append(Paragraph('Ready for processing events: ' + humanize.intcomma(int(ready)/1000000)  +' M', styles["Normal"]))

        doc.build(Report)
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="report.pdf"'
        response.write(buff.getvalue())
        buff.close()
        return response
    def fillReport(self, data):
            buffer = self.buffer
            doc = SimpleDocTemplate(buffer,
                                    rightMargin=72,
                                    leftMargin=72,
                                    topMargin=72,
                                    bottomMargin=72,
                                    headertext=self.headertext,
                                    footertext=self.footertext,
                                    pagesize=self.pagesize)

            # Our container for 'Flowable' objects
            elements = []

            # A large collection of style sheets pre-made for us
            styles = getSampleStyleSheet()
            #styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

            #Configure style and word wrap
            s = getSampleStyleSheet()
            s = s["BodyText"]
            s.wordWrap = 'CJK'
            #format the data table
            data2 = [[Paragraph(cell, s) for cell in row] for row in data]
            t=Table(data2, repeatRows=1)
            #Send the data and build the file
            elements.append(Paragraph('Report', styles['Heading2']))
            elements.append(t)

            doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer)

            # Get the value of the BytesIO buffer and write it to the response.
            pdf = buffer.getvalue()
            buffer.close()
            return pdf
Esempio n. 5
0
def libro_memos(request, memos):
    ''' Función para descarga de memorándums en PDF '''
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = u'attachment; filename=Memorándum.pdf; pagesize=A4'

    elementos = []
    doc = SimpleDocTemplate(response)    
    style = getSampleStyleSheet() 
    style2 = getSampleStyleSheet()
    styleFecha = getSampleStyleSheet()
    styleEncabezado = getSampleStyleSheet()

    fechas = datetime.datetime.today()
    mes = fecha.NormalDate().monthName()
    dia = fecha.NormalDate().dayOfWeekName()
    salto = '<br />'

    txtFecha = '%s, %s DE %s DE %s'%(dia.upper(), fechas.day, mes.upper(), fechas.year)
    styleF = styleFecha['Normal']
    styleF.fontSize = 8
    styleF.fontName = 'Helvetica'
    styleF.alignment = TA_RIGHT
    fechaV = Paragraph(txtFecha, styleF)
    elementos.append(fechaV)
    elementos.append(Spacer(1,5))

    #-- Espacio para poner el encabezado con la clase Canvas
    elementos.append(Spacer(1,75))

    from django_messages.models import Message
    # memo = Message.objects.filter(id=memos)

    txtTitulo = u'MEMORÁNDUM%s' %(salto)
    titulo = style['Heading1']
    titulo.fontSize = 12
    titulo.fontName = 'Helvetica-Bold'
    titulo.alignment = TA_CENTER
    tituloV = Paragraph(txtTitulo, titulo)
    elementos.append(tituloV)
    elementos.append(Spacer(1,5))

    x = [
    ('BOX', (0,0), (-1,-1), 0.50, colors.black),
    ('ALIGN', (0,0), (-1,-1), 'LEFT'),
    #('TOPPADDING', (0,0), (-1,-1), 1),
    #('BOTTOMPADDING', (0,0), (-1,-1), 2),
    ('GRID', (0,0), (-1,-1), 0.50, colors.black),
    #('FONT', (0,0), (-1,-1), "Helvetica", 8),
    ('FONT', (0,0), (-1,-1), "Helvetica", 6),
    ]

    # Fin código de barras

    #doc.build(elementos, canvasmaker=NumeroDePagina, onFirstPage=encabezado_constancia)
    doc.build(elementos, canvasmaker=pieDePaginaConstancias, onFirstPage=encabezado_constancia)
    return response  
Esempio n. 6
0
def seatingChartByStudent(request, id):
    mealTime = models.MealTime.objects.get(pk=id)

    allStudents = set(mealTime.allStudents())
    seenStudents = set()

    data = []

    for tableAssignment in mealTime.tableassignment_set.all():
        table = tableAssignment.table
        student = tableAssignment.student

        data.append((student.first_name, student.last_name, table.description))

        seenStudents.add(student)

    leftovers = [(s.first_name, s.last_name) for s in (allStudents - seenStudents)]
    leftovers.sort(key=lambda s: (s[1], s[0]))
    data.sort(key=lambda s: (s[1], s[0]))
        
    normal = getSampleStyleSheet()["Normal"]
    heading = getSampleStyleSheet()["Title"]
    heading.fontSize = 40
    
    story=[]
    story.append(Paragraph(mealTime.name, heading))
    story.append(FrameBreak())
    story.append(NextPageTemplate("twoCol"))
    
    for first, last, table in data:
        story.append(Paragraph("%s %s: %s" % (first, last, table), normal))
    
    out = BytesIO()
    doc = BaseDocTemplate(out, pagesize=letter, author="Rectory School Seating Chart Generator", title=mealTime.name)
    
    top = Frame(doc.leftMargin, doc.height, doc.width, 100)
    frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height-75, id='col1')
    frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height-75, id='col2')
    doc.addPageTemplates([PageTemplate(id='topColHeader',frames=[top, frame1,frame2]), ])
    
    frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
    frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')
    doc.addPageTemplates([PageTemplate(id='twoCol',frames=[frame1,frame2]), ])
    
    #start the construction of the pdf
    doc.build(story)
    
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="{mealTime:} by student.pdf"'.format(mealTime=mealTime.name)

    response.write(out.getvalue())

    return response
Esempio n. 7
0
def generarPDFGrid(filename):

    fondo = settings.STATIC_ROOT + '/img/plantillas_img_cuentas/'+filename

    def myFirstPage(canvas, doc):
        PAGE_HEIGHT,PAGE_WIDTH = letter
        canvas.saveState()
        canvas.drawImage(fondo, 0,0, PAGE_HEIGHT, PAGE_WIDTH )
        canvas.setStrokeColorRGB(1,0,1,alpha=0.1)
        #canvas.setPageSize(landscape(letter))
        canvas.setFont('Arial', 10)
        canvas.drawString(150, 579, "-")

        SHOW_GRID = True
        if SHOW_GRID:
             n = 5
             s = 200
             #canvas.setStrokeGray(0.90)
             #canvas.setFillGray(0.90)
             canvas.setStrokeColorRGB(0,1,1,alpha=0.1)
             canvas.setFillColorRGB(1,0,1)
             canvas.setFont('Arial',1)
             for x in range(s):
                for y in range(s):
                   canvas.rect(x*n,y*n, width=n, height=n, stroke=1)
                   canvas.drawString(x*n,y*n,"%s,%s" % ((x*n),(y*n)) )
        canvas.restoreState()


    filename = "pdf_gen.pdf"
    buff = StringIO()
    styleSheet = getSampleStyleSheet()
    doc = SimpleDocTemplate(buff, pagesize=letter,
                        rightMargin=40,leftMargin=40,
                        topMargin=72,bottomMargin=50)

    Story = []
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))

    ptext = '''<font size=12>
               </font>'''
    Story.append(Paragraph(ptext, styles["Justify"]))
    doc.build(Story, onFirstPage=myFirstPage) #, onLaterPages=myLaterPages)

    fo = open(filename, "wb")
    fo.write(buff.getvalue())
    fo.close()

    buff.close()

    return filename
Esempio n. 8
0
   def __addHead( self ):

      if  self.tipo == "stock":
         styles = getSampleStyleSheet()
         ptext  = '<font size=14>Reporte estado de Stock</font>'
         styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
         self.elements.append( Paragraph(ptext, styles["Normal"]) )
         self.elements.append(Spacer(1, 12))
      elif self.tipo == "ganancia":
         styles = getSampleStyleSheet()
         ptext  = '<font size=14>Reporte de ganancias de Tifosi (%s, %s)</font>' % ( self.data[0], self.data[1] )
         styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
         self.elements.append( Paragraph(ptext, styles["Normal"]) )
         self.elements.append(Spacer(1, 12))
Esempio n. 9
0
 def estilos(self, nombre):
     if nombre == 'Estilo1':
         estilo1 = getSampleStyleSheet()
         estilo1.add(ParagraphStyle(name= 'Estilo1', fontName= "Helvetica", fontSize= 10, leading= 10, alignment= TA_CENTER))
         estilo1 = estilo1['Estilo1']  
         estilo1.wordWrap = 'CJK' 
     
     elif nombre == 'Estilo2':
         estilo1 = getSampleStyleSheet()
         estilo1.add(ParagraphStyle(name= 'Estilo2', fontName= "Helvetica", fontSize= 10, leading= 10, wordWrap= 'CJK', alignment= TA_LEFT))
         estilo1 = estilo1['Estilo2']  
         estilo1.wordWrap = 'CJK'
         
     return estilo1 
Esempio n. 10
0
  def setup_styles(self):
    # Build style sheets
    s1, s2, s3 = getSampleStyleSheet(), getSampleStyleSheet(), getSampleStyleSheet()
    self.sessionStyle, self.dateStyle = s1['Normal'], s2['Normal']
    self.titleStyle = s3['Heading2']
    self.titleStyle.alignment = TA_CENTER
    self.dateStyle.backColor = colors.grey
    self.dateStyle.textColor = colors.white
    self.dateStyle.alignment = TA_CENTER

    # Base table style
    self.tableStyle = [
      # Grid around the table
      ('GRID', (0,0), (-1,-1), 0.5, colors.black),
    ]
Esempio n. 11
0
 def __init__(self, pdf_file, xml_file,country_name):
     pdfmetrics.registerFont(TTFont('Arial', 'fonts/Arial.ttf'))
     pdfmetrics.registerFont(TTFont('Arial-Bold', 'fonts/Arial-Bold.ttf'))
     pdfmetrics.registerFont(TTFont('Arial-Italic', 'fonts/Arial-Italic.ttf'))
     addMapping('Arial',0,0,'Arial')
     addMapping('Arial',0,1,'Arial-Italic')
     addMapping('Arial',1,0,'Arial-Bold')
     
     self.country = country_name
     self.styles = getSampleStyleSheet()
     self.e = ElementTree.parse(xml_file).getroot()
     self.width, self.height =  int(self.e.getchildren()[0].get("width")), int(self.e.getchildren()[0].get("height"))
     self.c = canvas.Canvas(pdf_file, pagesize=(self.width,self.height))
     self.fonts = {}
     for page in self.e.findall("page"):
         for fontspec in page.findall("fontspec"):
             font = {}
             font["size"] = int(fontspec.get("size"))
             font["color"] = fontspec.get("color")
             font["background"] = fontspec.get("background")
             if fontspec.get("indent") is not None:
                 font["indent"] = fontspec.get("indent")
             else:
                 font["indent"] = "0"
             if fontspec.get("padding") is not None:
                 font["padding"] = fontspec.get("padding")
             else:
                 font["padding"] = "0"
             self.fonts[fontspec.get("id")] = font 
    def test3(self):
        from reportlab.pdfgen.canvas import Canvas

        aW=307
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']
        btj = ParagraphStyle('bodyText1j',parent=bt,alignment=TA_JUSTIFY)
        p=Paragraph("""<a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
                keepTogether attributes.  Generated at 1111. The number in brackets
                at the end of each paragraph is its position in the story. llllllllllllllllllllllllll 
                bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc ddddddddddddddddddddd eeeeyyy""",btj)

        w,h=p.wrap(aW,1000)
        canv=Canvas('test_platypus_paragraph_just.pdf',pagesize=(aW,h))
        i=len(canv._code)
        p.drawOn(canv,0,0)
        ParaCode=canv._code[i:]
        canv.saveState()
        canv.setLineWidth(0)
        canv.setStrokeColorRGB(1,0,0)
        canv.rect(0,0,aW,h)
        canv.restoreState()
        canv.showPage()
        canv.save()
        from reportlab import rl_config
        x = rl_config.paraFontSizeHeightOffset and '50' or '53.17'
        good = ['q', '1 0 0 1 0 0 cm', 'q', 'BT 1 0 0 1 0 '+x+' Tm 3.59 Tw 12 TL /F1 10 Tf 0 0 0 rg (Subsequent pages test pageBreakBefore, frameBreakBefore and) Tj T* 0 Tw .23 Tw (keepTogether attributes. Generated at 1111. The number in brackets) Tj T* 0 Tw .299167 Tw (at the end of each paragraph is its position in the story. llllllllllllllllllllllllll) Tj T* 0 Tw 66.9 Tw (bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc) Tj T* 0 Tw (ddddddddddddddddddddd eeeeyyy) Tj T* ET', 'Q', 'Q']
        ok= ParaCode==good
        assert ok, "\nParaCode=%r\nexpected=%r" % (ParaCode,good)
Esempio n. 13
0
    def endClass(self, name, doc, bases):
        h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code
        styleSheet = getSampleStyleSheet()
        bt1 = styleSheet['BodyText']
        story = self.story

        # Use only the first line of the class' doc string --
        # no matter how long! (Do the same later for methods)
        classDoc = reduceDocStringLength(doc)

        tsa = tableStyleAttributes = []

        # Make table with class and method rows
        # and add it to the story.
        p = Paragraph('<b>%s</b>' % self.classCompartment, bt)
        p.style.alignment = TA_CENTER
        rows = [(p,)]
        # No doc strings, now...
        # rows = rows + [(Paragraph('<i>%s</i>' % classDoc, bt1),)]
        lenRows = len(rows)
        tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black))
        for name, doc, sig in self.methodCompartment:
            nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1)
            rows.append((nameAndSig,))
            # No doc strings, now...
            # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1)
            # rows.append((docStr,))
        tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black))
        t = Table(rows, (12*cm,))
        tableStyle = TableStyle(tableStyleAttributes)
        t.setStyle(tableStyle)
        self.story.append(t)
        self.story.append(Spacer(1*cm, 1*cm))
Esempio n. 14
0
    def endFunctions(self, names):
        h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code
        styleSheet = getSampleStyleSheet()
        bt1 = styleSheet['BodyText']
        story = self.story
        if not names:
            return

        tsa = tableStyleAttributes = []

        # Make table with class and method rows
        # and add it to the story.
        p = Paragraph('<b>%s</b>' % self.classCompartment, bt)
        p.style.alignment = TA_CENTER
        rows = [(p,)]
        lenRows = len(rows)
        tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black))
        for name, doc, sig in self.methodCompartment:
            nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1)
            rows.append((nameAndSig,))
            # No doc strings, now...
            # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1)
            # rows.append((docStr,))
        tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black))
        t = Table(rows, (12*cm,))
        tableStyle = TableStyle(tableStyleAttributes)
        t.setStyle(tableStyle)
        self.story.append(t)
        self.story.append(Spacer(1*cm, 1*cm))
Esempio n. 15
0
def make_suggested_starts(phage_genes, phage_name, file_path):
    """
        Creates a PDF page of the suggested starts of a phage
        Genes are list in order
        {Gene Name} is a member of Pham {Number}: {Suggested Start Coordinates}
    """
    file_name = os.path.join(file_path, "%sSuggestedStarts.pdf" % (phage_name))
    if check_file(file_name):
        return
    doc = SimpleDocTemplate(file_name, pagesize=letter)
    story = []
    print "making suggested starts page"
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="paragraph"))
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    text = '<font size=14> Suggested Start Coordinates</font>'
    story.append(Paragraph(text, styles['Center']))
    story.append(Spacer(1, 12))
    for gene_id in sorted(phage_genes.iterkeys()):
        phage_gene = phage_genes[gene_id]
        pham = phage_gene["pham_no"]
        gene = phage_gene["gene"]
        suggested_start = phage_gene["suggested_start"]
        if pham == None:
            text = '<font size=12> %s is not a member of an existing Pham </font>' % (gene.gene_id)
        else:
            text = '<font size=12> %s is a member of Pham %s:  %s </font>' % (gene.gene_id, pham, suggested_start)
        story.append(Paragraph(text, styles['Normal']))
    doc.build(story)
Esempio n. 16
0
 def writePdfName(self, pdfName):
   self.elements.append(Spacer(100, 220))
   pdftext = '<center><font size=36><u>' + pdfName + '</u></font></center>'
   styleSheet = getSampleStyleSheet()
   styleSheet.add(ParagraphStyle(name='Center', alignment=TA_JUSTIFY))
   self.elements.append(Paragraph(pdftext, styleSheet["Normal"]))
   self.elements.append(PageBreak())
Esempio n. 17
0
def generar_pdf_Producto(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "productos.pdf" 
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Productos", styles['Heading1'])
    productos.append(header)
    headings = ('Proveedor','Nombre', 'Descripcion', 'Marca', 'Precio','Stock Actual')
    allproductos = [(p.prov_id, p.pro_nom, p.pro_des, p.pro_mar, p.pro_pre, p.pro_sto_act) for p in Producto.objects.all()]

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (6, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
Esempio n. 18
0
def buildTable(data):
  doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
  doc.pagesize = landscape(A4)
  elements = []

  #Configure style and word wrap
  s = getSampleStyleSheet()
  s = s["BodyText"]
  s.wordWrap = 'CJK'

  pdf_data = [["Requirement", "Description", "Test Case(s)"]]

  #TODO: Need a numerical sort here
  keys = sorted(data.keys())

  for key in keys:
    data[key][2] = '\n'.join(data[key][2])
    pdf_data.append([Paragraph(cell, s) for cell in data[key]])


  # Build the Table and Style Information
  tableThatSplitsOverPages = Table(pdf_data, repeatRows=1)
  tableThatSplitsOverPages.hAlign = 'LEFT'
  tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black),
                         ('VALIGN',(0,0),(-1,-1),'TOP'),
                         ('LINEBELOW',(0,0),(-1,-1),1,colors.black),
                         ('INNERGRID', (0,0), (-1,-1),1,colors.black),
                         ('BOX',(0,0),(-1,-1),1,colors.black),
                         ('BOX',(0,0),(0,-1),1,colors.black)])
  tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue)
  tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white)
  tableThatSplitsOverPages.setStyle(tblStyle)
  elements.append(tableThatSplitsOverPages)

  doc.build(elements)
Esempio n. 19
0
def outputtopdf(outputfile,title,labels,db,resdb):
    import logging
    log = logging.getLogger('outputtopdf')
    try:
            from reportlab.platypus import TableStyle, Table, SimpleDocTemplate, Paragraph
            from reportlab.lib import colors
            from reportlab.lib.styles import getSampleStyleSheet
            from reportlab.pdfgen import canvas
    except ImportError:
            log.error('Reportlab was not found. To export to pdf you need to have reportlab installed. Check out www.reportlab.org')
            return
    log.debug('ok reportlab library found')
    styles = getSampleStyleSheet()
    rows=list()
    rows.append(labels)
    for k in db.keys():
        cols = [k,db[k]]
        if resdb is not None:
            if resdb.has_key(k):
                cols.append(resdb[k])
            else:
                cols.append('N/A')
        rows.append(cols)    
    t=Table(rows)
    mytable = TableStyle([('BACKGROUND',(0,0),(-1,0),colors.black),
                            ('TEXTCOLOR',(0,0),(-1,0),colors.white)])
    t.setStyle(mytable)
    doc = SimpleDocTemplate(outputfile)
    elements = []
    style = styles["Heading1"]
    Title = Paragraph(title,style)
    elements.append(Title)
    elements.append(t)
    doc.build(elements)
 def subtitle_style(self):
     styles = getSampleStyleSheet()
     subtitle_style = styles["Heading2"]
     subtitle_style.fontSize = 24
     subtitle_style.leading = 26
     subtitle_style.alignment = TA_CENTER
     return subtitle_style
Esempio n. 21
0
def generar_pdf(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "proveedores.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    proveedores = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Proveedores", styles['Heading1'])
    proveedores.append(header)
    headings = ('No. Proveedor','Nombre','RFC','Giro','Direccion','Ciudad','Estado','Pais','Telefono','Correo','Comentario')
    allproveedores = [(p.num_proveedor, p.nombre, p.RFC ,p.giro ,p.direccion ,p.ciudad ,p.estado ,p.pais ,p.telefono ,p.correo ,p.comentario) for p in Proveedor.objects.all()]
    print (allproveedores);

    t = Table([headings] + allproveedores)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    proveedores.append(t)
    doc.build(proveedores)
    response.write(buff.getvalue())
    buff.close()
    return response
Esempio n. 22
0
def getSampleStory(depth=3):
    """Makes a story with lots of paragraphs.  Uses the random
    TOC data and makes paragraphs to correspond to each."""
    from reportlab.platypus.doctemplate import randomText
    from random import randint

    styles = getSampleStyleSheet()
    TOCData = getSampleTOCData(depth)

    story = [Paragraph("This is a demo of the table of contents object",
                       styles['Heading1'])]

    toc = TableOfContents0()  # empty on first pass
    #toc.addEntries(TOCData)  # init with random page numbers
    story.append(toc)

    # the next full page should switch to internal page style
    story.append(NextPageTemplate("Body"))

    # now make some paragraphs to correspond to it
    for (level, text, pageNum) in TOCData:
        if level == 0:
            #page break before chapter
            story.append(PageBreak())

        headingStyle = (styles['Heading1'], styles['Heading2'], styles['Heading3'])[level]
        headingPara = Paragraph(text, headingStyle)
        story.append(headingPara)
        # now make some body text
        for i in range(randint(1,6)):
            bodyPara = Paragraph(randomText(),
                                 styles['Normal'])
            story.append(bodyPara)

    return story
Esempio n. 23
0
def generate_certificate(description_of_items,cost_of_items,amount,cost,qty,raise_for,request ):

    buffer = BytesIO()
    styleSheet = getSampleStyleSheet()
    style = styleSheet['Normal']
    canv = Canvas('my_pdf.pdf')
    canv.setFillColorRGB(0, 0, 255)
    canv.setFont('Helvetica-Bold', 44, leading=None)
    canv.drawCentredString(102, 800, "INVOICE")
    canv.setFont('Helvetica-Bold', 8, leading=None)
    #canv.drawCentredString(38, 824, "From:")
    b = Company_credentials.objects.get(user=request.user)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(480, 826, b.company_name)
    canv.drawCentredString(480, 813, b.email)
    canv.drawCentredString(480, 801, b.country + ',' + b.phone_number)
    #canv.drawCentredString(480, 790, b.email)
    canv.setFillColorRGB(0, 0, 0)

    canv.drawCentredString(480, 790, "Raised on:" + str(datetime.date.today()) )
    canv.line(0, 785, 800, 785)
    canv.setFont('Helvetica', 21, leading=None)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(68, 760, "Description:")
    canv.setFillColorRGB(0, 0, 0)
    canv.setFont('Helvetica-Bold', 14, leading=None)
    canv.drawCentredString(120, 730, "ITEMS")
    canv.drawCentredString(320, 730, "RATE")
    canv.drawCentredString(410, 730, "QTY")
    canv.drawCentredString(500, 730, "AMOUNT")
    canv.setFont('Helvetica', 8, leading=None)
    y_coordinate = 710
    chaska = 0
    length = len(description_of_items)
    for chaska in range(length):
        canv.drawCentredString(120, y_coordinate,description_of_items[chaska])
        canv.drawCentredString(320, y_coordinate, str(cost_of_items[chaska]))
        canv.drawCentredString(410, y_coordinate, str(qty[chaska]))
        canv.drawCentredString(500, y_coordinate, '$' + str(amount[chaska]))
        y_coordinate = y_coordinate - 15
    y_coordinate = y_coordinate - 25
    canv.line(310, y_coordinate, 580, y_coordinate)
    canv.setFont('Helvetica-Bold', 12, leading=None)
    canv.drawCentredString(410, y_coordinate-16, "Total")
    canv.drawCentredString(500, y_coordinate-16, '$' + str(cost))
    canv.setFillColorRGB(0,0,255)
    canv.setFont('Helvetica', 16, leading=None)
    canv.drawCentredString(55, y_coordinate-16, "Raised For:")
    canv.setFillColorRGB(0, 0, 0)
    P = Paragraph(raise_for, style)
    aW = 180
    aH = y_coordinate-46
    w, h = P.wrap(aW, aH)  # find required space
    if w <= aW and h <= aH:
        P.drawOn(canv, 12, aH)
        aH = aH - h  # reduce the available height
    canv.save()
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Esempio n. 24
0
def print_rep(uid):
    registerFont(TTFont('DroidSans', 'DroidSans.ttf'))

    pdf = StringIO()

    doc = SimpleDocTemplate(pdf, pagesize=A4)
    elements = []
    style = getSampleStyleSheet()
    style.add(ParagraphStyle(name='Header', alignment=TA_LEFT,
                             fontName='DroidSans',
                             fontSize=14, leading=16))
    style.add(ParagraphStyle(name='Left', alignment=TA_LEFT,
                             fontName='DroidSans',
                             fontSize=12))
    style.add(ParagraphStyle(name='Right', alignment=TA_RIGHT,
                             fontName='DroidSans',
                             fontSize=12))
    if uid == 0:
        elements.append(Paragraph(u'<u>Users List</u>', style['Header']))
        u = User.query.all()     
        for i, o in enumerate(u):
            elements.append(Paragraph(u'%s. %s %s %s' % (i+1, o.name, o.email, o.progress), style['Left']))
    else:
        u = User.query.get(uid)
        elements.append(Paragraph(u'%s %s %s' % (u.name, u.email, u.progress), style['Header']))

    doc.build(elements)
    pdf_file = pdf.getvalue()
    pdf.close()
    response = make_response(pdf_file)

    response.headers['Content-Disposition'] = "attachment; filename='pdf_user.pdf"
    response.mimetype = 'application/pdf'
    return response
Esempio n. 25
0
 def make_content(self):
     """
     This needs to be done for every label becuase frame.addFrame clears out the 
     flowables.
     """
     
     styles = getSampleStyleSheet()
     styleN = styles['Normal']
     
     self.slogan = []
     self.slogan.append(Paragraph(self.tag.slogan1,styleN))
     self.slogan.append(Paragraph(self.tag.slogan2,styleN))
         
     self.contact =[]
     self.contact.append(Paragraph(self.tag.contact1,styleN))
     self.contact.append(Paragraph(self.tag.contact2,styleN))
     self.contact.append(Paragraph(self.tag.contact3,styleN))
         
     self.url=[Paragraph(self.tag.url,styleN)]
                                
     self.qrcode=[]
     if self.tag.qrcode:
         self.qrcode.append(Image(self.tag.qrcode.path, 1.0*inch, 1.0*inch))           
     
     self.logo=[]
     if self.tag.logo:
         self.logo.append(Image(self.tag.logo.path, 0.4*self.height, 0.4*self.height))
Esempio n. 26
0
def email_admin(self, subject, text, sorted_self):

    site_name = SiteSetting.objects.all().first().site_name

    styleSheet = getSampleStyleSheet()

    # Send the admin a PDF of client details
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"'

    string_buffer = StringIO()

    new_pdf = []
    header = Paragraph(site_name + " Attendee Details", styleSheet['Heading1'])
    new_pdf.append(header)

    for element in sorted_self:
        new_pdf.append(Paragraph(element[0], styleSheet['Heading3']))
        new_pdf.append(Paragraph(element[1], styleSheet['BodyText']))
        new_pdf.append(Spacer(1, 2))

    doc = SimpleDocTemplate(string_buffer)
    doc.build(new_pdf)
    pdf = string_buffer.getvalue()
    string_buffer.close()

    msg = EmailMultiAlternatives(subject, text, EMAIL_HOST_USER, [EMAIL_HOST_USER])
    msg.attach(self.first_name + self.last_name + site_name + ".pdf", pdf, "application/pdf")
    msg.send(fail_silently=True)
Esempio n. 27
0
    def __init__(self, invoice_path, pdf_info=None):
        if not pdf_info:
            pdf_info = self.default_pdf_info

        SimpleDocTemplate.__init__(
            self,
            invoice_path,
            pagesize=letter,
            rightMargin=inch,
            leftMargin=inch,
            topMargin=inch,
            bottomMargin=inch,
            **pdf_info.__dict__
        )

        self._defined_styles = getSampleStyleSheet()
        self._defined_styles.add(
            ParagraphStyle('RightHeading1', parent=self._defined_styles.get('Heading1'), alignment=TA_RIGHT)
        )
        self._defined_styles.add(
            ParagraphStyle('TableParagraph', parent=self._defined_styles.get('Normal'), alignment=TA_CENTER)
        )

        self.invoice_info = None
        self.service_provider_info = None
        self.client_info = None
        self.is_paid = False
        self._items = []
        self._item_tax_rate = None
        self._transactions = []
        self._story = []
        self._bottom_tip = None
        self._bottom_tip_align = None
Esempio n. 28
0
File: pdf.py Progetto: awriel/eden
    def addParagraph(self, text, style=None, append=True):
        """
        Method to create a paragraph that may be inserted into the document

        @param text: The text for the paragraph
        @param append: If True then the paragraph will be stored in the
        document flow ready for generating the pdf.

        @return The paragraph

        This method can return the paragraph rather than inserting into the
        document. This is useful if the paragraph needs to be first
        inserted in another flowable, before being added to the document.
        An example of when this is useful is when large amounts of text
        (such as a comment) are added to a cell of a table.
        """

        if text != "":
            if style == None:
                styleSheet = getSampleStyleSheet()
                style = styleSheet["Normal"]
            para = Paragraph(text, style)
            if append and self.body_flowable:
                self.body_flowable.append(para)
            return para
        return ""
Esempio n. 29
0
    def get_style(self):
        from reportlab.lib.styles import getSampleStyleSheet

        styles = getSampleStyleSheet()
        style = styles["Normal"]
        style.fontName = 'OpenSans'
        return style
def convertSourceFiles(filenames):
    "Helper function - makes minimal PDF document"

    from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
    from reportlab.lib.styles import getSampleStyleSheet
    styT=getSampleStyleSheet()["Title"]
    styC=getSampleStyleSheet()["Code"]
    doc = SimpleDocTemplate("pygments2xpre.pdf")
    S = [].append
    for filename in filenames:
        S(Paragraph(filename,style=styT))
        src = open(filename, 'r').read()
        fmt = pygments2xpre(src)
        S(XPreformatted(fmt, style=styC))
    doc.build(S.__self__)
    print('saved pygments2xpre.pdf')
 def style_n(self):
     style = getSampleStyleSheet()['Normal']
     style.leading = 12
     style.allowWidows = 0
     style.spaceBefore = 0.2 * inch
     return style
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  # Justified

        # format labels

        # 0 row
        intestazione = Paragraph("<b>SCHEDA INVENTARIO REPERTI<br/>" + str(self.datestrfdate()) + "</b>", styNormal)
        intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)

        # 1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)
        us = Paragraph("<b>US</b><br/>" + str(self.us), styNormal)
        nr_inventario = Paragraph("<b>Nr. Inventario</b><br/>" + str(self.numero_inventario), styNormal)

        # 2 row
        criterio_schedatura = Paragraph("<b>Criterio schedatura</b><br/>" + self.criterio_schedatura, styNormal)
        tipo_reperto = Paragraph("<b>Tipo reperto</b><br/>" + self.tipo_reperto, styNormal)
        definizione = Paragraph("<b>Definizione</b><br/>" + self.definizione, styNormal)

        # 3 row
        stato_conservazione = Paragraph("<b>Stato Conservazione</b><br/>" + self.stato_conservazione, styNormal)
        datazione = Paragraph("<b>Datazione</b><br/>" + self.datazione_reperto, styNormal)

        # 4 row
        descrizione = ''
        try:
            descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.descrizione), styDescrizione)
        except:
            pass

            # 5 row
        elementi_reperto = ''
        if eval(self.elementi_reperto) > 0:
            for i in eval(self.elementi_reperto):
                if elementi_reperto == '':
                    try:
                        elementi_reperto += ("Elemento rinvenuto: %s, Unita' di musura: %s, Quantita': %s") % (
                        str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass
                else:
                    try:
                        elementi_reperto += ("<br/>Elemento rinvenuto: %s, Unita' di musura: %s, Quantita': %s") % (
                        str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass

        elementi_reperto = Paragraph("<b>Elementi reperto</b><br/>" + elementi_reperto, styNormal)

        # 6 row
        misurazioni = ''
        if eval(self.misurazioni) > 0:
            for i in eval(self.misurazioni):
                if misurazioni == '':
                    try:
                        misurazioni += ("<b>Tipo di misura: %s, Unita' di musura: %s, Quantita': %s") % (
                        str(i[0]), str(i[2]), str(i[1]))
                    except:
                        pass
                else:
                    try:
                        misurazioni += ("<br/><b>Tipo di misura: %s, Unita' di musura: %s, Quantita': %s") % (
                        str(i[0]), str(i[2]), str(i[1]))
                    except:
                        pass
        misurazioni = Paragraph("<b>Misurazioni</b><br/>" + misurazioni, styNormal)

        # 7 row
        tecnologie = ''
        if eval(self.tecnologie) > 0:
            for i in eval(self.tecnologie):
                if tecnologie == '':
                    try:
                        tecnologie += (
                                      "<b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (
                                      str(i[0]), str(i[1]), str(i[2]), str(i[3]), str(i[4]))
                    except:
                        pass
                else:
                    try:
                        tecnologie += (
                                      "<br/><b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (
                                      str(i[0]), str(i[1]), str(i[2]), str(i[3]), str(i[4]))
                    except:
                        pass
        tecnologie = Paragraph("<b>Tecnologie</b><br/>" + tecnologie, styNormal)

        # 8 row
        rif_biblio = ''
        if eval(self.rif_biblio) > 0:
            for i in eval(self.rif_biblio):  # gigi
                if rif_biblio == '':
                    try:
                        rif_biblio += ("<b>Autore: %s, Anno: %s, Titolo: %s, Pag.: %s, Fig.: %s") % (
                        str(i[0]), str(i[1]), str(i[2]), str(i[3]), str(i[4]))
                    except:
                        pass
                else:
                    try:
                        rif_biblio += (
                                      "<br/><b>Tipo tecnologia: %s, Posizione: %s, Tipo quantita': %s, Unita' di musura: %s, Quantita': %s") % (
                                      str(i[0]), str(i[1]), str(i[2]), str(i[3]), str(i[4]))
                    except:
                        pass

        rif_biblio = Paragraph("<b>Riferimenti bibliografici</b><br/>" + rif_biblio, styNormal)

        # 9 row
        riferimenti_stratigrafici = Paragraph("<b>Riferimenti stratigrafici</b>", styNormal)

        # 10 row
        area = Paragraph("<b>Area</b><br/>" + self.area, styNormal)
        us = Paragraph("<b>US</b><br/>" + self.us, styNormal)

        # 11 row
        riferimenti_magazzino = Paragraph("<b>Riferimenti magazzino</b>", styNormal)

        # 12 row
        lavato = Paragraph("<b>Lavato</b><br/>" + self.lavato, styNormal)
        nr_cassa = Paragraph("<b>Nr. Cassa</b><br/>" + self.nr_cassa, styNormal)
        luogo_conservazione = Paragraph("<b>Luogo di conservazione</b><br/>" + self.luogo_conservazione, styNormal)

        # schema
        cell_schema = [  # 00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [intestazione, '01', '02', '03', '04', '05', '06', '07', intestazione2, '09'],
            [sito, '01', '02', area, '04', us, '06', '07', nr_inventario, '09'],  # 1 row ok
            [tipo_reperto, '01', '02', criterio_schedatura, '04', '05', definizione, '07', '08', '09'],
            # 2 row ok
            [datazione, '01', '02', '03', '04', stato_conservazione, '06', '07', '08', '09'],  # 3 row ok
            [descrizione, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 4 row ok
            [elementi_reperto, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 5 row ok
            [misurazioni, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 6 row ok
            [tecnologie, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 7 row ok
            [rif_biblio, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 8 row ok
            [riferimenti_stratigrafici, '02', '03', '04', '05', '06', '07', '08', '09'],  # 9 row ok
            [area, '01', '02', us, '04', '05', '06', '07', '08', '09'],  # 10 row ok
            [riferimenti_magazzino, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 11 row ok
            [lavato, '01', '02', nr_cassa, '04', '05', luogo_conservazione, '07', '08', '09'],  # 12 row ok
            ['www.pyarchinit.altervista.org', '01', '02', '03', '04', '05', '06', '07', '08', '09']  # 13 row
        ]

        # table style
        table_style = [

            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # 0 row
            ('SPAN', (0, 0), (7, 0)),  # intestazione
            ('SPAN', (8, 0), (9, 0)),  # intestazione

            # 1 row
            ('SPAN', (0, 1), (2, 1)),  # dati identificativi
            ('SPAN', (3, 1), (4, 1)),  # dati identificativi
            ('SPAN', (5, 1), (7, 1)),  # dati identificativi
            ('SPAN', (8, 1), (9, 1)),  # dati identificativi

            # 2 row
            ('SPAN', (0, 2), (2, 2)),  # definizione
            ('SPAN', (3, 2), (5, 2)),  # definizione
            ('SPAN', (6, 2), (9, 2)),  # definizione
            ('VALIGN', (0, 2), (9, 2), 'TOP'),

            # 3 row
            ('SPAN', (0, 3), (4, 3)),  # datazione
            ('SPAN', (5, 3), (9, 3)),  # conservazione

            # 4 row
            ('SPAN', (0, 4), (9, 4)),  # descrizione

            # 5 row
            ('SPAN', (0, 5), (9, 5)),  # elementi_reperto

            # 6 row
            ('SPAN', (0, 6), (9, 6)),  # misurazioni

            # 7 row
            ('SPAN', (0, 7), (9, 7)),  # tecnologie

            # 8 row
            ('SPAN', (0, 8), (9, 8)),  # bibliografia

            # 9 row
            ('SPAN', (0, 9), (9, 9)),  # Riferimenti stratigrafici - Titolo

            # 10 row
            ('SPAN', (0, 10), (2, 10)),  # Riferimenti stratigrafici - area
            ('SPAN', (3, 10), (9, 10)),  # Riferimenti stratigrafici - us

            # 11 row
            ('SPAN', (0, 11), (9, 11)),  # Riferimenti magazzino - Titolo

            # 12 row
            ('SPAN', (0, 12), (2, 12)),  # Riferimenti magazzino - lavato
            ('SPAN', (3, 12), (5, 12)),  # Riferimenti magazzino - nr_cassa
            ('SPAN', (6, 12), (9, 12)),  # Riferimenti magazzino - luogo conservazione

            # 13 row
            ('SPAN', (0, 13), (9, 13)),  # pie' di pagina
            ('ALIGN', (0, 13), (9, 13), 'CENTER')

        ]

        t = Table(cell_schema, colWidths=50, rowHeights=None, style=table_style)

        return t
 def style_h3(self):
     style = getSampleStyleSheet()['Heading3']
     style.textColor = self.VIOLET_ULL
     return style
Esempio n. 34
0
			hlurl = link.get('href')
			if len(text) == 0:
				if link.find('img') != None:
					if imagelink:
						text = '[image]'
					else:
						continue
				else:
					if qmlink:
						text = '[???]'
					else:
						continue
			if '#' in hlurl and not '.' in hlurl:	#only shortcuts to other websites
				continue
			if hlurl[0] == '/':
				hlurl = domain + hlurl
			hl.append([text, hlurl])
		
		l = dialogs.edit_list_dialog('Hyperlinks',hl)
		
		style = getSampleStyleSheet()
		items = []
		for i in l:
			items.append(Paragraph('<link href="' + i[1] + '" color="blue">' + i[0] + '</link>', style['Heading3']))
		if format:
			pdf = SimpleDocTemplate(filename, pagesize=A4)
		else:
			pdf = SimpleDocTemplate(filename, pagesize=letter)
		pdf.build(items)
		print 'PDF is created.'
Esempio n. 35
0
def genInvoice(c , o, ofr , it, se): # canvas , order , offer , item , service
    c.setFont("Times-Roman" , 20)
    c.drawCentredString(2*cm, 27*cm,"Brand")
    c.line(1*cm , 26*cm ,20*cm,26*cm )
    c.drawImage(os.path.join(globalSettings.BASE_DIR , 'static_shared','images' , 'logo.png') , 3*cm , 26.2*cm , 2*cm, 2*cm)
    c.setFont("Times-Roman" , 12)
    c.drawString(5*cm, 27.35*cm , "Contact us : 1800 1234 5678 | [email protected]")
    styles=getSampleStyleSheet()
    sead = se.address # service provide address
    serAddress = '<p><font size=14>%s.</font><font size=10>  34, %s , %s, %s, Pin : %s</font></p>' %(se.name , sead.street , sead.city , sead.state , sead.pincode)
    p = Paragraph( serAddress , styles['Normal'])
    p.wrapOn(c, 15*cm, 1*cm)
    p.drawOn(c, 5*cm, 26.3*cm)
    c.setDash(6,3)
    c.rect(14.4*cm, 27.2*cm, 5.5*cm, 0.6*cm )
    c.drawString(14.5*cm, 27.35*cm , "Invoice # DEL-%s" %(o.pk))
    pSrc = '''
        <font size=10>
            <strong>Order ID: OD%s</strong><br/><br/>
            <strong>Order Date : </strong> %s <br/>
            <strong>Invoice Date : </strong> %s <br/>
            <strong>VAT/TIN : </strong> %s <br/>
            <strong>CST# : </strong> %s <br/>
        </font>
    ''' % (o.pk , o.created.date() , o.created.date() , se.tin , se.tin)
    p = Paragraph( pSrc , styles['Normal'])
    p.wrapOn(c, 6*cm, 5*cm)
    p.drawOn(c, 1*cm, 22.4*cm)
    custAdd = o.address # customer address
    cust = o.user
    pSrc = '''
        <font size=10>
            <strong>Billing Address</strong><br/><br/>
            %s %s<br/>
            %s,<br/>
            %s Pin : %s,<br/>
            %s<br/>
            Phone : %s <br/>
        </font>
    ''' % (cust.first_name , cust.last_name , custAdd.street ,custAdd.city , custAdd.pincode , custAdd.state , o.mobile )
    p = Paragraph( pSrc , styles['Normal'])
    p.wrapOn(c, 6*cm, 5*cm)
    p.drawOn(c, 7.5*cm, 22*cm)
    pSrc = '''
        <font size=10>
            <strong>Shipping Address</strong><br/><br/>
            %s %s<br/>
            %s,<br/>
            %s Pin : %s,<br/>
            %s<br/>
            Phone : %s <br/>
        </font>
    ''' % (cust.first_name , cust.last_name , custAdd.street ,custAdd.city , custAdd.pincode , custAdd.state , o.mobile )
    p = Paragraph( pSrc , styles['Normal'])
    p.wrapOn(c, 6*cm, 5*cm)
    p.drawOn(c, 14*cm, 22*cm)
    c.setDash()
    pHeadProd = Paragraph('<strong>Product</strong>' , styles['Normal'])
    pHeadDetails = Paragraph('<strong>Details</strong>' , styles['Normal'])
    pHeadQty = Paragraph('<strong>Qty</strong>' , styles['Normal'])
    pHeadPrice = Paragraph('<strong>Price</strong>' , styles['Normal'])
    pHeadTax = Paragraph('<strong>Tax</strong>' , styles['Normal'])
    pHeadTotal = Paragraph('<strong>Total</strong>' , styles['Normal'])

    bookingTotal , bookingHrs = getBookingAmount(o)

    pSrc = ''''<strong>%s</strong><br/>(5.00%sCST) <br/><strong>Start : </strong> %s <br/>
        <strong>End : </strong> %s <br/><strong>Booking Hours : </strong> %s Hours <br/>
        ''' %(it.description[0:40] , '%' , o.start.strftime('%Y-%m-%d , %H:%M %p'), o.end.strftime('%Y-%m-%d , %H:%M %p'), bookingHrs)
    pBodyProd = Paragraph('%s <strong>VB%s</strong>' %(it.title , it.pk) , styles['Normal'])
    pBodyTitle = Paragraph( pSrc , styles['Normal'])
    pBodyQty = Paragraph('%s' % (o.quantity) , styles['Normal'])
    pBodyPrice = Paragraph('<strong> %s </strong>/ Hr' % (ofr.rate) , styles['Normal'])

    tax = 0.05*bookingTotal
    pBodyTax = Paragraph('%s' % (tax) , styles['Normal'])
    pBodyTotal = Paragraph('%s' %(bookingTotal) , styles['Normal'])

    pFooterQty = Paragraph('%s' % (o.quantity) , styles['Normal'])
    pFooterTax = Paragraph('%s' %(tax) , styles['Normal'])
    pFooterTotal = Paragraph('%s' % (bookingTotal) , styles['Normal'])
    pFooterGrandTotal = Paragraph('%s' % (bookingTotal) , styles['Normal'])

    data = [[ pHeadProd, pHeadDetails, pHeadPrice , pHeadQty, pHeadTax , pHeadTotal],
            [pBodyProd, pBodyTitle, pBodyPrice, pBodyQty, pBodyTax , pBodyTotal],
            ['', '', '', pFooterQty, pFooterTax , pFooterTotal],
            ['', '', '', 'Grand Total', '' , pFooterGrandTotal]]
    t=Table(data)
    ts = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
                ('SPAN',(-3,-1),(-2,-1)),
                ('LINEABOVE',(0,0),(-1,0),0.25,colors.gray),
                ('LINEABOVE',(0,1),(-1,1),0.25,colors.gray),
                ('LINEABOVE',(-3,-2),(-1,-2),0.25,colors.gray),
                ('LINEABOVE',(0,-1),(-1,-1),0.25,colors.gray),
                ('LINEBELOW',(0,-1),(-1,-1),0.25,colors.gray),
            ])
    t.setStyle(ts)
    t._argW[0] = 3*cm
    t._argW[1] = 8*cm
    t._argW[2] = 2*cm
    t._argW[3] = 2*cm
    t._argW[4] = 2*cm
    t._argW[5] = 2*cm
    t.wrapOn(c, 19*cm, 6*cm)
    t.drawOn(c, 1*cm, 18*cm)
    def test0(self):
        '''
        Test case for Indexes. This will draw an index %sat the end of the
        document with dots seperating the indexing terms from the page numbers.
        Index terms are grouped by their first 2, and first 3 characters.
        The page numbers should be clickable and link to the indexed word.
        '''
        # Build story.

        for headers in False, True:
            path = outputfile('test_platypus_index%s.pdf' %
                              (headers and '_headers' or ''))
            doc = MyDocTemplate(path)
            story = []
            styleSheet = getSampleStyleSheet()
            bt = styleSheet['BodyText']

            description = '<font color=red>%s</font>' % (
                self.test0.__doc__ %
                (headers and 'with alphabetic headers ' or ''))
            story.append(Paragraph(description, bt))
            index = SimpleIndex(dot=' . ', headers=headers)

            def addParas(words):
                words = [asUnicode(w) for w in words]
                txt = u' '.join([(len(w) > 5 and u'<index item=%s/>%s' %
                                  (quoteattr(commajoin([w[:2], w[:3], w])), w)
                                  or w) for w in words])
                para = Paragraph(txt, makeBodyStyle())
                story.append(para)

            for i in xrange(20):
                addParas(
                    randomtext.randomText(randomtext.PYTHON, 5).split(' '))
            addParas([
                u + w for u in u'E\xc8\xc9\xca\xcb'
                for w in (u'erily', u'asily')
            ])
            addParas([
                u + w for u in u'A\xc0\xc4\xc1\xc3\xc2'
                for w in (u'dvance', u'ttend')
            ])
            addParas([
                u + w for u in u'O\xd2\xd6\xd3\xd2'
                for w in (u'rdinary', u'verflow')
            ])
            addParas([
                u + w for u in u'U\xd9\xdc\xdb'
                for w in (u'ndertow', u'nbeliever')
            ])
            addParas([
                u + w for u in u'e\xe8\xea\xeb\xe9'
                for w in (u'ventide', u'lision')
            ])
            addParas([
                u + w for u in u'o\xf2\xf5\xf3\xf4'
                for w in (u'verture', u'ntology')
            ])

            #test ampersand in index term
            txt = '\nMarks &amp; Spencer - purveyors of fine groceries, underwear and ampersands - should have their initials displayed however they were input.\n<index item="M&amp;S,groceries"/><index item="M&amp;S,underwear"/><index item="M&amp;S,ampersands"/>'
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

            story.append(index)

            doc.build(story, canvasmaker=index.getCanvasMaker())
Esempio n. 37
0
from django.utils.translation import ugettext as _

from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, \
    Paragraph, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm

# styles
par_style = getSampleStyleSheet()["Normal"]
h1_style = getSampleStyleSheet()["Heading1"]
h2_style = getSampleStyleSheet()["Heading2"]
table_style = TableStyle([
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
])

margin = 1.5 * cm


def h1(text):
    return Paragraph(text, h1_style)


def h2(text):
    return Paragraph(text, h2_style)


def par(text):
    def test4(self):
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']
        bfn = bt.fontName = 'Helvetica'
        bfs = bt.fontSize
        bfl = bt.leading
        canv = Canvas(outputfile('test_platypus_paragraph_line_lengths.pdf'))
        canv.setFont('Courier', bfs, bfl)
        pageWidth, pageHeight = canv._pagesize
        y = pageHeight - 15
        x = stringWidth('999: ', 'Courier', bfs) + 5
        aW = int(pageWidth) - 2 * x

        def doPara(x, text, wc, ns, n, hrep=' ', crep=' ', hdw=0, cdw=0):
            if '{H}' in text:
                text = text.replace('{H}', hrep)
                wc += hdw
            if '{C}' in text:
                text = text.replace('{C}', crep)
                wc += cdw
            p = Paragraph(text, bt)
            w, h = p.wrap(aW, 1000)
            annotations[:] = []
            if measuring:
                ends[:] = []
            p.drawOn(canv, x, y - h)
            canv.saveState()
            canv.setLineWidth(0.1)
            canv.setStrokeColorRGB(1, 0, 0)
            canv.rect(x, y - h, wc, h)

            if n is not None:
                canv.setFillColorRGB(0, 1, 0)
                canv.drawRightString(x, y - h, '%3d: ' % n)

            if annotations:
                canv.setLineWidth(0.1)
                canv.setStrokeColorRGB(0, 1, 0)
                canv.setFillColorRGB(0, 0, 1)
                canv.setFont('Helvetica', 0.2)
                for info in annotations:
                    cur_x = info['cur_x'] + x
                    cur_y = info['cur_y'] + y - h
                    canv.drawCentredString(cur_x, cur_y + 0.3,
                                           '%.2f' % (cur_x - x))
                    canv.line(cur_x, cur_y, cur_x, cur_y + 0.299)
            if measuring:
                if not ends:
                    errors.append(
                        'Paragraph measurement failure no ends found for %s\n%r'
                        % (ns, text))
                elif len(ends) > 1:
                    errors.append(
                        'Paragraph measurement failure no len(ends)==%d for %s\n%r'
                        % (len(ends), ns, text))
                else:
                    cur_x = ends[0]['cur_x']
                    adiff = abs(wc - cur_x)
                    length_errors.append(adiff)
                    if adiff > 1e-8:
                        errors.append(
                            'Paragraph measurement error wc=%.4f measured=%.4f for %s\n%r'
                            % (wc, cur_x, ns, text))
            canv.restoreState()
            return h

        swc = lambda t: stringWidth(t, 'Courier', bfs)
        swcbo = lambda t: stringWidth(t, 'Courier-BoldOblique', bfs)
        swh = lambda t: stringWidth(t, 'Helvetica', bfs)
        swhbo = lambda t: stringWidth(t, 'Helvetica-BoldOblique', bfs)
        swt = lambda t: stringWidth(t, 'Times-Roman', bfs)
        swtb = lambda t: stringWidth(t, 'Times-Bold', bfs)

        apat = re.compile("(<a\\s+name='a\\d+'/>)")
        argv = sys.argv[1:]
        data = (
            (0, "<span fontName='Courier'>Hello{C}</span> World.",
             swc('Hello ') + swh('World.')),
            (1, "<span fontName='Courier'>Hello</span>{H}World.",
             swc('Hello') + swh(' World.')),
            (2,
             " <a name='a2'/><span fontName='Courier'>Hello{C}</span> World.",
             swc('Hello ') + swh('World.')),
            (3,
             " <a name='a3'/><span fontName='Courier'>Hello</span>{H}World.",
             swc('Hello') + swh(' World.')),
            (4,
             "<span fontName='Courier'><a name='a4'/>Hello{C}</span> World.",
             swc('Hello ') + swh('World.')),
            (5, "<span fontName='Courier'><a name='a5'/>Hello</span>{H}World.",
             swc('Hello') + swh(' World.')),
            (6,
             "<span fontName='Courier'>Hello<a name='a6'/>{C}</span> World.",
             swc('Hello ') + swh('World.')),
            (7, "<span fontName='Courier'>Hello<a name='a7'/></span>{H}World.",
             swc('Hello') + swh(' World.')),
            (8,
             "<span fontName='Courier'>Hello{C}<a name='a8'/></span> World.",
             swc('Hello ') + swh('World.')),
            (9, "<span fontName='Courier'>Hello</span><a name='a9'/>{H}World.",
             swc('Hello') + swh(' World.')),
            (10,
             "<span fontName='Courier'>Hello{C}</span> <a name='a10'/>World.",
             swc('Hello ') + swh('World.')),
            (11,
             "<span fontName='Courier'>Hello</span>{H}<a name='a11'/>World.",
             swc('Hello') + swh(' World.')),
            (12,
             "<span fontName='Courier'>Hello{C}</span> World. <a name='a12'/>",
             swc('Hello ') + swh('World.')),
            (13,
             "<span fontName='Courier'>Hello</span>{H}World. <a name='a13'/>",
             swc('Hello') + swh(' World.')),
            (14,
             " <a name='a2'/> <span fontName='Courier'>Hello{C}</span> World.",
             swc('Hello ') + swh('World.')),
            (15,
             " <a name='a3'/> <span fontName='Courier'>Hello</span>{H}World.",
             swc('Hello') + swh(' World.')),
            (16,
             " <a name='a2'/> <span fontName='Courier'>Hello{C}<a name='b'/> </span> <a name='b'/> World.",
             swc('Hello ') + swh('World.')),
            (17,
             " <a name='a3'/> <span fontName='Courier'>Hello</span>{H}<a name='b'/> World.",
             swc('Hello') + swh(' World.')),
            (30,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}</span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (31,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (32,
             " <a name='a2'/><span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}</span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (33,
             " <a name='a3'/><span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (34,
             "<span fontName='Courier'><a name='a4'/>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span> </span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (35,
             "<span fontName='Courier'><a name='a5'/>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (36,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span><a name='a6'/> </span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (37,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span><a name='a7'/></span>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (38,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}<a name='a8'/></span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (39,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span><a name='a9'/>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (40,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}</span> <a name='a10'/>World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (41,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}<a name='a11'/>World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (42,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}</span> World. <a name='a12'/>",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (43,
             "<span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span> World.{H}<a name='a13'/>",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (44,
             " <a name='a2'/> <span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}</span> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (45,
             " <a name='a3'/> <span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
            (46,
             " <a name='a2'/> <span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span>{C}<a name='b'/> </span> <a name='b'/> World.",
             swt('l') + swtb('lo') + swc('He ') + swh('World.')),
            (47,
             " <a name='a3'/> <span fontName='Courier'>He<span face='Times-Roman' color='red'>l</span><span face='Times-Bold' color='orange'>lo</span></span>{H}<a name='b'/> World.",
             swt('l') + swtb('lo') + swc('He') + swh(' World.')),
        )
        _exceptions = {
            1: {
                8: swh(' '),
                12: swh(' '),
                13: swh(' '),
                14: swh(' '),
                15: swh(' '),
                16: swh(' '),
                17: swh(' '),
                38: swh(' '),
                42: swh(' '),
                43: swh(' '),
                44: swh(' '),
                45: swh(' '),
                46: swh(' '),
                47: swh(' '),
            },
        }

        def gex(n, v):
            return _exceptions[1].get(v, 0)

        x1 = x + max(_tmp[2] for _tmp in data) + 5
        x2 = x1 + max(_tmp[2] + 10 + gex(1, _tmp[0]) for _tmp in data) + 5
        x3 = x2 + max(_tmp[2] + 10 + gex(2, _tmp[0]) for _tmp in data) + 5
        x4 = x3 + max(_tmp[2] + 20 + gex(3, _tmp[0]) for _tmp in data) + 5
        annotations = []
        ends = []
        errors = []
        measuring = True
        length_errors = []

        def _onDrawFunc(canv, name, label):
            if measuring and label == 'end':
                ends.append(canv._curr_tx_info)
            annotations.append(canv._curr_tx_info)

        canv._onDrawFunc = _onDrawFunc

        rep0 = '<ondraw name="_onDrawFunc"/>\\1'
        for n, text, wc in data:
            if argv and str(n) not in argv: continue
            text0 = (apat.sub(rep0, text) if rep0 else
                     text) + ('<ondraw name="_onDrawFunc" label="end"/>'
                              if measuring else '')
            ns = str(n)
            h = doPara(x, text0, wc, ns, n)
            if '<a' in text:
                text1 = apat.sub(
                    '<img width="10" height="5" src="pythonpowered.gif"/>',
                    text0)
                doPara(x1, text1, wc + 10 + gex(1, n), ns + '.11', None)
                text2 = apat.sub(
                    '\\1<img width="10" height="5" src="pythonpowered.gif"/>',
                    text0)
                doPara(x2, text1, wc + 10 + gex(2, n), ns + '.12', None)
                text3 = apat.sub(
                    '\\1<img width="10" height="5" src="pythonpowered.gif"/><img width="10" height="5" src="pythonpowered.gif"/>\\1',
                    text0)
                doPara(x3, text3, wc + 20 + gex(3, n), ns + '.13', None)
                doPara(
                    x4,
                    text3,
                    wc + 20 + gex(3, n),
                    ns + '.14',
                    None,
                    hrep='<span face="Courier-BoldOblique"> </span>',
                    crep='<span face="Helvetica-BoldOblique"> </span>',
                    hdw=swcbo(' ') - swhbo(' '),
                    cdw=swhbo(' ') - swcbo(' '),
                )
            else:
                doPara(
                    x1,
                    text0,
                    wc,
                    ns + '.21',
                    None,
                    hrep='<span face="Courier-BoldOblique"> </span>',
                    crep='<span face="Helvetica-BoldOblique"> </span>',
                    hdw=swcbo(' ') - swhbo(' '),
                    cdw=swhbo(' ') - swcbo(' '),
                )
            y -= h + 1
        canv.showPage()
        canv.save()
        if errors:
            raise ValueError('\n'.join(errors))
Esempio n. 39
0
    def Guardar_Lista(self):
        tipo = self.ventanaempleados.cbGuardar_Lista.currentText()
        print(tipo)
        self.db.open()
        consulta = QtSql.QSqlQuery()
        if tipo == "CSV":
            ruta_guardar = ""
            NombreArchivo = QFileDialog.getSaveFileName(
                self, "Guardar Archivo", ruta_guardar)
            if NombreArchivo[0]:
                file = open(NombreArchivo[0] + '.csv', 'w')
                fieldnames = [
                    "CI_RIF", "Nombre", "Apellido", "Correo", "Telefono",
                    "Direccion", "Sueldo"
                ]
                csvsalida = csv.DictWriter(file, fieldnames)
                consulta.exec_("SELECT * FROM Empleados")
                while consulta.next():
                    csvsalida.writerow({
                        fieldnames[0]: consulta.value(0),
                        fieldnames[1]: consulta.value(1),
                        fieldnames[2]: consulta.value(2),
                        fieldnames[3]: consulta.value(3),
                        fieldnames[4]: consulta.value(4),
                        fieldnames[5]: consulta.value(5),
                        fieldnames[6]: consulta.value(6)
                    })
                file.close()
        elif tipo == "PDF":
            ruta_guardar = ""
            NombreArchivo = QFileDialog.getSaveFileName(
                self, "Guardar Archivo", ruta_guardar)
            if NombreArchivo[0]:
                estiloHoja = getSampleStyleSheet()
                story = []
                cuerpo = estiloHoja["BodyText"]
                cuerpo.alignment = TA_CENTER

                col = [
                    "CI_RIF", "Nombre", "Apellido", "Correo", "Telefono",
                    "Direccion", "Sueldo"
                ]
                fil = []
                fil.insert(0, col)
                filasTabla = 0
                consulta.exec_("SELECT * FROM Empleados")
                while consulta.next():
                    fil.insert(filasTabla + 1, [
                        consulta.value(0),
                        consulta.value(1),
                        consulta.value(2),
                        consulta.value(3),
                        consulta.value(4),
                        consulta.value(5),
                        consulta.value(6)
                    ])
                    filasTabla += 1
                datos = [i for i in fil]
                tabla = Table(data=datos,
                              colWidths=[60, 80, 90, 140, 110, 120, 130])
                story.append(tabla)
                doc = SimpleDocTemplate(NombreArchivo[0] + '.pdf',
                                        pagesize=landscape(LETTER),
                                        leftMargin=3,
                                        rightMargin=4,
                                        topMargin=3,
                                        bottomMargin=4)
                doc.build(story)
Esempio n. 40
0
def para(text: str) -> Paragraph:
    """
    Menginputkan text dan mengembalikan paragraph normal
    """
    normal_style = getSampleStyleSheet()["Normal"]
    return Paragraph(text, normal_style)
Esempio n. 41
0
def _build_recap(recaps, payment_ref):
    elements = []
    data = []
    i = 0
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(3, 18))
    elements.append(Paragraph(u"Récapitulatif des notes", styles['Center']))
    elements.append(Spacer(3, 18))

    data.append(("No d'ordre", u"Note no°", u"Nom et prénom", "Montant"))
    total = 0.0
    for recap in recaps:
        i += 1
        data.append((i, recap[0], recap[1], recap[2]))
        total = decimal.Decimal(total) + decimal.Decimal(recap[2])
    data.append(("", "", u"Total", round(total, 2)))

    table = Table(data, [2 * cm, 3 * cm, 7 * cm, 3 * cm, 3 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    elements.append(table)

    elements.append(Spacer(3, 18))

    _intro = Table([[
        u"Veuillez trouver ci-joint le récapitulatif des notes ainsi que le montant total payer"
    ]], [10 * cm, 5 * cm],
                   1 * [0.5 * cm],
                   hAlign='LEFT')
    elements.append(_intro)

    _total_a_payer = Table(
        [["Total " + u"à" + " payer:",
          "%10.2f Euros" % total]], [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    _infos_iban = Table(
        [[u"Numéro compte IBAN: LU55 0019 4555 2516 1000 BCEELULL"]],
        [10 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(_infos_iban)

    elements.append(Spacer(1, 18))
    _infos_iban = Table([[
        u"Lors du virement, veuillez indiquer la référence: %s " %
        payment_ref.upper()
    ]], [10 * cm],
                        1 * [0.5 * cm],
                        hAlign='LEFT')
    elements.append(_infos_iban)

    return elements
Esempio n. 42
0
def _build_invoices(prestations, invoice_number, invoice_date, accident_id,
                    accident_date):
    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    # import pydevd; pydevd.settrace()
    elements = []
    i = 0
    data = []
    patientSocNumber = ''
    patientNameAndFirstName = ''
    patientName = ''
    patientFirstName = ''
    patientAddress = ''

    data.append(('Num. titre', 'Prestation', 'Date', 'Nombre', 'Brut', 'Net',
                 'Heure', 'P. Pers', 'Executant'))
    pytz_luxembourg = pytz.timezone("Europe/Luxembourg")
    for presta in prestations:
        patient = presta.invoice_item.patient
        patientSocNumber = patient.code_sn
        patientNameAndFirstName = patient
        patientName = patient.name
        patientFirstName = patient.first_name
        patientAddress = patient.address
        patientZipCode = patient.zipcode
        patientCity = patient.city
        if presta.carecode.reimbursed:
            i += 1
            data.append((
                i,
                presta.carecode.code,
                (pytz_luxembourg.normalize(presta.date)).strftime('%d/%m/%Y'),
                '1',
                presta.carecode.gross_amount(presta.date),
                presta.carecode.gross_amount(presta.date),
                (pytz_luxembourg.normalize(presta.date)).strftime('%H:%M'),
                "",
                #TODO : replace with Global setting
                "300744-44"))

    for x in range(len(data), 22):
        data.append((x, '', '', '', '', '', '', '', ''))

    newData = []
    for y in range(0, len(data) - 1):
        newData.append(data[y])
        if y % 10 == 0 and y != 0:
            _gross_sum = _compute_sum(data[y - 9:y + 1], 4)
            _net_sum = _compute_sum(data[y - 9:y + 1], 5)
            newData.append(
                ('', '', '', 'Sous-Total', _gross_sum, _net_sum, '', '', ''))
    newData.append(('', '', '', 'Total', _compute_sum(data[1:], 4),
                    _compute_sum(data[1:], 5), '', '', ''))
    _total_facture = _compute_sum(data[1:], 5)

    headerData = [
        [
            'IDENTIFICATION DU FOURNISSEUR DE SOINS DE SANTE\n'
            # TODO : replace with Global setting
            + 'Regine SIMBA\n' + '1A, rue fort wallis\n' +
            'L-2714 Luxembourg\n' + u'Tél: 691.30.85.84',
            'CODE DU FOURNISSEUR DE SOINS DE SANTE\n' + '300744-44'
        ],
        [
            u'Matricule patient: %s' % smart_text(patientSocNumber.strip()) +
            "\n" + u'Nom et Pr' + smart_text("e") +
            u'nom du patient: %s' % smart_text(patientNameAndFirstName),
            u'Nom: %s' % smart_text(patientName.strip()) + '\n' + u'Pr' +
            smart_text(u"é") +
            u'nom: %s' % smart_text(patientFirstName.strip()) + '\n' +
            u'Rue: %s' % patientAddress.strip() + '\n' +
            u'Code postal: %s' % smart_text(patientZipCode.strip()) + '\n' +
            u'Ville: %s' % smart_text(patientCity.strip())
        ],
        [
            u'Date accident: %s\n' % (accident_date if accident_date else "") +
            u'Num. accident: %s' % (accident_id if accident_id else "")
        ]
    ]

    headerTable = Table(headerData, 2 * [10 * cm],
                        [2.5 * cm, 1 * cm, 1.5 * cm])
    headerTable.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('SPAN', (1, 1), (1, 2)),
        ]))

    table = Table(newData, 9 * [2 * cm], 24 * [0.5 * cm])
    table.setStyle(
        TableStyle([
            ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, -1), (-6, -1), 'RIGHT'),
            ('INNERGRID', (0, -1), (-6, -1), 0, colors.white),
            ('ALIGN', (0, -2), (-6, -2), 'RIGHT'),
            ('INNERGRID', (0, -2), (-6, -2), 0, colors.white),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    elements.append(headerTable)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    elements.append(Spacer(1, 18))
    elements.append(
        Paragraph(
            u"Mémoire d'Honoraires Num. %s en date du : %s" %
            (invoice_number, invoice_date), styles['Center']))
    elements.append(Spacer(1, 18))
    elements.append(table)
    elements.append(Spacer(1, 18))
    _total_a_payer = Table(
        [["Total facture:", "%10.2f Euros" % _total_facture]],
        [10 * cm, 5 * cm],
        1 * [0.5 * cm],
        hAlign='LEFT')
    elements.append(Spacer(1, 18))
    elements.append(_total_a_payer)
    elements.append(Spacer(1, 18))

    return {
        "elements": elements,
        "invoice_number": invoice_number,
        "patient_name": patientName + " " + patientFirstName,
        "invoice_amount": newData[23][5]
    }
Esempio n. 43
0
	def create_sheet(self):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT

		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified

		values_dict = {}
##		print len(self.DATA)
		for i in range(len(self.DATA)):
			values_dict["val"+str(i)] = self.DATA[i]
		print(values_dict)

##		print values_dict
##		
		paragraph_list = []
		for i in range(len(values_dict)):
			key = "val"+str(i)
			paragraph_list.append(Paragraph("<b>" + values_dict[key] + "</b><br/>", styNormal))
		print(paragraph_list)

##		#0 row
##		intestazione = Paragraph("<b>SCHEDA INDIVIDUI<br/>" + str(self.datestrfdate()) + "</b>", styNormal)
##		intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)
##
##		#1 row
##		sito = Paragraph("<b>Sito</b><br/>"  + str(self.sito), styNormal)
##		area = Paragraph("<b>Area</b><br/>"  + str(self.area), styNormal)
##		us = Paragraph("<b>US</b><br/>"  + str(self.us), styNormal)
##		nr_inventario = Paragraph("<b>Nr. Individuo</b><br/>"  + str(self.nr_individuo), styNormal)
##
##		#2 row
##		sesso = Paragraph("<b>Sesso</b><br/>"  + self.sesso, styNormal)
##		eta_min = Paragraph("<b>Eta' minima</b><br/>"  + self.eta_min, styNormal)
##		eta_max = Paragraph("<b>Eta' massima</b><br/>"  + self.eta_max, styNormal)
##
##		#3 row
##		classi_eta = Paragraph("<b>Classi di eta'</b><br/>"  + self.classi_eta, styNormal)
##
##		#4 row
##		osservazioni = ''
##		try:
##			osservazioni = Paragraph("<b>Osservazioni</b><br/>" + str(self.osservazioni), styDescrizione)
##		except:
##			pass
##
##		#12 row
##		data_schedatura  = Paragraph("<b>Data schedatura</b><br/>" + self.data_schedatura,styNormal)
##		schedatore = Paragraph("<b>Schedatore</b><br/>" + self.schedatore,styNormal)

		#schema
		cell_schema =  [ #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[paragraph_list[0], 'value', '02', '03', '04','05', '06', '07', paragraph_list[1], '09'],
						[paragraph_list[2], '01', '02', paragraph_list[3], '04', paragraph_list[4],'06', '07', paragraph_list[4], '09'], #1 row ok
						[paragraph_list[5], '01', '02', paragraph_list[6],'04', '05',paragraph_list[7], '07', '08', '09'], #2 row ok
						[paragraph_list[8], '01', '02', '03', '04', '05', '06', '07', '08', '09'], #3 row ok
						[paragraph_list[9], '01','02', '03', '04', '05','06', '07', '08', '09'], #4 row ok
						[paragraph_list[10], '01', '02', '03', '04', '05', paragraph_list[10], '07', '08', '09'], #5 row ok
						['https://sites.google.com/site/pyarchinit/', '01', '02', '03', '04','05', '06', '07','08', '09'] #6 row
						]


		#table style
		table_style=[

					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(7,0)),  #intestazione
					('SPAN', (8,0),(9,0)), #intestazione2

					#1 row
					('SPAN', (0,1),(2,1)),  #sito
					('SPAN', (3,1),(4,1)),  #area
					('SPAN', (5,1),(7,1)),  #us
					('SPAN', (8,1),(9,1)),  #nr_inventario

					#2 row
					('SPAN', (0,2),(2,2)),  #sesso
					('SPAN', (3,2),(5,2)),  #eta_min
					('SPAN', (6,2),(9,2)),  #eta_max
					('VALIGN',(0,2),(9,2),'TOP'), 

					#3 row
					('SPAN', (0,3),(9,3)), #classi_eta
					
					#4 row
					('SPAN', (0,4),(9,4)),  #osservazioni

					#5 row
					('SPAN', (0,5),(5,5)),  #data_schedatura
					('SPAN', (6,5),(9,5)),  #schedatore

					#13 row
					('SPAN', (0,6),(9,6)),  #pie' di pagina
					('ALIGN',(0,6),(9,6),'CENTER')

					]

		t=Table(cell_schema, colWidths=50, rowHeights=None,style= table_style)

		return t
Esempio n. 44
0
 def __init__(self, **kwargs):
     self._style_sheet = getSampleStyleSheet()
     for key in kwargs:
         for style_name in self._style_sheet.byName:
             obj = self._style_sheet[style_name]
             setattr(obj, key, kwargs[key])
Esempio n. 45
0
    def test_document(self):

        rowheights = (24, 16, 16, 16, 16)
        rowheights2 = (24, 16, 16, 16, 30)
        colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32)
        GRID_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 0.25,
                                  colors.black),
                                 ('ALIGN', (1, 1), (-1, -1), 'RIGHT')])

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 6
        styNormal.spaceAfter = 6

        data = (('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12,
                                               33, 2, -2, 44, 89),
                ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32,
                 119), ('Miscellaneous accessories', 0, 0, 0, 0, 0, 0, 1, 0, 0,
                        0, 2, 13), ('Hats', 893, 912, '1,212', 643, 789, 159,
                                    888, '1,298', 832, 453, '1,344', '2,843'))
        data2 = (('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                  'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47,
                                                12, 33, 2, -2, 44, 89),
                 ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32,
                  119), ('Key Ring', 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2,
                         13), ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159,
                               888, '1,298', 832, 453, '1,344', '2,843'))

        data3 = (
            ('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
             'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2,
                                    44, 89),
            ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32,
             119), ('Key Ring', 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2,
                    13),
            (Paragraph(
                "Let's <b>really mess things up with a <i>paragraph</i></b>",
                styNormal), 893, 912, '1,212', 643, 789, 159, 888, '1,298',
             832, 453, '1,344', '2,843'))

        lst = []

        lst.append(
            Paragraph("""Basics about column sizing and cell contents""",
                      styleSheet['Heading1']))

        t1 = Table(data, colwidths, rowheights)
        t1.setStyle(GRID_STYLE)
        lst.append(
            Paragraph(
                "This is GRID_STYLE with explicit column widths.  Each cell contains a string or number\n",
                styleSheet['BodyText']))
        lst.append(t1)
        lst.append(Spacer(18, 18))

        t2 = Table(data, None, None)
        t2.setStyle(GRID_STYLE)
        lst.append(
            Paragraph(
                """This is GRID_STYLE with no size info. It
                                does the sizes itself, measuring each text string
                                and computing the space it needs.  If the text is
                                too wide for the frame, the table will overflow
                                as seen here.""", styNormal))
        lst.append(t2)
        lst.append(Spacer(18, 18))

        t3 = Table(data2, None, None)
        t3.setStyle(GRID_STYLE)
        lst.append(
            Paragraph(
                """This demonstrates the effect of adding text strings with
        newlines to a cell. It breaks where you specify, and if rowHeights is None (i.e
        automatic) then you'll see the effect. See bottom left cell.""",
                styNormal))
        lst.append(t3)
        lst.append(Spacer(18, 18))

        colWidths = (None, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32)
        t3 = Table(data3, colWidths, None)
        t3.setStyle(GRID_STYLE)
        lst.append(
            Paragraph(
                """This table does not specify the size of the first column,
                                so should work out a sane one.  In this case the element
                                at bottom left is a paragraph, which has no intrinsic size
                                (the height and width are a function of each other).  So,
                                it tots up the extra space in the frame and divides it
                                between any such unsizeable columns.  As a result the
                                table fills the width of the frame (except for the
                                6 point padding on either size).""",
                styNormal))
        lst.append(t3)
        lst.append(PageBreak())

        lst.append(
            Paragraph("""Row and Column spanning""", styleSheet['Heading1']))

        lst.append(
            Paragraph(
                """This shows a very basic table.  We do a faint pink grid
        to show what's behind it - imagine this is not printed, as we'll overlay it later
        with some black lines.  We're going to "span" some cells, and have put a
        value of None in the data to signify the cells we don't care about.
        (In real life if you want an empty cell, put '' in it rather than None). """,
                styNormal))

        sty = TableStyle([
            #very faint grid to show what's where
            ('GRID', (0, 0), (-1, -1), 0.25, colors.pink),
        ])

        t = Table(self.getDataBlock(),
                  colWidths=None,
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(
            Paragraph(
                """We now center the text for the "period"
        across the four cells for each quarter.  To do this we add a 'span'
        command to the style to make the cell at row 1 column 3 cover 4 cells,
        and a 'center' command for all cells in the top row. The spanning
        is not immediately evident but trust us, it's happening - the word
        'Period' is centered across the 4 columns.  Note also that the
        underlying grid shows through.  All line drawing commands apply
        to the underlying grid, so you have to take care what you put
        grids through.""", styNormal))
        sty = TableStyle([
            #
            ('GRID', (0, 0), (-1, -1), 0.25, colors.pink),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('SPAN', (2, 0), (5, 0)),
        ])

        t = Table(self.getDataBlock(),
                  colWidths=None,
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(
            Paragraph(
                """We repeat this for the words 'Region', Product'
        and 'Total', which each span the top 2 rows; and for 'Nprth' and 'South'
        which span 3 rows.  At the moment each cell's alignment is the default
        (bottom), so these words appear to have "dropped down"; in fact they
        are sitting on the bottom of their allocated ranges.  You will just see that
        all the 'None' values vanished, as those cells are not drawn any more.""",
                styNormal))
        sty = TableStyle([
            #
            ('GRID', (0, 0), (-1, -1), 0.25, colors.pink),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('SPAN', (2, 0), (5, 0)),
            #span the other column heads down 2 rows
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (1, 1)),
            ('SPAN', (6, 0), (6, 1)),
            #span the 'north' and 'south' down 3 rows each
            ('SPAN', (0, 2), (0, 4)),
            ('SPAN', (0, 5), (0, 7)),
        ])

        t = Table(self.getDataBlock(),
                  colWidths=None,
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(PageBreak())

        lst.append(
            Paragraph(
                """Now we'll tart things up a bit.  First,
        we set the vertical alignment of each spanned cell to 'middle'.
        Next we add in some line drawing commands which do not slash across
        the spanned cells (this needs a bit of work).
        Finally we'll add some thicker lines to divide it up, and hide the pink.  Voila!
        """, styNormal))
        sty = TableStyle([
            #
            #            ('GRID', (0,0), (-1,-1), 0.25, colors.pink),
            ('TOPPADDING', (0, 0), (-1, -1), 3),

            #span the 'period'
            ('SPAN', (2, 0), (5, 0)),
            #span the other column heads down 2 rows
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (1, 1)),
            ('SPAN', (6, 0), (6, 1)),
            #span the 'north' and 'south' down 3 rows each
            ('SPAN', (0, 2), (0, 4)),
            ('SPAN', (0, 5), (0, 7)),

            #top row headings are centred
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            #everything we span is vertically centred
            #span the other column heads down 2 rows
            ('VALIGN', (0, 0), (0, 1), 'MIDDLE'),
            ('VALIGN', (1, 0), (1, 1), 'MIDDLE'),
            ('VALIGN', (6, 0), (6, 1), 'MIDDLE'),
            #span the 'north' and 'south' down 3 rows each
            ('VALIGN', (0, 2), (0, 4), 'MIDDLE'),
            ('VALIGN', (0, 5), (0, 7), 'MIDDLE'),

            #numeric stuff right aligned
            ('ALIGN', (2, 1), (-1, -1), 'RIGHT'),

            #draw lines carefully so as not to swipe through
            #any of the 'spanned' cells
            ('GRID', (1, 2), (-1, -1), 1.0, colors.black),
            ('BOX', (0, 2), (0, 4), 1.0, colors.black),
            ('BOX', (0, 5), (0, 7), 1.0, colors.black),
            ('BOX', (0, 0), (0, 1), 1.0, colors.black),
            ('BOX', (1, 0), (1, 1), 1.0, colors.black),
            ('BOX', (2, 0), (5, 0), 1.0, colors.black),
            ('GRID', (2, 1), (5, 1), 1.0, colors.black),
            ('BOX', (6, 0), (6, 1), 1.0, colors.black),

            # do fatter boxes around some cells
            ('BOX', (0, 0), (-1, 1), 2.0, colors.black),
            ('BOX', (0, 2), (-1, 4), 2.0, colors.black),
            ('BOX', (0, 5), (-1, 7), 2.0, colors.black),
            ('BOX', (-1, 0), (-1, -1), 2.0, colors.black),
        ])

        t = Table(self.getDataBlock(),
                  colWidths=None,
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(Paragraph("""How cells get sized""",
                             styleSheet['Heading1']))

        lst.append(
            Paragraph(
                """So far the table has been auto-sized.  This can be
        computationally expensive, and can lead to yucky effects. Imagine a lot of
        numbers, one of which goes to 4 figures - tha numeric column will be wider.
        The best approach is to specify the column
        widths where you know them, and let the system do the heights.  Here we set some
        widths - an inch for the text columns and half an inch for the numeric ones.
        """, styNormal))

        t = Table(self.getDataBlock(),
                  colWidths=(72, 72, 36, 36, 36, 36, 56),
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(
            Paragraph(
                """The auto-sized example 2 steps back demonstrates
        one advanced feature of the sizing algorithm. In the table below,
        the columns for Q1-Q4 should all be the same width.  We've made
        the text above it a bit longer than "Period".  Note that this text
        is technically in the 3rd column; on our first implementation this
        was sized and column 3 was therefore quite wide.  To get it right,
        we ensure that any cells which span columns, or which are 'overwritten'
        by cells which span columns, are assigned zero width in the cell
        sizing.  Thus, only the string 'Q1' and the numbers below it are
        calculated in estimating the width of column 3, and the phrase
        "What time of year?" is not used.  However, row-spanned cells are
        taken into account. ALL the cells in the leftmost column
        have a vertical span (or are occluded by others which do)
        but it can still work out a sane width for them.

        """, styNormal))

        data = self.getDataBlock()
        data[0][2] = "Which time of year?"
        #data[7][0] = Paragraph("Let's <b>really mess things up with a <i>paragraph</i>",styNormal)
        t = Table(
            data,
            #colWidths=(72,72,36,36,36,36,56),
            rowHeights=None,
            style=sty)
        lst.append(t)

        lst.append(
            Paragraph("""Paragraphs and unsizeable objects in table cells.""",
                      styleSheet['Heading1']))

        lst.append(
            Paragraph(
                """Paragraphs and other flowable objects make table
        sizing much harder. In general the height of a paragraph is a function
        of its width so you can't ask it how wide it wants to be - and the
        REALLY wide all-on-one-line solution is rarely what is wanted. We
        refer to Paragraphs and their kin as "unsizeable objects". In this example
        we have set the widths of all but the first column.  As you can see
        it uses all the available space across the page for the first column.
        Note also that this fairly large cell does NOT contribute to the
        height calculation for its 'row'.  Under the hood it is in the
        same row as the second Spam, but this row gets a height based on
        its own contents and not the cell with the paragraph.

        """, styNormal))

        data = self.getDataBlock()
        data[5][0] = Paragraph(
            "Let's <b>really mess things up</b> with a <i>paragraph</i>, whose height is a function of the width you give it.",
            styNormal)
        t = Table(data,
                  colWidths=(None, 72, 36, 36, 36, 36, 56),
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(
            Paragraph(
                """This one demonstrates that our current algorithm
        does not cover all cases :-(  The height of row 0 is being driven by
        the width of the para, which thinks it should fit in 1 column and not 4.
        To really get this right would involve multiple passes through all the cells
        applying rules until everything which can be sized is sized (possibly
        backtracking), applying increasingly dumb and brutal
        rules on each pass.
        """, styNormal))
        data = self.getDataBlock()
        data[0][2] = Paragraph(
            "Let's <b>really mess things up</b> with a <i>paragraph</i>.",
            styNormal)
        data[5][0] = Paragraph(
            "Let's <b>really mess things up</b> with a <i>paragraph</i>, whose height is a function of the width you give it.",
            styNormal)
        t = Table(data,
                  colWidths=(None, 72, 36, 36, 36, 36, 56),
                  rowHeights=None,
                  style=sty)
        lst.append(t)

        lst.append(
            Paragraph(
                """To avoid these problems remember the golden rule
        of ReportLab tables:  (1) fix the widths if you can, (2) don't use
        a paragraph when a string will do.
        """, styNormal))

        lst.append(
            Paragraph(
                """Unsized columns that contain flowables without
        precise widths, such as paragraphs and nested tables,
        still need to try and keep their content within borders and ideally 
        even honor percentage requests.  This can be tricky--and expensive.  
        But sometimes you can't follow the golden rules.
        """, styNormal))

        lst.append(
            Paragraph(
                """The code first calculates the minimum width
        for each unsized column by iterating over every flowable in each column
        and remembering the largest minimum width.  It then allocates
        available space to accomodate the minimum widths.  Any remaining space
        is divided up, treating a width of '*' as greedy, a width of None as
        non-greedy, and a percentage as a weight.  If a column is already
        wider than its percentage warrants, it is not further expanded, and
        the other widths accomodate it.
        """, styNormal))

        lst.append(
            Paragraph(
                """For instance, consider this tortured table.
        It contains four columns, with widths of None, None, 60%, and 20%,
        respectively, and a single row.  The first cell contains a paragraph.
        The second cell contains a table with fixed column widths that total 
        about 50% of the total available table width.  The third cell contains
        a string.  The last cell contains a table with no set widths but a 
        single cell containing a paragraph.
        """, styNormal))
        ministy = TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
        ])
        nested1 = [
            Paragraph('This is a paragraph.  The column has a width of None.',
                      styNormal)
        ]
        nested2 = [
            Table([[
                Paragraph(
                    'This table is set to take up two and a half inches.  The '
                    'column that holds it has a width of None.', styNormal)
            ]],
                  colWidths=(180, ),
                  rowHeights=None,
                  style=ministy)
        ]
        nested3 = '60% width'
        nested4 = [
            Table([[[
                Paragraph(
                    "This is a table with a paragraph in it but no width set.  "
                    "The column width in the containing table is 20%.",
                    styNormal)
            ]]],
                  colWidths=(None, ),
                  rowHeights=None,
                  style=ministy)
        ]
        t = Table([[nested1, nested2, nested3, nested4]],
                  colWidths=(None, None, '60%', '20%'),
                  rowHeights=None,
                  style=ministy)
        lst.append(t)

        lst.append(
            Paragraph(
                """Notice that the second column does expand to
        account for the minimum size of its contents; and that the remaining
        space goes to the third column, in an attempt to honor the '60%' 
        request as much as possible.  This is reminiscent of the typical HTML
        browser approach to tables.""", styNormal))

        lst.append(
            Paragraph(
                """To get an idea of how potentially expensive
        this is, consider the case of the last column: the table gets the
        minimum width of every flowable of every cell in the column.  In this
        case one of the flowables is a table with a column without a set
        width, so the nested table must itself iterate over its flowables. 
        The contained paragraph then calculates the width of every word in it
        to see what the biggest word is, given the set font face and size.  It
        is easy to imagine creating a structure of this sort that took an
        unacceptably large amount of time to calculate.  Remember the golden
        rule, if you can. """, styNormal))

        lst.append(
            Paragraph("""This code does not yet handle spans well.""",
                      styNormal))

        SimpleDocTemplate(outputfile('test_table_layout.pdf'),
                          showBoundary=1).build(lst)
Esempio n. 46
0
    def create_dictionary(self):
        self.file = self.parcial_path + "/dictionary_" + self.table.name + ".pdf"
        doc = SimpleDocTemplate(self.file, pagesize=landscape(A4))

        story = list()

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(
                name='CustomTitle',
                fontName='Times-Bold',
                fontSize=14,
                alignment=TA_CENTER,
                textColor=colors.black,
            ))

        # Title
        title = "DICIONÁRIO DE DADOS"
        story.append(Paragraph(title, styles['CustomTitle']))
        story.append(Spacer(1, 48))

        # Basic Info
        story.append(Paragraph("<b>RECURSO: </b>", styles['Normal']))
        story.append(Spacer(1, 4))
        story.append(Paragraph(self.resource.name, styles['Normal']))
        story.append(Spacer(1, 10))

        story.append(
            Paragraph("<b>FREQUÊNCIA DE ATUALIZAÇÃO: </b>", styles['Normal']))
        story.append(Spacer(1, 4))

        if self.resource.schedule_type == Resource.TYPE_DAY:
            story.append(Paragraph('DIARIAMENTE', styles['Normal']))
        elif self.resource.schedule_type == Resource.TYPE_WEEK:
            story.append(Paragraph('SEMANALMENTE', styles['Normal']))
        elif self.resource.schedule_type == Resource.TYPE_MONTH:
            story.append(Paragraph('MENSALMENTE', styles['Normal']))
        elif self.resource.schedule_type == Resource.TYPE_YEAR:
            story.append(Paragraph('ANUALMENTE', styles['Normal']))

        story.append(Spacer(1, 10))

        story.append(Paragraph('<b>DESCRIÇÃO:</b>', styles['Normal']))
        story.append(
            Paragraph(self.data_dictionary.description, styles['Normal']))

        story.append(Spacer(1, 6))

        # TABLE

        # Table Title
        story.append(Spacer(1, 48))

        # Table Data
        data = [
            ['COLUNA', 'TIPO', 'TAMANHO', 'ACEITA NULO', 'DESCRIÇÃO'],
        ]

        for column in DBColumn.objects.filter(
                db_table=self.table).order_by('id'):

            aceita_nulo = 'NÃO'
            if column.not_null == 'YES':
                aceita_nulo = 'SIM'

            tamanho = ''
            if column.size > 0:
                tamanho = column.size

            data.append([
                column.name,
                column.type.upper(), tamanho, aceita_nulo,
                column.dd_description
            ])

        for temp_table in DBTable.objects.filter(db_table=self.table):
            for column in DBColumn.objects.filter(
                    db_table=temp_table).order_by('id'):

                aceita_nulo = 'NÃO'
                if column.not_null == 'YES':
                    aceita_nulo = 'SIM'

                tamanho = ''
                if column.size > 0:
                    tamanho = column.size

                data.append([
                    temp_table.name + "_" + column.name,
                    column.type.upper(), tamanho, aceita_nulo,
                    column.dd_description
                ])

        table = Table(data,
                      colWidths=(60 * mm, 50 * mm, 25 * mm, 30 * mm, 80 * mm))

        table_style = TableStyle()
        table_style.add('BOX', (0, 0), (-1, -1), 0.50, colors.black)
        table_style.add('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black)
        table_style.add('FONTNAME', (0, 0), (-1, 0), 'Times-Bold')
        table_style.add('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey)
        table_style.add('ALIGNMENT', (2, 1), (-1, -1), 'CENTER')

        table.setStyle(table_style)

        story.append(table)

        doc.build(story)
    def create_report_pdf(self):
        PAGE_HEIGHT = defaultPageSize[1]
        styles = getSampleStyleSheet()
        total_amount = "0"
        #styles.add(ParagraphStyle(name="x", fontSize=12, leading = 7, alignment=TA_LEFT))
        #styles.add(ParagraphStyle(name="x2", fontSize=10, leading = 7, alignment=TA_LEFT))

        connection = sqlite3.connect("fci.db")
        results = connection.execute(
            "SELECT  PRINTER_HEATER_TITLE,PRINTER_HEADER,PRINTER_FOOTER FROM GLOBAL_VAR"
        )
        for x in results:
            Title = Paragraph(str(x[0]), styles["Title"])
            ptext = "<font name=Helvetica size=10>" + str(x[1]) + " </font>"
            Title2 = Paragraph(str(ptext), styles["Title"])
        connection.close()

        connection = sqlite3.connect("fci.db")
        results = connection.execute(
            "SELECT count(*) FROM WEIGHT_MST_FCI_VW " + str(self.whr_sql2))
        for x in results:
            total_amount = str(x[0])
        connection.close()

        summary_data = [[
            "From Date: " + str(self.from_dt), "To Date: " + str(self.to_dt),
            "Total Trucks: " + str(total_amount), "Report Date: " +
            str(datetime.datetime.now().strftime("%d %b %Y %H:%M"))
        ]]

        f3 = Table(summary_data)
        #f3.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.20, colors.black),('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),('FONT', (0, 0), (-1, -1), "Helvetica", 10)]))

        Elements = [
            Title,
            Spacer(1, 12), Title2,
            Spacer(1, 12), f3,
            Spacer(1, 12),
            Spacer(1, 12)
        ]

        childs_data = []
        childs_data = [[
            'Serial ID.', 'Recipt Id', ' Vehicle.No ', 'Material Name',
            ' Net Wt.', ' Tare Wt.', ' Gross Wt.', 'Storage Name'
        ]]
        connection = sqlite3.connect("fci.db")

        results = connection.execute(
            "SELECT SERIAL_ID_DISPLY,(SELECT A.BATCH_ID_DISPLAY FROM BATCH_MST A WHERE A.BATCH_ID=BATCH_ID) as BATCH_ID,VEHICLE_NO,MATERIAL_NAME,printf(\"%3d\",IFNULL(NET_WEIGHT_VAL,0)),printf(\"%3d\", TARE_WT_VAL) as TARE_WT_VAL,printf(\"%6d\", GROSS_WT_VAL) as GROSS_WT_VAL,TARGET_STORAGE FROM WEIGHT_MST_FCI_VW "
            + str(self.whr_sql2))
        for k in results:
            childs_data.append(k)
        connection.close()
        f = Table(childs_data)
        f.setStyle(
            TableStyle([("BOX", (0, 0), (-1, -1), 0.20, colors.black),
                        ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),
                        ('FONT', (0, 0), (-1, -1), "Helvetica", 9)]))

        Elements.append(f)

        doc = SimpleDocTemplate('./reports/dr_other_report.pdf', pagesize=A4)
        doc.pagesize = landscape(A4)
        doc.build(Elements)
        print("Done")
        self.filter_col_name = ""
    def test0(self):
        "This makes one long multi-page paragraph."

        # Build story.
        story = []

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.spaceBefore = 18
        bt = styleSheet['BodyText']
        bt.spaceBefore = 6

        story.append(Paragraph('Test of context-relative indentation', h1))

        story.append(Spacer(18, 18))

        story.append(Indenter(0, 0))
        story.append(
            Paragraph(
                "This should be indented 0 points at each edge. " +
                ("spam " * 25), bt))
        story.append(Indenter(0, 0))

        story.append(Indenter(36, 0))
        story.append(
            Paragraph(
                "This should be indented 36 points at the left. " +
                ("spam " * 25), bt))
        story.append(Indenter(-36, 0))

        story.append(Indenter(0, 36))
        story.append(
            Paragraph(
                "This should be indented 36 points at the right. " +
                ("spam " * 25), bt))
        story.append(Indenter(0, -36))

        story.append(Indenter(36, 36))
        story.append(
            Paragraph(
                "This should be indented 36 points at each edge. " +
                ("spam " * 25), bt))
        story.append(Indenter(36, 36))
        story.append(
            Paragraph(
                "This should be indented a FURTHER 36 points at each edge. " +
                ("spam " * 25), bt))
        story.append(Indenter(-72, -72))

        story.append(
            Paragraph(
                "This should be back to normal at each edge. " +
                ("spam " * 25), bt))

        story.append(Indenter(36, 36))
        story.append(
            Paragraph(("""This should be indented 36 points at the left
        and right.  It should run over more than one page and the indent should
        continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') *
                      20, bt))
        story.append(Indenter(-36, -36))

        story.append(NextPageTemplate('updown'))
        story.append(FrameBreak())
        story.append(
            Paragraph('Another test of context-relative indentation', h1))
        story.append(NextPageTemplate(
            'normal'))  # so NEXT page is different template...
        story.append(
            Paragraph(
                """This time we see if the indent level is continued across
            frames...this page has 2 frames, let's see if it carries top to bottom. Then
            onto a totally different template.""", bt))

        story.append(Indenter(0, 0))
        story.append(
            Paragraph(
                "This should be indented 0 points at each edge. " +
                ("spam " * 25), bt))
        story.append(Indenter(0, 0))
        story.append(Indenter(36, 72))
        story.append(
            Paragraph(("""This should be indented 36 points at the left
        and 72 at the right.  It should run over more than one frame and one page, and the indent should
        continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') *
                      35, bt))

        story.append(Indenter(-36, -72))
        story.append(
            Paragraph(
                "This should be back to normal at each edge. " +
                ("spam " * 25), bt))
        doc = MyDocTemplate(outputfile('test_platypus_indents.pdf'))
        doc.multiBuild(story)
Esempio n. 49
0
def _test0(self):
    "This makes one long multi-page paragraph."
    from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile

    # Build story.
    story = []

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1
    h1.outlineLevel = 0

    h2 = styleSheet['Heading2']
    h2.backColor = colors.cyan
    h2.keepWithNext = 1
    h2.outlineLevel = 1

    bt = styleSheet['BodyText']

    story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
    story.append(
        Paragraph(
            """
        Subsequent pages test cross-references: indexes, tables and individual
        cross references.  The number in brackets at the end of each paragraph
        is its position in the story. (%d)""" % len(story), bt))

    story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
    toc = TableOfContents()
    story.append(toc)

    chapterNum = 1
    for i in range(10):
        story.append(
            Paragraph(
                'Chapter %d: Chapters always starts a new page' % chapterNum,
                h1))
        chapterNum = chapterNum + 1
        for j in range(3):
            story.append(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            story.append(
                Paragraph(
                    'Heading 2 should always be kept with the next thing (%d)'
                    % len(story), h2))
            for j in range(3):
                story.append(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                story.append(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h2))
                story.append(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))
    story.append(Paragraph('The Index which goes at the back', h1))
    story.append(SimpleIndex())

    doc = MyDocTemplate(outputfile('test_platypus_xref.pdf'))
    doc.multiBuild(story)
Esempio n. 50
0
def form_01(request_data):
    """
    Форма Лист на оплату по созданным направлениям на услуги
    """
    form_name = "Маршрутный лист"

    ind_card = Card.objects.get(pk=request_data["card_pk"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)
    ind_dir = json.loads(request_data["dir"])

    # Получить данные с клиента физлицо-ФИО, пол, дата рождения
    individual_fio = ind.fio()
    individual_date_born = ind.bd()

    # Получить все источники, у которых title-ПЛАТНО
    ist_f = list(
        IstochnikiFinansirovaniya.objects.values_list('id').filter(
            title__exact='Платно'))
    ist_f_list = [int(x[0]) for x in ist_f]

    napr = Napravleniya.objects.filter(id__in=ind_dir)
    dir_temp = []

    # Проверить, что все направления принадлежат к одной карте и имеют ист. финансирования "Платно"
    for n in napr:
        if (n.istochnik_f_id in ist_f_list) and (n.client == ind_card):
            dir_temp.append(n.pk)

    # получить по направлению-услугам цену из Issledovaniya
    hospital_name = "ОГАУЗ \"Иркутская медикосанитарная часть ИАПО\""
    hospital_address = "г. Иркутс, ул. Жукова 9"

    # Получить данные физлицо-документы: паспорт, полис, снилс
    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_issued = documents['passport']['issued']
    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    # Генерировать pdf-Лист на оплату
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=10 * mm,
                            rightMargin=5 * mm,
                            topMargin=6 * mm,
                            bottomMargin=5 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("Лист на оплату"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 13
    style.leading = 12
    style.spaceAfter = 0 * mm
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 12
    styleCenter.leading = 10
    styleCenter.spaceAfter = 0 * mm
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 20
    styleCenterBold.leading = 15
    styleCenterBold.face = 'PTAstraSerifBold'
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    date_now = ''

    objs = [
        Paragraph('{}'.format(hospital_name), styleCenter),
        Spacer(1, 1 * mm),
        Paragraph('({} тел. 28-61-00)'.format(hospital_address), styleCenter),
        Spacer(1, 3 * mm),
        Paragraph('{}'.format(form_name), styleCenterBold),
        Spacer(1, 4 * mm),
        Paragraph('<font size = 11> <u> {}</u> </font>'.format(date_now),
                  styleCenter),
        Paragraph('<font size = 8> дата оформления </font>', styleCenter),
    ]

    styleTCenter = deepcopy(styleCenter)
    styleTCenter.alignment = TA_CENTER
    styleTCenter.leading = 3.5 * mm

    styleTBold = deepcopy(styleCenterBold)
    styleTBold.fontSize = 14
    styleTBold.alignment = TA_LEFT

    num = ind_card.number
    barcode128 = code128.Code128(num, barHeight=9 * mm, barWidth=1.25)

    opinion = [
        [
            Paragraph('№ карты:', style),
            Paragraph(num + "-" + "(" + num + ")", styleTBold), barcode128
        ],
    ]

    tbl = Table(opinion, colWidths=(23 * mm, 75 * mm, 100 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.0 * mm),
            ('BOTTOMPADDING', (1, 0), (1, 0), 1.0 * mm),
            ('ALIGN', (-1, 0), (-1, -1), 'RIGHT'),
        ]))

    objs.append(Spacer(1, 2 * mm))
    objs.append(tbl)

    opinion = [
        [
            Paragraph('', style),
            Paragraph('', style),
        ],
        [
            Paragraph('Пациент:', style),
            Paragraph(individual_fio, style),
        ],
        [
            Paragraph('Паспорт:', style),
            Paragraph(
                'серия: {} &nbsp;&nbsp;&nbsp;&nbsp; номер: {} &nbsp;&nbsp;&nbsp;&nbsp; дата выдачи: {}'
                .format(document_passport_serial, document_passport_num,
                        document_passport_issued),
                style,
            ),
        ],
        [
            Paragraph('Д/р:', style),
            Paragraph(individual_date_born, style),
        ],
    ]

    tbl = Table(opinion, colWidths=(23 * mm, 175 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.1 * mm),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ]))

    objs.append(Spacer(1, 2 * mm))
    objs.append(tbl)

    styleTB = deepcopy(style)
    styleTB.fontSize = 11.5
    styleTB.alignment = TA_CENTER
    styleTB.fontName = "PTAstraSerifBold"

    styleTC = deepcopy(style)
    styleTC.fontSize = 10.5
    styleTC.alignment = TA_LEFT

    styleTCright = deepcopy(styleTC)
    styleTCright.alignment = TA_RIGHT

    styleTCcenter = deepcopy(styleTC)
    styleTCcenter.alignment = TA_CENTER

    opinion = [
        [
            Paragraph('Код услуги', styleTB),
            Paragraph('Направление', styleTB),
            Paragraph('Услуга', styleTB),
            Paragraph('Информация', styleTB),
            Paragraph('Утвержденный перечень исследований', styleTB),
        ],
    ]

    example_template = [
        [
            Paragraph('1.2.3', style),
            Paragraph('4856397', style),
            Paragraph('Полный гематологический анализ', style),
            Paragraph('', style),
            Paragraph('', style),
        ],
        [
            Paragraph('1.2.3', style),
            Paragraph('97', style),
            Paragraph('ЛОР', style),
            Paragraph('каб.45', style),
            Paragraph('Аудиометрия, Исследование вестибулярного анализатора',
                      style),
        ],
        [
            Paragraph('1.2.3', style),
            Paragraph('4856398', style),
            Paragraph('Офтальмолог', style),
            Paragraph('каб.14 с 8.00 до 15.00', style),
            Paragraph(
                'биомикроскопия переднего отрезка глаза, Острота зрения, поле зрения',
                style),
        ],
        [
            Paragraph('1.2', style),
            Paragraph('98', style),
            Paragraph('Рентгенография грудной клетки в 2 проекциях', style),
            Paragraph('каб.19 с 8.00 до 15.00', style),
            Paragraph('', style),
        ],
        [
            Paragraph('1.5', style),
            Paragraph('981', style),
            Paragraph('Спирометрия', style),
            Paragraph('каб.16 с 9.00 до 15.00', style),
            Paragraph('', style),
        ],
    ]

    opinion.extend(example_template)

    tbl = Table(opinion,
                colWidths=(18 * mm, 25 * mm, 52 * mm, 45 * mm, 59 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

    objs.append(Spacer(1, 2 * mm))
    objs.append(tbl)
    objs.append(Spacer(1, 2 * mm))
    objs.append(Spacer(1, 2 * mm))

    objs.append(Spacer(1, 2 * mm))
    objs.append(Spacer(1, 7 * mm))

    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Esempio n. 51
0
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Frame
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
import time
from export import *
import sort
import user

stylesheet=getSampleStyleSheet()

# Formatting PDF files using reportlab

def drawTime(textList, style):
	newList = []
	for text in textList:
		newLine = "<strong>"+text.getActualTime()+"</strong>-"+"<i>"+text.user+"</i>: "+text.content
		newList.append(Paragraph(newLine, style=style))
	return newList

def exportToPDF(alltext):

	styles = getSampleStyleSheet()
	styleN = styles['Normal']
	styleH = styles['Heading1']
	# Cited from https://www.reportlab.com/docs/reportlab-userguide.pdf
	body = ParagraphStyle(fontName='Times', fontSize=12, name="TOCHeading1",
 			firstLineIndent=40, leading=16,spaceAfter = 6, spaceBefore = 6)
	heading = ParagraphStyle(fontName='Times-Bold', fontSize=16, name="TOCHeading1",
			leading=16,spaceAfter = 12, spaceBefore = 6, alignment=1)
Esempio n. 52
0
    def Guardar(self):
        tipo = self.ventanahabitaciones.cBGuardar.currentText()
        if tipo == "CSV":
            ruta_guardar = ""
            NombreArchivo = QFileDialog.getSaveFileName(
                self, "Guardar Archivo", ruta_guardar)
            if NombreArchivo[0]:
                file = open(NombreArchivo[0] + '.csv', 'w')
                self.db.open()
                consulta = QtSql.QSqlQuery()
                consulta.exec_("SELECT * FROM Habitaciones")
                fieldnames = [
                    "Numero_Codigo", "Piso", "Estado", "Capacidad", "Asignado"
                ]
                csvsalida = csv.DictWriter(file, fieldnames)
                while consulta.next():
                    csvsalida.writerow({
                        fieldnames[0]: consulta.value(0),
                        fieldnames[1]: consulta.value(1),
                        fieldnames[2]: consulta.value(2),
                        fieldnames[3]: consulta.value(3),
                        fieldnames[4]: consulta.value(4)
                    })
                file.close()
        elif tipo == "PDF":
            ruta_guardar = ""
            NombreArchivo = QFileDialog.getSaveFileName(
                self, "Guarfar Archivo", ruta_guardar)
            if NombreArchivo[0]:
                self.db.open()
                consulta = QtSql.QSqlQuery()
                consulta.exec_("SELECT * FROM Habitaciones")
                estiloHoja = getSampleStyleSheet()
                story = []
                cuerpo = estiloHoja["BodyText"]
                cuerpo.alignment = TA_CENTER

                col = [
                    "Numero_Codigo", "Piso", "Estado", "Capacidad", "Asignado"
                ]
                fil = []
                fil.insert(0, col)
                fila = 1
                while consulta.next():
                    fil.insert(fila, [
                        consulta.value(0),
                        consulta.value(1),
                        consulta.value(2),
                        consulta.value(3),
                        consulta.value(4)
                    ])
                    fila += 1
                datos = [i for i in fil]
                tabla = Table(data=datos, colWidths=[90, 60, 80, 60, 80])
                story.append(tabla)
                doc = SimpleDocTemplate(NombreArchivo[0] + '.pdf',
                                        pagesize=portrait(LETTER),
                                        leftMargin=3,
                                        rightMargin=4,
                                        topMargin=3,
                                        bottomMargin=4)
                doc.build(story)
def speedValidator():
    #Go through the filepath text - which is created from the drag and drop GUI.

    filepath = "/usr/local/Library/Digilog_Utilites.txt"
    filetext = open(filepath, 'r')

    routesdir = []
    for path in filetext:
        routesdir.append(path.strip())

    rspfilepaths = []
    for route in routesdir:
        os.chdir(route)
        for files in glob.glob("*.rsp"):
            rspfilepaths.append(route + files)

    fileDir = eg.diropenbox(msg="Where would you like your Speed Reports?",
                            title="Choose the directory for your Reports.")

    #     rspfilepaths = []
    # #     RouteDirs = get_immediate_subdirectories(fileDir)
    #
    #     for dirs in RouteDirs:
    #         fulldir = os.path.join(fileDir,dirs)
    #         os.chdir(fulldir)

    #Make a bunch of lists of the items that I will need from each route.
    MaximumList = []
    MinimumList = []
    AverageList = []
    listoftenthavgspeedlist = []
    listoflistsofspeedlist = []
    stdevList = []
    listofspeedlists = []
    cnt = 1
    for thisrsp in rspfilepaths:
        speedList, interval = getrspinfo(thisrsp)

        #Averages:
        total = 0
        speedlistfloat = []
        for num in speedList:
            speedlistfloat.append(float(num))
            total = float(num) + total
            listofspeedlists.append(float(num))
        listoflistsofspeedlist.append(listofspeedlists)
        lengthList = float(len(speedList))
        average = float(total) / float(lengthList)
        AverageList.append(average)

        #min and max:
        maximumspeed = max(speedlistfloat)
        minimumspeed = min(speedlistfloat)
        MaximumList.append(float(maximumspeed))
        MinimumList.append(float(minimumspeed))

        #stdev:
        stdSpeedList = []
        for num in speedList:
            stdSpeedList.append(float(num))
        stdev = numpy.std(stdSpeedList)
        stdevList.append(stdev)

        #get the tenth of a route list
        listoftenthavgspeedlist.append(
            getlistaverageforten(speedList, lengthList)
        )  #This will be a list of the averages of a tenth of the route.

        #Distance list
        xdistanceAxis_notrounded = []
        for i in range(0, int(lengthList)):
            xdistanceAxis_notrounded.append(i * interval)
            xmax = i * interval
        xdistanceAxis = []
        for number in xdistanceAxis_notrounded:
            xdistanceAxis.append(round(number, 4))

        #Graph:
        plt.plot(xdistanceAxis, speedList, label='route ' +
                 str(cnt))  #Don't want the entire route's name in the legend.
        plt.ylabel("Speed (mph)")
        plt.xlabel("Distance (miles )")
        ymax = float(maximumspeed) + int(5)
        ymin = float(minimumspeed) - int(10)
        plt.axis([0, xmax, ymin, ymax])
        legend(loc=4,
               ncol=2,
               mode="expand",
               borderaxespad=0,
               prop={'size': 10})
        plt.title(os.path.basename(fileDir) + " Speed Validation")

        #Count for the graph legend
        cnt = cnt + 1

    graphPath = fileDir + '/' + os.path.basename(fileDir) + "_Graph.pdf"
    plt.savefig(graphPath)

    #total routes std dev.
    totalstdev = numpy.mean(stdevList)
    if totalstdev >= 0.5:
        passfail = "Fail"
    else:
        passfail = "Pass"

    #total maximum/minimum
    totalMax = max(MaximumList)
    totalMin = min(MinimumList)

    #Total average of all the routes.
    totalspeed = 0
    for numb in AverageList:
        totalspeed = numb + totalspeed
    totalcount = len(AverageList)
    totalaverage = float(totalspeed) / totalcount
    totalaverage = round(totalaverage, 1)

    #the rounded values for the averagelist.  This is not used really.
    roundAvgList = []
    for avgnum in AverageList:
        roundAvgList.append(round(avgnum, 1))

    #WAYYYY TOOO many variables put into this function.  Probably not the best programming technique.
    textFilePath = createthetextfile(fileDir, listoftenthavgspeedlist,
                                     MaximumList, MinimumList, rspfilepaths,
                                     stdevList, roundAvgList, totalstdev,
                                     totalMax, totalMin, totalaverage,
                                     passfail)
    #________________________________________________________________________________________________________________________________
    MainPDFPath = fileDir + "/" + os.path.basename(fileDir) + "_Validation.pdf"

    #Read the data from the text file
    MainValidation = open(textFilePath, 'r')
    Data = []
    for line in MainValidation:
        Data.append(line)
    MainValidation.close()

    elements = []
    styles = getSampleStyleSheet()
    doc = SimpleDocTemplate(MainPDFPath)

    # Create two 'Paragraph' Flowables and add them to our 'elements'
    count = 1
    for line in Data:
        if count == 1:  #This is the title line.
            elements.append(
                Paragraph('<font size = 18>' + line + '</font',
                          styles['Heading1']))
            elements.append(Paragraph('\n', styles['Heading1']))
        elif count == 7:  #This is the line at the end of the validation summary.
            elements.append(Paragraph('<br/>', styles['Heading1']))
            elements.append(Paragraph('<br/>', styles['Heading1']))
            elements.append(
                Paragraph('<font size = 14>' + line + '</font',
                          styles['Normal']))
            elements.append(Paragraph('<br/>', styles['Heading1']))
            elements.append(Paragraph('<br/>', styles['Heading1']))
            elements.append(Paragraph('<br/>', styles['Heading1']))
        else:
            elements.append(
                Paragraph('<font size = 10>' + line + '</font',
                          styles['Normal']))
        count = count + 1
    # Write the document to disk
    doc.build(elements)
    #________________________________________________________________________________________________________________________________
    #remove that text file and then display an ending message.
    os.remove(textFilePath)
    window = Tk()
    window.wm_withdraw()
    tkMessageBox.showinfo(title="This is the End", message="Work Complete.")
Esempio n. 54
0
File: test.py Progetto: wondie/stdm
def fullTest(fileName="test_full.pdf"):
    """Creates large-ish test document with a variety of parameters"""

    story = []

    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    styleH2 = styles['Heading2']
    story = []

    story.append(Paragraph('ReportLab Barcode Test Suite - full output', styleH))
    story.append(Paragraph('Generated on %s' % time.ctime(time.time()), styleN))

    story.append(Paragraph('', styleN))
    story.append(Paragraph('Repository information for this build:', styleN))
    #see if we can figure out where it was built, if we're running in source
    if os.path.split(os.getcwd())[-1] == 'barcode' and os.path.isdir('.svn'):
        #runnning in a filesystem svn copy
        infoLines = os.popen('svn info').read()
        story.append(Preformatted(infoLines, styles["Code"]))
        
    story.append(Paragraph('About this document', styleH2))
    story.append(Paragraph('History and Status', styleH2))

    story.append(Paragraph("""
        This is the test suite and docoumentation for the ReportLab open source barcode API,
        being re-released as part of the forthcoming ReportLab 2.0 release.
        """, styleN))

    story.append(Paragraph("""
        Several years ago Ty Sarna contributed a barcode module to the ReportLab community.
        Several of the codes were used by him in hiw work and to the best of our knowledge
        this was correct.  These were written as flowable objects and were available in PDFs,
        but not in our graphics framework.  However, we had no knowledge of barcodes ourselves
        and did not advertise or extend the package.
        """, styleN))

    story.append(Paragraph("""
        We "wrapped" the barcodes to be usable within our graphics framework; they are now available
        as Drawing objects which can be rendered to EPS files or bitmaps.  For the last 2 years this
        has been available in our Diagra and Report Markup Language products.  However, we did not
        charge separately and use was on an "as is" basis.
        """, styleN))

    story.append(Paragraph("""
        A major licensee of our technology has kindly agreed to part-fund proper productisation
        of this code on an open source basis in Q1 2006.  This has involved addition of EAN codes
        as well as a proper testing program.  Henceforth we intend to publicise the code more widely,
        gather feedback, accept contributions of code and treat it as "supported".  
        """, styleN))

    story.append(Paragraph("""
        This involved making available both downloads and testing resources.  This PDF document
        is the output of the current test suite.  It contains codes you can scan (if you use a nice sharp
        laser printer!), and will be extended over coming weeks to include usage examples and notes on
        each barcode and how widely tested they are.  This is being done through documentation strings in
        the barcode objects themselves so should always be up to date.
        """, styleN))

    story.append(Paragraph('Usage examples', styleH2))
    story.append(Paragraph("""
        To be completed
        """, styleN))

    story.append(Paragraph('The codes', styleH2))
    story.append(Paragraph("""
        Below we show a scannable code from each barcode, with and without human-readable text.
        These are magnified about 2x from the natural size done by the original author to aid
        inspection.  This will be expanded to include several test cases per code, and to add
        explanations of checksums.  Be aware that (a) if you enter numeric codes which are too
        short they may be prefixed for you (e.g. "123" for an 8-digit code becomes "00000123"),
        and that the scanned results and readable text will generally include extra checksums
        at the end.
        """, styleN))

    codeNames = getCodeNames()
    from reportlab.lib.utils import flatten
    width = [float(x[8:]) for x in sys.argv if x.startswith('--width=')]
    height = [float(x[9:]) for x in sys.argv if x.startswith('--height=')]
    isoScale = [int(x[11:]) for x in sys.argv if x.startswith('--isoscale=')]
    options = {}
    if width: options['width'] = width[0]
    if height: options['height'] = height[0]
    if isoScale: options['isoScale'] = isoScale[0]
    scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')]
    scales = map(float,scales and flatten(scales) or [1])
    scales = map(float,scales and flatten(scales) or [1])
    for scale in scales:
        story.append(PageBreak())
        story.append(Paragraph('Scale = %.1f'%scale, styleH2))
        story.append(Spacer(36, 12))
        for codeName in codeNames:
            s = [Paragraph('Code: ' + codeName, styleH2)]
            for hr in (0,1):
                s.append(Spacer(36, 12))
                dr = createBarcodeDrawing(codeName, humanReadable=hr,**options)
                dr.renderScale = scale
                s.append(dr)
                s.append(Spacer(36, 12))
            s.append(Paragraph('Barcode should say: ' + dr._bc.value, styleN))
            story.append(KeepTogether(s))

    SimpleDocTemplate(fileName).build(story)
    print 'created', fileName
Esempio n. 55
0
def exportPDF(request, slug):
    """Exports recipes to a pdf"""

    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    registerFontFamily('Vera',
                       normal='Vera',
                       bold='VeraBd',
                       italic='VeraIt',
                       boldItalic='VeraBI')

    recipe = get_object_or_404(Recipe, slug=slug)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=' + recipe.slug + '.pdf'

    # Our container for 'Flowable' objects
    elements = []

    # set up our styles
    styles = getSampleStyleSheet()
    styleH1 = styles['Heading1']
    styleH1.textColor = colors.green
    styleH1.fontName = 'VeraBd'
    styleH2 = styles['Heading2']
    styleH2.textColor = colors.goldenrod
    styleH2.fontName = 'Vera'
    styleNormal = styles['Normal']
    styleNormal.fontName = 'Vera'
    styleBullet = styles['Bullet']
    styleBullet.fontName = 'VeraIt'

    # create the pdf doc
    doc = SimpleDocTemplate(response)

    # set the openeats logo
    logo = settings.STATIC_ROOT + "/" + settings.OELOGO
    I = Image(logo)
    I.hAlign = 'LEFT'
    elements.append(I)
    elements.append(Spacer(0, 1 * cm))

    # add the recipe photo if the recipe has one
    if recipe.photo:
        photo = settings.BASE_PATH + recipe.photo.url
        I = Image(photo)
        I.height = "CENTER"
        elements.append(I)
        elements.append(Spacer(0, 0.5 * cm))

    # add the meat of the pdf
    elements.append(Paragraph(recipe.title, styleH1))
    elements.append(Paragraph('info', styleH2))
    elements.append(Paragraph(recipe.info, styleNormal))
    elements.append(Paragraph('ingredients', styleH2))

    for ing in recipe.ingredients.all():
        ing = "%s %s %s %s" % (ing.quantity, ing.measurement, ing.title,
                               ing.preparation)
        elements.append(Paragraph(ing, styleBullet))

    elements.append(Paragraph('directions', styleH2))
    elements.append(Paragraph(recipe.directions, styleNormal))

    # build the pdf and return it
    doc.build(elements)
    return response
Esempio n. 56
0
def make_report(POP, outfile="NeuroDesign.pdf"):
    '''
    Function to create a report of a finished design optimisation.
    '''
    if not isinstance(POP.cov, np.ndarray):
        POP.evaluate()

    styles = getSampleStyleSheet()

    doc = SimpleDocTemplate(outfile, pagesize=letter,
                            rightMargin=40, leftMargin=40,
                            topMargin=40, bottomMargin=18)

    Story = []

    curpath = os.path.dirname(__file__)

    logofile = os.path.join(curpath, "media/NeuroDes.png")
    im = Image(logofile, 1 * inch, 1.25 * inch)
    Story.append(im)
    Story.append(Spacer(1, 12))

    title = 'NeuroDesign: optimalisation report'
    Story.append(Paragraph(title, styles['title']))
    Story.append(Spacer(1, 12))

    formatted_time = time.ctime()
    ptext = 'Document created: %s' % formatted_time
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    Story.append(Paragraph("Correlation between designs", styles["Heading2"]))
    Story.append(Spacer(1, 12))

    corr = 'During the optimisation, the designs are mixed with each other to find better combinations.  As such, the designs can look very similar. Actually, the genetic algorithm uses natural selection as a basis, and as such, the designs can be clustered in families.  This is the covariance matrix between the final {0} designs'.format(
        POP.G)
    Story.append(Paragraph(corr, styles["Normal"]))

    fig = plt.figure(figsize=(6, 6))
    plt.imshow(POP.cov, interpolation="nearest")
    plt.colorbar()
    imgdata = BytesIO()
    fig.savefig(imgdata, format='pdf')
    imgdata.seek(0)  # rewind the data

    reader = form_xo_reader
    image = reader(imgdata)
    img = PdfImage(image, width=300, height=250)
    Story.append(img)

    Story.append(PageBreak())

    Story.append(Paragraph("Selected designs", styles["Heading2"]))
    Story.append(Spacer(1, 12))

    designs = 'The following figure shows in the upper panel the optimisation score over the different generations.  Below are the expected signals of the best designs from different families, more specific and in relation with the covariance matrix, designs {0}.  Next to each design is the covariance matrix between the regressors, and the diagonal matrix with the eigenvalues of the design matrix.'.format(str(POP.out)[
                                                                                                                                                                                                                                                                                                                                                                                                                         1:-1])
    Story.append(Paragraph(designs, styles["Normal"]))

    fig = plt.figure(figsize=(12, 18))
    gs = gridspec.GridSpec(POP.outdes + 4, 5)
    plt.subplot(gs[:2, :])
    plt.plot(POP.optima)

    for des in range(POP.outdes):
        design = POP.designs[POP.out[des]]
        stdes = des + 2
        plt.subplot(gs[stdes, :3])
        plt.plot(design.Xconv, lw=2)
        plt.axis('off')
        plt.subplot(gs[stdes, 3])
        varcov = np.corrcoef(design.Xconv.T)
        plt.imshow(varcov, interpolation='nearest', clim=(-1, 1), cmap="RdBu")
        plt.axis('off')
        plt.colorbar(ticks=[-1, 0, 1])
        plt.subplot(gs[stdes, 4])
        eigenv = np.diag(np.linalg.svd(design.Xconv.T)[1])
        plt.imshow(eigenv, interpolation='nearest', clim=(0, 1))
        plt.axis('off')
        plt.colorbar(ticks=[0, 1])

    imgdata = BytesIO()
    fig.savefig(imgdata, format='pdf')
    imgdata.seek(0)  # rewind the data

    reader = form_xo_reader
    image = reader(imgdata)
    img = PdfImage(image, width=500, height=600)
    Story.append(img)

    Story.append(PageBreak())

    intro = 'Experimental settings'
    Story.append(Paragraph(intro, styles["Heading2"]))
    Story.append(Spacer(1, 12))

    exp = [
        ["Repetition time (TR):", POP.exp.TR],
        ["Number of trials:", POP.exp.n_trials],
        ["Number of scans:", POP.exp.n_scans],
        ["Number of different stimuli:", POP.exp.n_stimuli],
        [],
        ["Stimulus probabilities:", Table([POP.exp.P], rowHeights=13)],
        [],
        ["Duration of stimulus (s)", POP.exp.stim_duration],
        ["Seconds before stimulus (in trial):", POP.exp.t_pre],
        ["Seconds after stimulus (in trial)", POP.exp.t_post],
        ["Duration of trial (s):", POP.exp.trial_duration],
        ["Total experiment duration(s):", POP.exp.duration],
        [],
        ["Number of stimuli between rest blocks", POP.exp.restnum],
        ["Duration of rest blocks (s):", POP.exp.restdur],
        [],
        [],
        [],
        [],
        [],
        ["Contrasts:", Table(list(POP.exp.C), rowHeights=13)],
        [],
        ["ITI model:", POP.exp.ITImodel],
        ["minimum ITI:", POP.exp.ITImin],
        ["mean ITI:", POP.exp.ITImean],
        ["maximum ITI:", POP.exp.ITImax],
        [],
        ["Hard probabilities: ", POP.exp.hardprob],
        ["Maximum number of repeated stimuli:", POP.exp.maxrep],
        ["Resolution of design:", POP.exp.resolution],
        [],
        ["Assumed autocorrelation:", POP.exp.rho]
    ]

    Story.append(Table(exp, rowHeights=13))

    optset = 'Optimalisation settings'
    Story.append(Paragraph(optset, styles["Heading2"]))
    Story.append(Spacer(1, 12))

    opt = [
        ["Optimalisation weights (Fe,Fd,Fc,Ff):", Table([POP.weights], rowHeights=13)],
        [],
        ["Aoptimality?", POP.Aoptimality],
        ["Number of designs in each generation:", POP.G],
        ["Number of immigrants in each generation:", POP.I],
        ["Confounding order:", POP.exp.confoundorder],
        ["Convergence criterion:", POP.convergence],
        ["Number of precycles:", POP.preruncycles],
        ["Number of cycles:", POP.cycles],
        ["Percentage of mutations:", POP.q],
        ["Seed:", POP.seed]
    ]

    Story.append(Table(opt, rowHeights=13))

    doc.build(Story)
Esempio n. 57
0
def MakeTotalPDF(config):
    '''
    Make a PDF containing the fastq_screen images from each sample

    Also, parse the fastq_screen .txt files and calculate the per-sample off-species rate
    '''
    lanes = config.get("Options", "lanes")
    if lanes != '':
        lanes = '_lanes{}'.format(lanes)

    stylesheet = getSampleStyleSheet()

    pdf = BaseDocTemplate("%s/%s%s/ContaminationReport.pdf" % (config.get(
        "Paths", "outputDir"), config.get("Options", "runID"), lanes),
                          pagesize=A4)
    fM = Frame(pdf.leftMargin,
               pdf.bottomMargin,
               pdf.width,
               pdf.height,
               id="main")

    tab = [[
        "Project", "Sample", "confident off-species reads/sample",
        "% Optical Duplication"
    ]]
    txt = "\nProject\tSample\tconfident off-species reads/sample\t% Optical Duplicates\n"
    elements = []

    projs = glob.glob("%s/%s%s/Project_*" % (config.get(
        "Paths", "outputDir"), config.get("Options", "runID"), lanes))
    projs.sort()

    #Make the table
    for proj in projs:
        pname = proj.split("/")[-1]
        txts = glob.glob("%s/Sample_*/*_screen.txt" % proj)
        txts.sort()
        for i in range(len(txts)):
            # Get the percent optical duplication
            _ = "{}.duplicate.txt".format(txts[i][:-14])
            if os.path.exists(_):
                _ = open(_).read().strip().split("\t")
                duplicationRate = "{:5.2f}%".format(
                    (100.0 * int(_[0])) / int(_[1]))
            else:
                duplicationRate = "NA"
            tab.append([
                pname, txts[i].split("/")[-1][:-11],
                "%5.2f" % getOffSpecies(txts[i]), duplicationRate
            ])
            txt += "%s\t%s\t%5.2f\t%s\n" % (pname, txts[i].split(
                "/")[-1][:-11], getOffSpecies(txts[i]), duplicationRate)
    txt += "\n"

    #Add the table
    t = Table(
        tab,
        style=[
            ('ROWBACKGROUNDS', (0, 0), (-1, -1), (0xD3D3D3, None))  #Light grey
        ],
        repeatRows=1)
    elements.append(t)
    elements.append(Spacer(0, 30))

    #Add the images
    for proj in projs:
        pname = proj.split("/")[-1]
        elements.append(Paragraph(pname, stylesheet['title']))
        imgs = glob.glob("%s/Sample_*/*.png" % proj)
        imgs.sort()
        for i in range(len(imgs)):
            TmpImg = utils.ImageReader(imgs[i])
            iw, ih = TmpImg.getSize()
            iw = 0.5 * iw
            ih = 0.5 * ih
            elements.append(Image(imgs[i], width=iw, height=ih, hAlign="LEFT"))

    pdf.addPageTemplates([PageTemplate(id="foo", frames=[fM])])
    pdf.build(elements)

    return txt
Esempio n. 58
0
def build_linear_pdf_schedule(conference, room, tracks, day, colored, pagesize,
                              orientation, titledatefmt):
    q = Q(conference=conference,
          status=1,
          starttime__isnull=False,
          endtime__isnull=False)
    q = q & (Q(room=room) | Q(cross_schedule=True))
    q = q & (Q(track__in=tracks) | Q(track__isnull=True))
    if day:
        q = q & Q(starttime__range=(day.day, day.day + timedelta(days=1)))

    sessions = ConferenceSession.objects.select_related(
        'track', 'room').filter(q).order_by('starttime')

    (width, height, canvas, resp) = _setup_canvas(pagesize, orientation)

    # Fetch and modify styles
    st_time = getSampleStyleSheet()['Normal']
    st_time.fontName = "DejaVu Serif"
    st_time.fontSize = 10
    st_time.spaceAfter = 8
    st_title = getSampleStyleSheet()['Normal']
    st_title.fontName = "DejaVu Serif"
    st_title.fontSize = 10
    st_title.spaceAfter = 8
    st_speakers = getSampleStyleSheet()['Normal']
    st_speakers.fontName = "DejaVu Serif"
    st_speakers.fontSize = 10
    st_speakers.spaceAfter = 8

    table_horiz_margin = cm(2)

    default_tbl_style = [
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
        ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 15),
    ]

    # Loop over days, creating one page for each day
    lastdate = None
    tbldata = []
    tblstyle = copy.copy(default_tbl_style)

    def _finalize_page():
        canvas.setFont("DejaVu Serif", 20)
        canvas.drawCentredString(
            width // 2, height - cm(2),
            "%s - %s" % (room.roomname, lastdate.strftime(titledatefmt)))

        t = Table(tbldata,
                  colWidths=[cm(3), width - cm(3) - 2 * table_horiz_margin])
        t.setStyle(TableStyle(tblstyle))
        w, h = t.wrapOn(canvas, width, height)
        t.drawOn(canvas, table_horiz_margin, height - cm(4) - h)
        canvas.showPage()

    for s in sessions:
        if timezone.localdate(s.starttime) != lastdate:
            if lastdate is not None:
                # New page for a new day!
                _finalize_page()
            lastdate = timezone.localdate(s.starttime)
            tbldata = []
            tblstyle = copy.copy(default_tbl_style)

        if colored and s.track and s.track.fgcolor:
            st_title.textColor = st_speakers.textColor = s.track.fgcolor
        else:
            st_title.textColor = st_speakers.textColor = colors.black

        tstr = Paragraph(
            "%s - %s" % (timezone.localtime(s.starttime).strftime("%H:%M"),
                         timezone.localtime(s.endtime).strftime("%H:%M")),
            st_time)
        if s.cross_schedule:
            # Just add a blank row for cross schedule things, so we get the time on there
            tbldata.extend([(tstr, '')])
        else:
            tbldata.extend([(tstr, (Paragraph(s.title, st_title),
                                    Paragraph("<i>%s</i>" % s.speaker_list,
                                              st_speakers)))])
            if colored and s.track and s.track.color:
                tblstyle.append(('BACKGROUND', (1, len(tbldata) - 1),
                                 (1, len(tbldata) - 1), s.track.color), )

    _finalize_page()
    canvas.save()

    return resp
Esempio n. 59
0
    def Guardar_Turnos(self):
        tipo = self.ventanaempleados.cbGuardar.currentText()
        row = self.ventanaempleados.tablaTurnos.rowCount()
        if self.ventanaempleados.tablaTurnos.item(0, 0) != None:
            if tipo == "CSV":
                ruta_guardar = ""
                NombreArchivo = QFileDialog.getSaveFileName(
                    self, "Guardar Archivo", ruta_guardar)
                if NombreArchivo[0]:
                    file = open(NombreArchivo[0] + '.csv', 'w')
                    fieldnames = [
                        "N°", "CI_RIF", "Hora_Inicio", "Hora_Fin", "Fecha"
                    ]
                    csvsalida = csv.DictWriter(file, fieldnames)
                    for i in range(row):
                        csvsalida.writerow({
                            fieldnames[0]:
                            self.ventanaempleados.tablaTurnos.item(i,
                                                                   0).text(),
                            fieldnames[1]:
                            self.ventanaempleados.tablaTurnos.item(i,
                                                                   1).text(),
                            fieldnames[2]:
                            self.ventanaempleados.tablaTurnos.item(i,
                                                                   2).text(),
                            fieldnames[3]:
                            self.ventanaempleados.tablaTurnos.item(i,
                                                                   3).text(),
                            fieldnames[4]:
                            self.ventanaempleados.tablaTurnos.item(i,
                                                                   4).text()
                        })
                    file.close()
            elif tipo == "PDF":
                ruta_guardar = ""
                NombreArchivo = QFileDialog.getSaveFileName(
                    self, "Guardar Archivo", ruta_guardar)
                if NombreArchivo[0]:
                    estiloHoja = getSampleStyleSheet()
                    story = []
                    cuerpo = estiloHoja["BodyText"]
                    cuerpo.alignment = TA_CENTER

                    col = ["N°", "CI_RIF", "Hora_Inicio", "Hora_Fin", "Fecha"]
                    fil = []
                    fil.insert(0, col)
                    filasTabla = 0
                    for fila in range(row):
                        fil.insert(fila + 1, [
                            self.ventanaempleados.tablaTurnos.item(
                                filasTabla, 0).text(),
                            self.ventanaempleados.tablaTurnos.item(
                                filasTabla, 1).text(),
                            self.ventanaempleados.tablaTurnos.item(
                                filasTabla, 2).text(),
                            self.ventanaempleados.tablaTurnos.item(
                                filasTabla, 3).text(),
                            self.ventanaempleados.tablaTurnos.item(
                                filasTabla, 4).text()
                        ])
                        filasTabla += 1
                    datos = [i for i in fil]
                    tabla = Table(data=datos, colWidths=[20, 60, 60, 60, 60])
                    story.append(tabla)
                    doc = SimpleDocTemplate(NombreArchivo[0] + '.pdf',
                                            pagesize=portrait(LETTER),
                                            leftMargin=3,
                                            rightMargin=4,
                                            topMargin=3,
                                            bottomMargin=4)
                    doc.build(story)
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    btj = ParagraphStyle('bodyText1j', parent=bt, alignment=TA_JUSTIFY)
    btr = ParagraphStyle('bodyText1r', parent=bt, alignment=TA_RIGHT)
    btc = ParagraphStyle('bodyText1c', parent=bt, alignment=TA_CENTER)
    from reportlab.lib.utils import TimeStamp
    ts = TimeStamp()
    a(
        Paragraph(
            """
        <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (ts.asctime, len(story)), bt))

    for i in range(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in range(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in range(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    for align, bts in [('left', bt), ('JUSTIFIED', btj), ('RIGHT', btr),
                       ('CENTER', btc)]:
        a(Paragraph('Now we do &lt;br/&gt; tests(align=%s)' % align, h1))
        a(Paragraph('First off no br tags', h3))
        a(Paragraph(_text1, bts))
        a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1),
                      bts))
        a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(
                _text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1),
                    bts))
        a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(
            Paragraph(
                _text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
        a(Paragraph("""text one<br/>text two<br/>""", bts))
        a(Paragraph("Border with &lt;br/&gt; at the end of the paragraph!",
                    h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt1))
        a(Paragraph("Border no &lt;br/&gt; at the end of the paragraph!", h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two""", bt1))
        a(Paragraph("Different border style!", h3))
        bt2 = ParagraphStyle('bodyText1', bt1)
        bt2.borderWidth = 1.5
        bt2.borderColor = colors.toColor('blue')
        bt2.backColor = colors.gray
        bt2.borderRadius = 3
        bt2.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt2))
    for i in 0, 1, 2:
        P = Paragraph(
            """This is a paragraph with <font color='blue'><a href='#top'>with an incredibly
long and boring link in side of it that
contains lots and lots of stupidly boring and worthless information.
So that we can split the link and see if we get problems like Dinu's.
I hope we don't, but you never do Know.</a></font>""", bt)
        a(P)

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)