示例#1
0
文件: views.py 项目: Shirk/OpenSlides
    def get_assignment(self, assignment, story):
        # title
        story.append(Paragraph(_("Election: %s") % assignment.name,
            stylesheet['Heading1']))
        story.append(Spacer(0, 0.5 * cm))
        # posts
        cell1a = []
        cell1a.append(Paragraph("<font name='Ubuntu-Bold'>%s:</font>" %
            _("Number of available posts"), stylesheet['Bold']))
        cell1b = []
        cell1b.append(Paragraph(str(assignment.posts), stylesheet['Paragraph']))
        # candidates
        cell2a = []
        cell2a.append(Paragraph("<font name='Ubuntu-Bold'>%s:</font><seqreset" \
            " id='counter'>" % _("Candidates"), stylesheet['Heading4']))
        cell2b = []
        for candidate in assignment.candidates:
            cell2b.append(Paragraph("<seq id='counter'/>.&nbsp; %s" % candidate,
                stylesheet['Signaturefield']))
        if assignment.status == "sea":
            for x in range(0, 2 * assignment.posts):
                cell2b.append(Paragraph("<seq id='counter'/>.&nbsp; "
                    "__________________________________________",
                    stylesheet['Signaturefield']))
        cell2b.append(Spacer(0, 0.2 * cm))

        # Vote results

        # Preparing
        vote_results = assignment.vote_results(only_published=True)
        polls = assignment.poll_set.filter(published=True)
        data_votes = []

        # Left side
        cell3a = []
        cell3a.append(Paragraph("%s:" % (_("Vote results")),
            stylesheet['Heading4']))

        if polls.count() == 1:
            cell3a.append(Paragraph("%s %s" % (polls.count(), _("ballot")),
                stylesheet['Normal']))
        elif polls.count() > 1:
            cell3a.append(Paragraph("%s %s" % (polls.count(), _("ballots")),
                stylesheet['Normal']))

        # Add table head row
        headrow = []
        headrow.append(_("Candidates"))
        for poll in polls:
            headrow.append("%s." % poll.get_ballot())
        data_votes.append(headrow)


        # Add result rows
        elected_candidates = list(assignment.elected)
        for candidate, poll_list in vote_results.iteritems():
            row = []

            candidate_string = candidate.clean_name
            if candidate in elected_candidates:
                candidate_string = "* " + candidate_string
            if candidate.name_suffix:
                candidate_string += "\n(%s)" % candidate.name_suffix
            row.append(candidate_string)
            for vote in poll_list:
                if vote == None:
                    row.append('–')
                elif 'Yes' in vote and 'No' in vote and 'Abstain' in vote:
                    row.append(_("Y: %(YES)s\nN: %(NO)s\nA: %(ABSTAIN)s")
                        % {'YES':vote['Yes'], 'NO': vote['No'],
                        'ABSTAIN': vote['Abstain']})
                elif 'Votes' in vote:
                    row.append(vote['Votes'])
                else:
                    pass
            data_votes.append(row)

        # Add votes invalid row
        footrow_one = []
        footrow_one.append(_("Invalid votes"))
        for poll in polls:
            footrow_one.append(poll.print_votesinvalid())
        data_votes.append(footrow_one)

        # Add votes cast row
        footrow_two = []
        footrow_two.append(_("Votes cast"))
        for poll in polls:
            footrow_two.append(poll.print_votescast())
        data_votes.append(footrow_two)

        table_votes=Table(data_votes)
        table_votes.setStyle( TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
            ('VALIGN',(0, 0),(-1, -1), 'TOP'),
            ('LINEABOVE',(0, 0),(-1, 0), 2, colors.black),
            ('LINEABOVE',(0, 1),(-1, 1), 1, colors.black),
            ('LINEBELOW',(0, -1),(-1, -1), 2, colors.black),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9))),
        ]))

        # table
        data = []
        data.append([cell1a, cell1b])
        if polls:
            data.append([cell3a, table_votes])
            data.append(['', '* = ' + _('elected')])
        else:
            data.append([cell2a, cell2b])
        data.append([Spacer(0, 0.2 * cm), ''])
        t=Table(data)
        t._argW[0] = 4.5 * cm
        t._argW[1] = 11 * cm
        t.setStyle(TableStyle([ ('BOX', (0,0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
        story.append(t)
        story.append(Spacer(0, 1 * cm))

        # text
        story.append(Paragraph("%s" % assignment.description.replace('\r\n',
            '<br/>'), stylesheet['Paragraph']))
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.platypus import Table
from reportlab.platypus import TableStyle

# List of Lists
data = [
    ['Employee_ID ', 'Company', 'Salary ', ' Post' ],
    ['EmP_5', 'HaldiRam', '10000', 'Manager'],
    ['EmP_7', 'Balaji', ' 75000', 'Assistant Manager']
    
]
fileName = 'pdfTable.pdf'
pdf = SimpleDocTemplate(fileName,pagesize=letter)
table = Table(data)
style = TableStyle([
    ('BACKGROUND', (0,0), (3,0),colors.white),
    ('TEXTCOLOR',(0,0),(-1,0),colors.greenyellow),

    ('ALIGN',(0,0),(-1,-1),'CENTER'),

    ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
    ('FONTSIZE', (0,0), (-1,0), 14),

    ('BOTTOMPADDING', (0,0), (-1,0), 12),

    ('BACKGROUND',(0,1),(-1,-1),colors.beige),

    ('BOX',(0,0),(-1,-1),2,colors.black),
  #  ('LINEBEFORE',(2,1),(2,-1),6,colors.red),
示例#3
0
def CreatePDF(name, easycompute, compute, question):
    element = []
    pdf_file = SimpleDocTemplate(name + '.pdf',
                                 pagesizes=A4,
                                 rightMargin=72,
                                 leftMargin=22,
                                 topMargin=20,
                                 bottomMargin=18)

    # 注册字体
    pdfmetrics.registerFont(TTFont('FZKT', 'FangZhengKaiTi.ttf'))

    # 设置段落格式
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(
        name='title01',
        fontName='FZKT',
        alignment=1,
    ))
    styles.add(
        ParagraphStyle(
            name='name',
            fontName='FZKT',
            # alignment = 2,
            fontSize=20,
            leftIndent=282,
        ))
    styles.add(
        ParagraphStyle(
            name='subject',
            fontName='FZKT',
            alignment=4,
            fontSize=18,
        ))
    styles.add(
        ParagraphStyle(
            name='question',
            fontName='FZKT',
            leading=24,
            alignment=4,
            fontSize=18,
        ))

    # 添加titile
    title = '<font size=25>每日一练</font><font size=15>(二年级下册)</font>'
    element.append(Paragraph(title, styles['title01']))
    # 添加空格行
    element.append(Spacer(1, 24))
    name_and_data = '姓名: ' + name
    element.append(Paragraph(name_and_data, styles['name']))
    element.append(Spacer(1, 12))
    element.append(Paragraph('一:口算', styles['subject']))
    element.append(Spacer(1, 12))

    # 表格样式
    table_style = TableStyle([
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('FONTSIZE', (0, 0), (-1, -1), 14),
        ('LEFTPADDING', (0, 0), (-1, -1), 28),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 9),
    ])
    table_all_data = Table(easycompute, style=table_style)
    element.append(table_all_data)

    element.append(Paragraph('二:笔算', styles['subject']))
    element.append(Spacer(1, 12))

    table_style1 = TableStyle([
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('FONTSIZE', (0, 0), (-1, -1), 14),
        ('RIGHTPADDING', (0, 0), (-1, -1), 80),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 100),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    table_all_data = Table(compute, style=table_style1)
    element.append(table_all_data)

    element.append(Paragraph('三:问题解决', styles['subject']))
    element.append(Spacer(1, 12))
    element.append(Paragraph(question, styles['question']))

    pdf_file.build(element)
示例#4
0
    def createDocument(self):
        """"""
        voffset = 30

        # create header data
        header = """<font size="9">
        5 Year Maintenance Certificate<br/>
        %s_C%s<br/>
        Rev%s</font>
        """ % (self.job, self.report, self.revision)
        p = Paragraph(header, myStyle)

        # create header logo and size it
        logo = Image("img/image1.png")
        logo.drawHeight = 0.75 * inch
        logo.drawWidth = 3.43 * inch

        # combine logo and header data into array for table creation
        data = [[logo, p]]

        # create table for placement in header region, and define location
        table = Table(data, colWidths=4 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("VALIGN", (-1, -1), (-1, -1), "CENTER"),
                        ("ALIGN", (-1, -1), (-1, -1), "RIGHT")])
        table.wrapOn(self.c, self.width - 100, self.height)
        table.drawOn(self.c, *self.coord(5, 25, mm))

        # create Certificate title
        ptext = "<b>Certificate of Inspection & Compatibility</b>"
        self.createParagraph(ptext, 0, voffset + 8, TitleStyle)

        # create body text of the certificate and style
        if self.isRemote == 'no':
            ptext = """
            <b><i>Offshore Technical Compliance LLC</i></b> was present for the following 5 Year Maintenance Inspection of the equipment listed below. 
             The inspections were conducted per <b>%s’s</b> Preventative Maintenance (PM) program and the equipment 
             manufacture’s guidelines.
            """ % self.organization
        else:
            ptext = """
            <b><i>Offshore Technical Compliance LLC</i></b> has verified the following 5 Year Maintenance Inspection of the equipment listed below. 
             The inspections were conducted per <b>%s’s</b> Preventative Maintenance (PM) program and the equipment 
             manufacture’s guidelines.
            """ % self.organization
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.c, self.width - 70, self.height)
        p.drawOn(self.c, *self.coord(15, voffset + 25, mm))

        # create first table
        # create data structure for table parsing
        data = self.dataPrepTable1(self.jobdata, self.certdata)
        table = Table(data, colWidths=3.6 * inch)
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("ALIGN", (0, 0), (0, 0), "CENTER"),
                        ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                        ('BACKGROUND', (0, 7), (0, 7), HexColor(0x595959)),
                        ('SPAN', (0, 0), (1, 0)),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 80, mm))

        # create second table
        data = self.dataPrepTable2(self.certdata)
        table = Table(data, colWidths=3.6 * inch)
        if len(self.certdata[1]) > 45:
            table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                            ("ALIGN", (0, 0), (0, 0), "CENTER"),
                            ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                            ('SPAN', (0, 0), (1, 0)),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black), ('FONTSIZE', (1, 1), (1, 1), 8),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        else:
            table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                            ("ALIGN", (0, 0), (0, 0), "CENTER"),
                            ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
                            ('SPAN', (0, 0), (1, 0)),
                            ('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 130, mm))

        # # create third table
        # data = self.dataPrepTable3(self.certdata)
        # table = Table(data, colWidths=3.6 * inch)
        # table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
        #                 ("ALIGN", (0, 0), (0, 0), "CENTER"),
        #                 ('BACKGROUND', (0, 0), (0, 0), HexColor(0x3a3b3d)),
        #                 ('SPAN', (0, 0), (1, 0)),
        #                 ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        #                ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])
        # table.wrapOn(self.c, self.width, self.height)
        # table.drawOn(self.c, *self.coord(15, voffset + 167, mm))

        # create signature area (table)
        if self.isRemote == 'no':
            data = [[
                'Witness:', self.Witness, 'Date:',
                datetime.date.today().strftime('%d %b %Y')
            ], [],
                    [
                        'Engineering Approval:', self.Engineering, 'Date:',
                        datetime.date.today().strftime('%d %b %Y')
                    ]]
        else:
            data = [[
                'Verification:', self.Witness, 'Date:',
                datetime.date.today().strftime('%d %b %Y')
            ], [],
                    [
                        'Engineering Approval:', self.Engineering, 'Date:',
                        datetime.date.today().strftime('%d %b %Y')
                    ]]
        table = Table(data,
                      colWidths=(1.5 * inch, 3.75 * inch, 0.6 * inch,
                                 1.35 * inch))
        table.setStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                        ("ALIGN", (0, 0), (0, 1), "RIGHT"),
                        ("ALIGN", (1, 0), (1, 2), "RIGHT")])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(15, voffset + 200, mm))

        # add in signatures
        logo = Image("img/signatures/" + self.WitnessSig)
        logo.drawHeight = .5 * inch
        logo.drawWidth = 1.5 * inch
        logo.wrapOn(self.c, self.width, self.height)
        logo.drawOn(self.c, *self.coord(65, voffset + 187, mm))

        logo = Image("img/signatures/" + self.EngineeringSig)
        logo.drawHeight = .5 * inch
        logo.drawWidth = 1.5 * inch
        logo.wrapOn(self.c, self.width, self.height)
        logo.drawOn(self.c, *self.coord(65, voffset + 202, mm))

        # create footer area (table)
        data = [['www.otcompliance.com', 'PROPRIETARY/CONFIDENTIAL', '1']]
        table = Table(data, colWidths=(2.7 * inch, 2.7 * inch, 2.7 * inch))
        table.setStyle([
            ("VALIGN", (0, 0), (0, 0), "TOP"),
            ("ALIGN", (1, 0), (1, 0), "CENTER"),
            ("ALIGN", (-1, -1), (-1, -1), "RIGHT"),
        ])
        table.wrapOn(self.c, self.width, self.height)
        table.drawOn(self.c, *self.coord(5, voffset + 245, mm))
        self.drawLine()
示例#5
0
	def reporteador(self,obj_move):

		import sys
		reload(sys)
		sys.setdefaultencoding('iso-8859-1')

		param = self.env['main.parameter'].search([])[0]

		pdfmetrics.registerFont(TTFont('Calibri', param.download_directory + 'Calibri.ttf'))
		pdfmetrics.registerFont(TTFont('Calibri-Bold',param.download_directory +  'CalibriBold.ttf'))

		width ,height  = A4  # 595 , 842
		wReal = width- 30
		hReal = height - 40

		direccion = self.env['main.parameter'].search([])[0].dir_create_file
		c = canvas.Canvas( direccion + "AsientoContable.pdf", pagesize= A4 )
		inicio = 0
		pos_inicial = hReal-83
		libro = None
		voucher = None
		total = 0
		debeTotal = 0
		haberTotal = 0
		pagina = 1
		textPos = 0
		
		self.cabezera(c,wReal,hReal,obj_move,1)


		posicion_indice = 1

		for i in obj_move.line_ids:
			c.setFont("Calibri", 8)
			pagina, pos_inicial = self.verify_linea(c,wReal,hReal,pos_inicial,12,pagina,1,obj_move)
			
			c.drawString( 10 ,pos_inicial, str(posicion_indice) )
			c.drawString( 22 ,pos_inicial, self.particionar_text( i.name,70) )
			c.drawString( 102 ,pos_inicial, self.particionar_text( i.partner_id.name if i.partner_id.id else '',100) )
			c.drawString( 222 ,pos_inicial,self.particionar_text( i.nro_comprobante if i.nro_comprobante else '',70) )
			c.drawString( 302 ,pos_inicial,self.particionar_text( (i.account_id.code + ' - ' + i.account_id.name) if i.account_id.id else '',75) )
			c.drawString( 392 ,pos_inicial,self.particionar_text( i.date_maturity if i.date_maturity else '',40) )
			c.drawRightString( 498 ,pos_inicial, '{:,.2f}'.format(decimal.Decimal ("%0.2f" % i.debit)))
			c.drawRightString( 558 ,pos_inicial, '{:,.2f}'.format(decimal.Decimal ("%0.2f" % i.credit)))
			c.drawString( 562 ,pos_inicial,self.particionar_text( i.type_document_it.code if i.type_document_it.id else '',20) )

			c.line( 20, pos_inicial-2, 585 ,pos_inicial-2)

			tamanios_x = [80,120, 80, 90, 50,60,60,25]

			acum_tx = 20
			for i in tamanios_x:
				c.line( acum_tx, pos_inicial-2, acum_tx ,pos_inicial+12)
				acum_tx += i
			c.line( acum_tx, pos_inicial-2, acum_tx ,pos_inicial+12)

			posicion_indice += 1



		posicion_indice= 1



		pagina, pos_inicial = self.verify_linea(c,wReal,hReal,pos_inicial,36,pagina,2,obj_move)



		style = getSampleStyleSheet()["Normal"]
		style.leading = 8
		style.alignment= 1
		paragraph1 = Paragraph(
		    "<font size=8><b>Nombre</b></font>",
		    style
		)
		paragraph2 = Paragraph(
		    "<font size=8><b>Empresa</b></font>",
		    style
		)
		paragraph3 = Paragraph(
		    "<font size=8><b>Comprobante</b></font>",
		    style
		)
		paragraph4 = Paragraph(
		    "<font size=8><b>Cuenta</b></font>",
		    style
		)
		paragraph5 = Paragraph(
		    "<font size=8><b>Fecha V.</b></font>",
		    style
		)
		paragraph6 = Paragraph(
		    "<font size=8><b>Debe</b></font>",
		    style
		)
		paragraph7 = Paragraph(
		    "<font size=8><b>Haber</b></font>",
		    style
		)
		paragraph8 = Paragraph(
		    "<font size=8><b>Cta. Analítica</b></font>",
		    style
		)
		paragraph9 = Paragraph(
		    "<font size=8><b>Importe Divisa</b></font>",
		    style
		)
		paragraph10 = Paragraph(
		    "<font size=8><b>Divisa</b></font>",
		    style
		)
		paragraph11 = Paragraph(
		    "<font size=8><b>TC SUNAT</b></font>",
		    style
		)
		paragraph12 = Paragraph(
		    "<font size=8><b>TD</b></font>",
		    style
		)

		data= [[ paragraph8 ,paragraph9,paragraph10,paragraph11]]
		t=Table(data,colWidths=(100,100,50,60), rowHeights=(9))
		t.setStyle(TableStyle([
			('GRID',(0,0),(-1,-1), 1, colors.black),
			('ALIGN',(0,0),(-1,-1),'LEFT'),
			('VALIGN',(0,0),(-1,-1),'MIDDLE'),
			('TEXTFONT', (0, 0), (-1, -1), 'Calibri-Bold'),
			('FONTSIZE',(0,0),(-1,-1),4),
			('BACKGROUND', (0, 0), (-1, -1), colors.gray)
		]))

		t.wrapOn(c,20,pos_inicial)
		t.drawOn(c,20,pos_inicial)


		for i in obj_move.line_ids:
			c.setFont("Calibri", 8)
			pagina, pos_inicial = self.verify_linea(c,wReal,hReal,pos_inicial,12,pagina,2,obj_move)
			
			c.drawString( 10 ,pos_inicial, str(posicion_indice) )
			c.drawString( 22 ,pos_inicial,self.particionar_text( i.analytic_account_id.name if i.analytic_account_id.id else '', 43) )
			c.drawRightString( 218 ,pos_inicial, '{:,.2f}'.format(decimal.Decimal ("%0.2f" % i.amount_currency)))
			c.drawString( 222 ,pos_inicial,self.particionar_text( i.currency_id.name if i.currency_id.id else '',24) )
			c.drawRightString( 328 ,pos_inicial, "%0.3f" % i.tc)
			
			c.line( 20, pos_inicial-2, 330 ,pos_inicial-2)


			tamanios_x = [100,100,50,60]

			acum_tx = 20
			for i in tamanios_x:
				c.line( acum_tx, pos_inicial-2, acum_tx ,pos_inicial+12)
				acum_tx += i
			c.line( acum_tx, pos_inicial-2, acum_tx ,pos_inicial+12)

			posicion_indice += 1
		
		pagina, pos_inicial = self.verify_linea(c,wReal,hReal,pos_inicial,24,pagina,2,obj_move)






		c.drawString( 10 ,pos_inicial, 'HECHO POR:' )
		c.drawString( 60 ,pos_inicial, obj_move.create_uid.name if obj_move.create_uid.id else self.env.uid.name )


		pagina, pos_inicial = self.verify_linea(c,wReal,hReal,pos_inicial,50,pagina,3,obj_move)

		c.line( 125-47, pos_inicial+10, 125+47 ,pos_inicial+10)
		c.line( 290-47, pos_inicial+10, 290+47 ,pos_inicial+10)
		c.line( 165+290-47, pos_inicial+10, 165+290+47 ,pos_inicial+10)
		c.drawCentredString( 125 ,pos_inicial, 'HECHO POR:' )
		c.drawCentredString( 165+290 ,pos_inicial, 'REVISADO:' )
		c.drawCentredString( 290 ,pos_inicial, 'APROBADO:' )

		c.save()
示例#6
0
def cedula_hallazgo(documento):
    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    output = PdfFileWriter()
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Cedula_de_Hallazgo.pdf'

    buffer = StringIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=50,
                            bottomMargin=100)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontSize=8))
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              fontSize=8))

    Story = []

    I = Image(os.path.join(settings.BASE_DIR, 'static', 'img', 'logo.png'))
    I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
    I.drawWidth = 1.25 * inch
    data = [[I, '', '', '', '', ''], ['SUJETO PASIVO:', '', '', '', '', ''],
            ['MATERIA:', '', '', '', '', '']]
    data[0][2] = Paragraph(
        u'''<b>CEDULA DE HALLAZGOS<br/>
                            Contribución Especial del 1% por la Presentación de<br/>
                            Servicios Turísticos</b>''', styles["Center"])
    data[0][4] = documento.codigo
    data[1][1] = documento.pst.nombre_o_razon()
    data[1][3] = 'RIF: ' + documento.pst.rif
    data[2][1] = documento.hallazgos_materia
    data[2][3] = 'PERIODO: ' + documento.fecha_notificacion.strftime(
        "%d/%m/%Y")
    w = [80, 30, 90, 90, 80, 80]
    Story.append(
        Table(data,
              colWidths=w,
              style=[('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                     ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                     ('FONTSIZE', (0, 0), (-1, -1), 8),
                     ('SPAN', (0, 0), (1, 0)), ('SPAN', (2, 0), (3, 0)),
                     ('SPAN', (4, 0), (5, 0)), ('SPAN', (1, 1), (2, 1)),
                     ('SPAN', (1, 2), (2, 2)), ('SPAN', (3, 1), (5, 1)),
                     ('SPAN', (3, 2), (5, 2))]))
    Story.append(Spacer(1, 12))

    data = [['CONDICIÓN', 'CRITERIO', 'EFECTO', 'EVIDENCIA'], ['', '', '', ''],
            ['', '', '', '']]
    try:
        data[2][0] = Paragraph(documento.hallazgos_condicion,
                               styles["Justify"])
        data[2][1] = Paragraph(documento.hallazgos_criterio, styles["Justify"])
        data[2][2] = Paragraph(documento.hallazgos_efecto, styles["Justify"])
        data[2][3] = Paragraph(documento.hallazgos_evidencia,
                               styles["Justify"])
    except:
        pass
    Story.append(
        Table(data,
              colWidths=[95, 170, 81, 105],
              style=[
                  ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                  ('GRID', (0, 2), (-1, 2), 0.25, colors.black),
                  ('FONTSIZE', (0, 0), (-1, -1), 8),
                  ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                  ('VALIGN', (0, 2), (-1, 2), 'TOP'),
              ]))
    Story.append(Spacer(1, 12))

    ptext = 'Observaciones: <u>%s</u>' % documento.observaciones
    Story.append(Paragraph(ptext, styles['Normal']))
    Story.append(Spacer(1, 12))

    Story.append(
        Paragraph('Fiscal Actuante: %s' % gerente.get_full_name(),
                  styles['Normal']))
    Story.append(
        Paragraph('Supervisor: %s' % supervisor.get_full_name(),
                  styles['Normal']))

    doc.build(Story)

    watermark = PdfFileReader(buffer)
    output.addPage(watermark.getPage(0))
    output.write(response)
    return response
示例#7
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle

        hauteur_page = A4[1]
        largeur_page = A4[0]

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=30, leftMargin=40, rightMargin=40)
        story = []

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ( (largeur_page-175, 100) )
        dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
        dataTableau.append( (_(u"Inscriptions"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
        style = TableStyle([
                ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                ('VALIGN', (0,0), (-1,-1), 'TOP'),
                ('ALIGN', (0,0), (0,0), 'LEFT'),
                ('FONT',(0,0),(0,0), "Helvetica-Bold", 16),
                ('ALIGN', (1,0), (1,0), 'RIGHT'),
                ('FONT',(1,0),(1,0), "Helvetica", 6),
                ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # Intro
        styleA = ParagraphStyle(name="A", fontName="Helvetica", fontSize=6, spaceAfter=20)
        #story.append(Paragraph(self.labelParametres, styleA))

        # Tableau
        dataTableau = []
        largeurColonnesSuivantes = 70
        largeurColonne1 = largeur_page - 80 - 1.0 * (len(self.dictImpression["entete"])-1) * largeurColonnesSuivantes
        largeursColonnes = [largeurColonne1,]
        for x in range(0, len(self.dictImpression["entete"])-1):
            largeursColonnes.append(largeurColonnesSuivantes)

        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])

        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques :
            listeLignes = self.dictImpression[rubrique]

            for ligne in listeLignes :
                dataTableau.append(ligne)

        positionLigneTotal = len(self.dictImpression["contenu"]) + 1
        listeStyles = [
            ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), # Centre verticalement toutes les cases
            ('FONT',(0,0),(-1,-1), "Helvetica", 7), # Donne la police de caract. + taille de police
            ('GRID', (0,0), (-1,-1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau
            ('ALIGN', (1,0), (-1,-1), 'CENTRE'), # Centre les cases
            ('BACKGROUND', (0,0), (-1,0), (0.6, 0.6, 0.6) ), # Donne la couleur de fond du label
            ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal), (0.8, 0.8, 0.8) ), # Donne la couleur de fond du total
            ]

        # Formatage des lignes "Activités"
        for indexColoration, typeColoration in self.dictImpression["coloration"] :

            if typeColoration == "activite" :
                listeStyles.append( ('FONT', (0, indexColoration+1), (-1, indexColoration+1), "Helvetica-Bold", 7) )
                listeStyles.append( ('BACKGROUND', (0, indexColoration+1), (-1, indexColoration+1), (0.91, 0.91, 0.91)) )

            if typeColoration == "regroup" :
                listeStyles.append( ('FONT', (0, indexColoration+1), (-1, indexColoration+1), "Helvetica-Bold", 7) )
                listeStyles.append( ('TEXTCOLOR', (0, indexColoration+1), (-1, indexColoration+1), (1, 1, 1)) )
                listeStyles.append( ('BACKGROUND', (0, indexColoration+1), (-1, indexColoration+1), (0, 0, 0)) )

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes, repeatRows=1)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)
        story.append(Spacer(0,20))

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
示例#8
0
文件: views.py 项目: moodpulse/l2
def gen_pdf_execlist(request):
    """
    Лист исполнения
    :param request:
    :return:
    """
    type = int(request.GET["type"])
    date_start = request.GET["datestart"]
    date_end = request.GET["dateend"]
    if type != 2:
        date_start, date_end = try_parse_range(date_start, date_end)

    researches = json.loads(request.GET["researches"])
    xsize = 8
    ysize = 8
    from reportlab.lib.pagesizes import landscape

    lw, lh = landscape(A4)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="execlist.pdf"'
    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            rightMargin=10,
                            leftMargin=80,
                            topMargin=10,
                            bottomMargin=0)
    doc.pagesize = landscape(A4)

    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    import os.path
    from django.utils.text import Truncator

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf')))
    elements = []
    for res in directory.Researches.objects.filter(pk__in=researches):
        if type != 2:
            iss_list = Issledovaniya.objects.filter(
                tubes__doc_recive_id__isnull=False,
                tubes__time_recive__range=(date_start, date_end),
                time_confirmation__isnull=True,
                research__pk=res.pk,
                deferred=False).order_by('tubes__time_recive')
        else:
            iss_list = Issledovaniya.objects.filter(
                research__pk=res.pk,
                deferred=True,
                time_confirmation__isnull=True,
                tubes__doc_recive__isnull=False).order_by('tubes__time_recive')

        if iss_list.count() == 0:
            # if not hb:
            #    elements.append(PageBreak())
            continue
        pn = 0
        tubes = []
        for iss in iss_list:
            for tube in iss.tubes.all():
                # if not tube.doc_recive:
                #    pass
                # else:
                tubes.append(tube)
        if len(tubes) == 0:
            continue
        pn += 1
        p = Paginator(tubes, xsize * (ysize - 1))

        for pg_num in p.page_range:
            pg = p.page(pg_num)
            data = [[]]
            for j in range(0, xsize):
                data[-1].append("<br/><br/><br/><br/><br/>")
            inpg = Paginator(pg.object_list, xsize)
            for inpg_num in inpg.page_range:
                inpg_o = inpg.page(inpg_num)
                data.append([])
                for inobj in inpg_o.object_list:
                    data[-1].append(
                        inobj.issledovaniya_set.first().napravleniye.client.
                        individual.fio(short=True, dots=True) + ", " +
                        inobj.issledovaniya_set.first().napravleniye.client.
                        individual.age_s(iss=inobj.issledovaniya_set.first()) +
                        "<br/>№ напр.: " +
                        str(inobj.issledovaniya_set.first().napravleniye_id) +
                        "<br/>" + "№ ёмкости: " + str(inobj.pk) + "<br/>" +
                        Truncator(inobj.issledovaniya_set.first().napravleniye.
                                  doc.podrazdeleniye.title).chars(19) +
                        "<br/><br/>")
            if len(data) < ysize:
                for i in range(len(data), ysize):
                    data.append([])
            for y in range(0, ysize):
                if len(data[y]) < xsize:
                    for i in range(len(data[y]), xsize):
                        data[y].append("<br/><br/><br/><br/><br/>")
            style = TableStyle([
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('INNERGRID', (0, 0), (-1, -1), 0.3, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.3, colors.black),
            ])

            s = getSampleStyleSheet()
            s = s["BodyText"]
            s.wordWrap = 'LTR'
            data = transpose(data)
            data2 = [[
                Paragraph('<font face="OpenSans" size="7">' + cell + "</font>",
                          s) for cell in row
            ] for row in data]
            tw = lw - 90
            t = Table(data2,
                      colWidths=[
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8),
                          int(tw / 8)
                      ])
            t.setStyle(style)
            st = ""
            if type == 2:
                st = ", отложенные"
            elements.append(
                Paragraph(
                    '<font face="OpenSans" size="10">' + res.title + st +
                    ", " + str(pg_num) + " стр<br/><br/></font>", s))
            elements.append(t)
            elements.append(PageBreak())

    doc.build(elements)
    pdf = buffer.getvalue()  # Получение данных из буфера
    buffer.close()  # Закрытие буфера
    response.write(pdf)  # Запись PDF в ответ
    return response
示例#9
0
文件: views.py 项目: moodpulse/l2
def print_history(request):
    """Печать истории забора материала за день"""
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.platypus import Table, TableStyle
    from reportlab.lib import colors
    from reportlab.platypus import Paragraph
    from reportlab.lib.styles import getSampleStyleSheet

    styleSheet = getSampleStyleSheet()
    import os.path
    import collections

    filter = False
    filterArray = []
    if "filter" in request.GET.keys():
        filter = True
        filterArray = json.loads(request.GET["filter"])

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER,
                                        'OpenSans.ttf')))  # Загрузка шрифта

    response = HttpResponse(
        content_type='application/pdf')  # Формирование ответа
    response[
        'Content-Disposition'] = 'inline; filename="napr.pdf"'  # Content-Disposition inline для показа PDF в браузере
    buffer = BytesIO()  # Буфер
    c = canvas.Canvas(buffer, pagesize=A4)  # Холст
    tubes = []
    if not filter:
        tubes = TubesRegistration.objects.filter(
            doc_get=request.user.doctorprofile).order_by('time_get').exclude(
                time_get__lt=datetime.now().date())
    else:
        for v in filterArray:
            tubes.append(TubesRegistration.objects.get(pk=v))
    labs = {}  # Словарь с пробирками, сгруппироваными по лаборатории
    for v in tubes:  # Перебор пробирок
        iss = Issledovaniya.objects.filter(
            tubes__id=v.id)  # Получение исследований для пробирки
        iss_list = []  # Список исследований
        k = v.doc_get.podrazdeleniye.title + "@" + str(
            iss[0].research.get_podrazdeleniye().title)
        for val in iss:  # Цикл перевода полученных исследований в список
            iss_list.append(val.research.title)
        if k not in labs.keys(
        ):  # Добавление списка в словарь если по ключу k нету ничего в словаре labs
            labs[k] = []
        for value in iss_list:  # Перебор списка исследований
            labs[k].append(
                {
                    "type":
                    v.type.tube.title,
                    "researches":
                    value,
                    "client-type":
                    iss[0].napravleniye.client.base.short_title,
                    "lab_title":
                    iss[0].research.get_podrazdeleniye().title,
                    "time":
                    strtime(v.time_get),
                    "dir_id":
                    iss[0].napravleniye_id,
                    "podr":
                    v.doc_get.podrazdeleniye.title,
                    "reciver":
                    None,
                    "tube_id":
                    str(v.id),
                    "history_num":
                    iss[0].napravleniye.history_num,
                    "fio":
                    iss[0].napravleniye.client.individual.fio(short=True,
                                                              dots=True),
                }
            )  # Добавление в список исследований и пробирок по ключу k в словарь labs
    labs = collections.OrderedDict(sorted(labs.items()))  # Сортировка словаря
    c.setFont('OpenSans', 20)

    paddingx = 17
    data_header = [
        "№", "ФИО, № истории", "№ емкости", "Тип емкости",
        "Наименования исследований", "Емкость не принята (замечания)"
    ]
    tw = w - paddingx * 4.5
    tx = paddingx * 3
    ty = 90
    c.setFont('OpenSans', 9)
    styleSheet["BodyText"].fontName = "OpenSans"
    styleSheet["BodyText"].fontSize = 7
    doc_num = 0

    for key in labs:
        doc_num += 1
        p = Paginator(labs[key], 47)
        i = 0
        if doc_num >= 2:
            c.showPage()

        for pg_num in p.page_range:
            pg = p.page(pg_num)
            if pg_num >= 0:
                draw_tituls(c, p.num_pages, pg_num, paddingx, pg[0],
                            request.user.doctorprofile.hospital_safe_title)
            data = []
            tmp = []
            for v in data_header:
                tmp.append(Paragraph(str(v), styleSheet["BodyText"]))
            data.append(tmp)
            merge_list = {}
            num = 0
            lastid = "-1"

            for obj in pg.object_list:
                tmp = []
                if lastid != obj["tube_id"]:
                    i += 1
                    lastid = obj["tube_id"]
                    shownum = True
                else:
                    shownum = False
                    if lastid not in merge_list.keys():
                        merge_list[lastid] = []
                    merge_list[lastid].append(num)

                if shownum:
                    tmp.append(Paragraph(str(i), styleSheet["BodyText"]))
                    fio = obj["fio"]
                    if obj["history_num"] and len(obj["history_num"]) > 0:
                        fio += ", " + obj["history_num"]
                    tmp.append(Paragraph(fio, styleSheet["BodyText"]))
                    tmp.append(
                        Paragraph(obj["tube_id"], styleSheet["BodyText"]))
                    tmp.append(Paragraph(obj["type"], styleSheet["BodyText"]))
                else:
                    tmp.append("")
                    tmp.append("")
                    tmp.append("")
                    tmp.append("")
                research_tmp = obj["researches"]
                if len(research_tmp) > 38:
                    research_tmp = research_tmp[0:-(len(research_tmp) -
                                                    38)] + "..."
                tmp.append(Paragraph(research_tmp, styleSheet["BodyText"]))
                tmp.append(Paragraph("", styleSheet["BodyText"]))

                data.append(tmp)
                num += 1

            style = TableStyle([
                ('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                ('LEFTPADDING', (0, 0), (-1, -1), 1),
                ('RIGHTPADDING', (0, 0), (-1, -1), 1),
                ('TOPPADDING', (0, 0), (-1, -1), 1),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
            ])
            for span in merge_list:  # Цикл объединения ячеек
                for pos in range(0, 6):
                    style.add(
                        'INNERGRID', (pos, merge_list[span][0]),
                        (pos, merge_list[span][0] + len(merge_list[span])),
                        0.28, colors.white)
                    style.add(
                        'BOX', (pos, merge_list[span][0]),
                        (pos, merge_list[span][0] + len(merge_list[span])),
                        0.2, colors.black)
            t = Table(data,
                      colWidths=[
                          int(tw * 0.03),
                          int(tw * 0.23),
                          int(tw * 0.08),
                          int(tw * 0.23),
                          int(tw * 0.31),
                          int(tw * 0.14)
                      ],
                      style=style)

            t.canv = c
            wt, ht = t.wrap(0, 0)
            t.drawOn(c, tx, h - ht - ty)
            if pg.has_next():
                c.showPage()

    c.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    slog.Log(key="", type=10, body="", user=request.user.doctorprofile).save()
    return response
示例#10
0
文件: views.py 项目: moodpulse/l2
def gen_pdf_dir(request):
    """Генерация PDF направлений"""
    direction_id = json.loads(request.GET.get("napr_id", '[]'))
    if direction_id == []:
        request_direction_id = json.loads(request.body)
        direction_id = request_direction_id.get("napr_id", "[]")
    if SettingManager.get(
            "pdf_auto_print", "true", "b"
    ) and not request.GET.get('normis') and not request.GET.get('embedded'):
        pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="directions.pdf"'

    pdfmetrics.registerFont(
        TTFont('OpenSans', os.path.join(FONTS_FOLDER, 'OpenSans.ttf')))
    pdfmetrics.registerFont(
        TTFont('OpenSansBold', os.path.join(FONTS_FOLDER,
                                            'OpenSans-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('TimesNewRoman', os.path.join(FONTS_FOLDER,
                                             'TimesNewRoman.ttf')))
    dn = (Napravleniya.objects.filter(pk__in=direction_id).prefetch_related(
        Prefetch(
            'issledovaniya_set',
            queryset=Issledovaniya.objects.all().select_related(
                'research', 'research__podrazdeleniye', 'localization',
                'service_location').prefetch_related(
                    'research__fractions_set'),
        )).select_related(
            'client',
            'client__base',
            'client__individual',
            'parent',
            'parent__research',
            'doc_who_create',
            'doc_who_create__podrazdeleniye',
            'doc',
            'doc__podrazdeleniye',
            'imported_org',
            'istochnik_f',
        ).order_by('pk'))

    donepage = dn.exclude(issledovaniya__research__direction_form=0)
    donepage = donepage.exclude(external_organization__isnull=False)
    external_org_form = dn.filter(external_organization__isnull=False)

    buffer = BytesIO()
    count_direction = len(direction_id)
    format_A6 = SettingManager.get(
        "format_A6", default='False',
        default_type='b') and count_direction == 1 and donepage.count() == 0
    page_size = A6 if format_A6 else A4
    c = canvas.Canvas(buffer, pagesize=page_size)
    c.setTitle('Направления {}'.format(', '.join(
        [str(x) for x in direction_id])))

    # для внешних организацй
    external_print_form = False
    if external_org_form.count() > 0:
        external_print_form = True
        f = import_string('directions.forms.forms' + '380' + '.form_' + '05')
        c = canvas.Canvas(buffer, pagesize=A4)
        f(c, external_org_form)

    ddef = dn.filter(issledovaniya__research__direction_form=0,
                     external_organization=None).distinct()
    p = Paginator(ddef, 4)  # Деление списка направлений по 4
    instructions = []
    has_def = ddef.count() > 0
    def_form_print = False
    if has_def and not format_A6:
        if external_print_form:
            def_form_print = True
            c.showPage()
        framePage(c)
    for pg_num in p.page_range:
        pg = p.page(pg_num)
        i = 4  # Номер позиции направления на странице (4..1)
        for n_ob in pg.object_list:  # Перебор номеров направлений на странице
            def_form_print = True
            print_direction(
                c, i, n_ob, format_A6
            )  # Вызов функции печати направления на указанную позицию
            instructions += n_ob.get_instructions()
            i -= 1
        if pg.has_next():  # Если есть следующая страница
            c.showPage()  # Создание новой страницы
            framePage(c)  # Рисование разделительных линий для страницы

    if donepage.count() > 0 and has_def:
        if external_print_form or def_form_print:
            c.showPage()
    n = 0
    cntn = donepage.count()
    for d in donepage:
        n += 1
        iss = d.issledovaniya_set.all()
        if not iss.exists():
            continue
        form = iss[0].research.direction_form
        if form != 0 and not d.external_organization:
            current_type_form = str(form)
            f = import_string('directions.forms.forms' +
                              current_type_form[0:3] + '.form_' +
                              current_type_form[3:5])
            f(c, d)
        if n != cntn:
            c.showPage()

    instructions_pks = []
    instructions_filtered = []
    for i in instructions:
        if i["pk"] in instructions_pks:
            continue
        instructions_pks.append(i["pk"])
        instructions_filtered.append(i)
    if len(instructions_filtered) > 0:
        s = getSampleStyleSheet()
        s = s["BodyText"]
        s.wordWrap = 'LTR'
        c.showPage()
        tx = '<font face="OpenSansBold" size="10">Памятка пациенту по проведению исследований</font>\n'
        for i in instructions_filtered:
            tx += '--------------------------------------------------------------------------------------\n<font face="OpenSansBold" size="10">{}</font>\n<font face="OpenSans" size="10">&nbsp;&nbsp;&nbsp;&nbsp;{}\n</font>'.format(  # noqa: E501
                i["title"], i["text"])
        data = [[Paragraph(tx.replace("\n", "<br/>"), s)]]

        t = Table(data, colWidths=[w - 30 * mm])
        t.setStyle(
            TableStyle([
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.white),
                ('LEFTPADDING', (0, 0), (-1, -1), 4),
                ('TOPPADDING', (0, 0), (-1, -1), 0.5),
                ('RIGHTPADDING', (0, 0), (-1, -1), 2),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
            ]))
        t.canv = c
        wt, ht = t.wrap(0, 0)
        t.drawOn(c, 15 * mm, h - 15 * mm - ht)
        c.showPage()

    c.save()  # Сохранение отрисованного на PDF
    pdf = buffer.getvalue()  # Получение данных из буфера

    # Проверить, если единый источник финансирвоания у направлений и title==платно, тогода печатать контракт
    fin_ist_set = set()
    card_pk_set = set()
    for n in dn:
        if n.istochnik_f:
            fin_ist_set.add(n.istochnik_f)
        card_pk_set.add(n.client_id)

    internal_type = n.client.base.internal_type

    fin_status = None
    if fin_ist_set and fin_ist_set.pop().title.lower() == 'платно':
        fin_status = True

    if request.GET.get("contract") and internal_type:
        if request.GET["contract"] == '1' and SettingManager.get(
                "direction_contract", default='False', default_type='b'):
            if len(card_pk_set) == 1 and fin_status:
                new_form_contract = SettingManager.get("new_form_contract",
                                                       default='True',
                                                       default_type='b')
                if new_form_contract:
                    from forms.forms102 import form_02 as f_contract
                else:
                    from forms.forms102 import form_01 as f_contract

                fc = f_contract(
                    request_data={
                        **dict(request.GET.items()),
                        "user": request.user,
                        "card_pk": card_pk_set.pop(),
                        "hospital": request.user.doctorprofile.get_hospital(),
                    })
                if fc:
                    fc_buf = BytesIO()
                    fc_buf.write(fc)
                    fc_buf.seek(0)
                    buffer.seek(0)
                    from pdfrw import PdfReader, PdfWriter

                    today = datetime.now()
                    date_now1 = datetime.strftime(today, "%y%m%d%H%M%S%f")[:-3]
                    date_now_str = str(n.client_id) + str(date_now1)
                    dir_param = SettingManager.get("dir_param",
                                                   default='/tmp',
                                                   default_type='s')
                    file_dir = os.path.join(dir_param,
                                            date_now_str + '_dir.pdf')
                    file_contract = os.path.join(
                        dir_param, date_now_str + '_contract.pdf')
                    save_tmp_file(buffer, filename=file_dir)
                    save_tmp_file(fc_buf, filename=file_contract)
                    pdf_all = BytesIO()
                    inputs = [file_contract] if SettingManager.get(
                        "only_contract", default='False',
                        default_type='b') else [file_dir, file_contract]
                    writer = PdfWriter()
                    for inpfn in inputs:
                        writer.addpages(PdfReader(inpfn).pages)
                    writer.write(pdf_all)
                    pdf_out = pdf_all.getvalue()
                    pdf_all.close()
                    response.write(pdf_out)
                    buffer.close()
                    os.remove(file_dir)
                    os.remove(file_contract)
                    fc_buf.close()
                    return response

    buffer.close()  # Закрытие буфера

    response.write(pdf)  # Запись PDF в ответ

    return response
示例#11
0
文件: views.py 项目: moodpulse/l2
def print_direction(c: Canvas, n, dir: Napravleniya, format_a6: bool = False):
    xn, yn = 0, 0
    if not format_a6:
        if n % 2 != 0:
            xn = 1
        if n > 2:
            yn = 1

    barcode = eanbc.Ean13BarcodeWidget(dir.pk + 460000000000,
                                       humanReadable=0,
                                       barHeight=17)
    bounds = barcode.getBounds()
    width = bounds[2] - bounds[0]
    height = bounds[3] - bounds[1]
    d = Drawing(width, height)
    d.add(barcode)
    paddingx = 15
    ac = dir.is_all_confirm()
    canc = dir.cancel
    visit = dir.visit_date is not None
    if ac or canc or visit:
        c.saveState()
        c.setFillColorRGB(0, 0, 0, 0.2)
        c.rotate(45)
        if xn == 0 and yn == 1:
            ox = w / 2 + 40 * mm
            oy = h / 2 - 30 * mm
        elif xn == 0 and yn == 0:
            ox = w / 2 - 65 * mm
            oy = 13.5 * mm
        elif xn == 1 and yn == 0:
            ox = w - 95.75 * mm
            oy = 13.5 * mm - h / 4
        else:
            ox = w + 9.25 * mm
            oy = h / 2 - 30 * mm - h / 4
        c.setFont('OpenSansBold', 50)
        s = 'ОТМЕНЕНО'
        if ac:
            s = 'ИСПОЛНЕНО'
        elif visit:
            s = 'ПОСЕЩЕНО'
        c.drawString(ox, oy, s)
        c.restoreState()

    c.setFont('OpenSans', 10)
    c.drawCentredString(w / 2 - w / 4 + (w / 2 * xn),
                        (h / 2 - height - 5) + (h / 2) * yn,
                        dir.hospital_short_title)

    c.setFont('OpenSans', 8)
    c.drawCentredString(
        w / 2 - w / 4 + (w / 2 * xn), (h / 2 - height - 15) + (h / 2) * yn,
        "(%s. %s)" % (dir.hospital_address, dir.hospital_phones))

    c.setFont('OpenSans', 14)
    c.drawCentredString(
        w / 2 - w / 4 + (w / 2 * xn), (h / 2 - height - 30) + (h / 2) * yn,
        "Направление" + ("" if not dir.imported_from_rmis else " из РМИС"))

    renderPDF.draw(d, c, w / 2 - width + (w / 2 * xn) - paddingx / 3 - 5 * mm,
                   (h / 2 - height - 57) + (h / 2) * yn)

    c.setFont('OpenSans', 20)
    c.drawString(paddingx + (w / 2 * xn), (h / 2 - height) + (h / 2) * yn - 57,
                 "№ " + str(dir.pk))  # Номер направления

    c.setFont('OpenSans', 9)
    c.drawString(
        paddingx + (w / 2 * xn), (h / 2 - height - 70) + (h / 2) * yn,
        "Создано: " + strdate(dir.data_sozdaniya) + " " +
        strtime(dir.data_sozdaniya)[:5])
    history_num = dir.history_num
    additional_num = dir.additional_num
    if history_num and len(history_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          "№ истории: " + history_num)
    elif additional_num and len(additional_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          f"({str(additional_num).strip()})")
    elif dir.client.number_poliklinika and len(
            dir.client.number_poliklinika) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          f"({str(dir.client.number_poliklinika).strip()})")

    if dir.history_num and len(dir.history_num) > 0:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 70) + (h / 2) * yn,
                          "№ истории: " + dir.history_num)

    c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 80) + (h / 2) * yn,
                 "ФИО: " + dir.client.individual.fio())

    c.drawRightString(w / 2 * (xn + 1) - paddingx,
                      (h / 2 - height - 80) + (h / 2) * yn,
                      "Пол: " + dir.client.individual.sex)

    c.drawRightString(
        w / 2 * (xn + 1) - paddingx, (h / 2 - height - 90) + (h / 2) * yn,
        "Д/р: {} ({})".format(dir.client.individual.bd(),
                              dir.client.individual.age_s(direction=dir)))

    c.drawString(
        paddingx + (w / 2 * xn), (h / 2 - height - 90) + (h / 2) * yn,
        "{}: {}".format("ID" if dir.client.base.is_rmis else "Номер карты",
                        dir.client.number_with_type()))
    diagnosis = dir.diagnos.strip()[:35]
    if not dir.imported_from_rmis:
        if diagnosis != "":
            c.drawString(
                paddingx + (w / 2 * xn),
                (h / 2 - height - 100) + (h / 2) * yn,
                ("" if dir.vich_code == "" else
                 ("Код: " + dir.vich_code + "  ")) + "Диагноз (МКБ 10): " +
                ("не указан" if diagnosis == "-" else diagnosis),
            )
        elif dir.vich_code != "":
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 100) + (h / 2) * yn,
                         "Код: " + dir.vich_code)
        if dir.istochnik_f:
            c.drawString(
                paddingx + (w / 2 * xn), (h / 2 - height - 110) + (h / 2) * yn,
                "Источник финансирования: " + dir.client.base.title + " - " +
                dir.istochnik_f.title)
        else:
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 110) + (h / 2) * yn,
                         "Источник финансирования: ")
    else:
        nds = 0
        if diagnosis != "":
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 100) + (h / 2) * yn,
                         "Диагноз (МКБ 10): " + diagnosis)
            nds = 5
        if dir.imported_org:
            c.drawString(paddingx + (w / 2 * xn),
                         (h / 2 - height - 105 - nds) + (h / 2) * yn,
                         "Организация: " + dir.imported_org.title)

    issledovaniya = dir.issledovaniya_set.all()

    vid = []
    has_descriptive = False
    has_doc_refferal = False
    need_qr_code = False
    for i in issledovaniya:
        rtp = i.research.reversed_type
        if rtp < -1:
            has_doc_refferal = True
            rt = {
                -2: 'Консультации',
                -3: 'Лечение',
                -4: 'Стоматология',
                -5: 'Стационар',
                -6: 'Микробиология',
                -9998: 'Морфология',
                -9: 'Формы',
                -11: 'Заявления',
                -12: 'Мониторинги',
            }[rtp]
            # if rtp == -6:
            #     has_micro = True
        else:
            rt = i.research.podrazdeleniye.get_title()
        if rt not in vid:
            vid.append(rt)
            if i.research.podrazdeleniye and i.research.podrazdeleniye.p_type == Podrazdeleniya.PARACLINIC:
                has_descriptive = True
                if i.research.podrazdeleniye.can_has_pacs:
                    need_qr_code = True

    c.drawString(paddingx + (w / 2 * xn),
                 (h / 2 - height - 120) + (h / 2) * yn,
                 "Вид: " + ", ".join(vid))

    if dir.purpose:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 120) + (h / 2) * yn,
                          "Цель: " + dir.get_purpose_display())

    if dir.external_organization:
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 134) + (h / 2) * yn,
                          dir.external_organization.title)

    if dir.parent and dir.parent.research.is_hospital:
        c.setFont('OpenSansBold', 8)
        c.drawRightString(w / 2 * (xn + 1) - paddingx,
                          (h / 2 - height - 129) + (h / 2) * yn,
                          ("Стационар-" + str(dir.parent.napravleniye_id)))
    c.setFont('OpenSans', 9)

    styleSheet = getSampleStyleSheet()

    all_iss = issledovaniya.count()
    max_f = 9
    min_f = 7
    max_res = 36

    max_off = max_f - min_f
    font_size = max_f - (max_off * (all_iss / max_res))

    styleSheet["BodyText"].leading = font_size + 0.5
    data = []

    values = []

    service_locations = {}

    n = 0
    for v in issledovaniya:
        n += 1
        service_location_title = "" if not v.service_location else v.service_location.title
        if service_location_title:
            if service_location_title not in service_locations:
                service_locations[service_location_title] = []
            service_locations[service_location_title].append(n)
        values.append({
            "title":
            v.research.get_title(),
            "full_title":
            v.research.title,
            "sw":
            v.research.sort_weight,
            "count":
            v.how_many,
            "comment":
            v.localization.title if v.localization else v.comment,
            "n":
            n,
            "g":
            -1 if not v.research.fractions_set.exists() else
            v.research.fractions_set.first().relation_id,
            "info":
            v.research.paraclinic_info,
            "hospital_department_replaced_title":
            v.hospital_department_replaced_title,
        })

    one_sl = len(service_locations) <= 1

    tw = w / 2 - paddingx * 2
    m = 0
    ns = {}
    if has_descriptive or has_doc_refferal:
        tmp = [
            Paragraph(
                '<font face="OpenSansBold" size="8">%s</font>' %
                ("Исследование" if not has_doc_refferal else "Назначение"),
                styleSheet["BodyText"]),
            Paragraph('<font face="OpenSansBold" size="8">Информация</font>',
                      styleSheet["BodyText"]),
        ]
        data.append(tmp)
        colWidths = [int(tw * 0.5), int(tw * 0.5)]
        values.sort(key=lambda l: l["full_title"])

        for v in values:
            ns[v["n"]] = v["n"]
            tmp = [
                Paragraph(
                    '<font face="OpenSans" size="8">' +
                    ("" if one_sl else "№{}: ".format(v["n"])) +
                    xh.fix(v["full_title"]) +
                    ("" if not v["comment"] else
                     " <font face=\"OpenSans\" size=\"" +
                     str(font_size * 0.8) +
                     "\">[{}]</font>".format(v["comment"])) +
                    ("" if not v["hospital_department_replaced_title"] else
                     f"<br/>Направлен в: {v['hospital_department_replaced_title']}"
                     ) + "</font>",
                    styleSheet["BodyText"],
                ),
                Paragraph(
                    '<font face="OpenSans" size="8">' + xh.fix(v["info"]) +
                    "</font>", styleSheet["BodyText"]),
            ]
            data.append(tmp)
        m = 8
    else:
        colWidths = [int(tw / 2), int(tw / 2)]
        c.drawString(paddingx + (w / 2 * xn),
                     (h / 2 - height - 134) + (h / 2) * yn, "Назначения: ")
        c.setStrokeColorRGB(0, 0, 0)
        c.setLineWidth(1)
        values.sort(key=lambda l: (l["g"], l["sw"]))

        n_rows = int(len(values) / 2)

        normvars = []
        c_cnt = nc_cnt = 0
        for i in range(0, len(values) + 1):
            if (i + 1) % 2 == 0:
                nc_cnt += 1
                if nc_cnt + n_rows < len(values):
                    normvars.append(values[nc_cnt + n_rows])
            else:
                normvars.append(values[c_cnt])
                c_cnt += 1

        p = Paginator(normvars, 2)
        n = 1
        for pg_num in p.page_range:
            pg = p.page(pg_num)
            tmp = []
            for obj in pg.object_list:
                ns[obj["n"]] = n
                tmp.append(
                    Paragraph(
                        '<font face="OpenSans" size="' + str(font_size) +
                        '">' + ("" if one_sl else "№{}: ".format(n)) +
                        obj["title"] +
                        ("" if not obj["count"] or obj["count"] == 1 else
                         " ({}шт.)".format(str(obj["count"]))) +
                        ("" if not obj["comment"] else
                         " <font face=\"OpenSans\" size=\"" +
                         str(font_size * 0.8) +
                         "\">[{}]</font>".format(obj["comment"])) + "</font>",
                        styleSheet["BodyText"],
                    ))
                n += 1
            if len(pg.object_list) < 2:
                tmp.append(
                    Paragraph(
                        '<font face="OpenSans" size="' + str(font_size) +
                        '"></font>', styleSheet["BodyText"]))
            data.append(tmp)

    t = Table(data, colWidths=colWidths)
    t.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TEXTCOLOR', (0, -1), (-1, -1), colors.black),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('LEFTPADDING', (0, 0), (-1, -1), 4),
            ('TOPPADDING', (0, 0), (-1, -1), 0.5),
            ('RIGHTPADDING', (0, 0), (-1, -1), 2),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ]))
    t.canv = c
    wt, ht = t.wrap(0, 0)
    t.drawOn(c, paddingx + (w / 2 * xn),
             ((h / 2 - height - 138 + m) + (h / 2) * yn - ht))

    c.setFont('OpenSans', 8)
    if not has_descriptive and not has_doc_refferal:
        c.drawString(paddingx + (w / 2 * xn),
                     (h / 2 - height - 138 + m) + (h / 2) * yn - ht - 10,
                     "Всего назначено: " + str(len(issledovaniya)))

    if service_locations:
        n = 0 if has_descriptive or has_doc_refferal else 1
        if one_sl:
            c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 138 + m) +
                         (h / 2) * yn - ht - 14 - n * 10,
                         "Место: " + list(service_locations)[0])
        else:
            c.drawString(paddingx + (w / 2 * xn), (h / 2 - height - 138 + m) +
                         (h / 2) * yn - ht - 14 - n * 10,
                         "Места оказания услуг:")
            for title in service_locations:
                n += 1
                c.drawString(
                    paddingx + (w / 2 * xn),
                    (h / 2 - height - 138 + m) + (h / 2) * yn - ht - 14 -
                    n * 10,
                    title + " – услуги " + ', '.join(
                        map(lambda x: "№{}".format(ns[x]),
                            service_locations[title])),
                )

    if need_qr_code:
        qr_value = translit(dir.client.individual.fio(), 'ru', reversed=True)
        qr_code = qr.QrCodeWidget(qr_value)
        qr_code.barWidth = 70
        qr_code.barHeight = 70
        qr_code.qrVersion = 1
        d = Drawing()
        d.add(qr_code)
        renderPDF.draw(d, c, paddingx + (w / 2 * xn) + 200, 32 + (h / 2) * yn)

    nn = 0
    if not dir.imported_from_rmis:
        if dir.doc_who_create and dir.doc_who_create != dir.doc:
            nn = 9
            c.drawString(
                paddingx + (w / 2 * xn), 13 + (h / 2) * yn,
                Truncator("Выписал: %s, %s" %
                          (dir.doc_who_create.get_fio(),
                           dir.doc_who_create.podrazdeleniye.title)).chars(63))

        if dir.doc:
            c.drawString(
                paddingx + (w / 2 * xn), 22 + (h / 2) * yn + nn,
                "Отделение: " +
                Truncator(dir.get_doc_podrazdeleniye_title()).chars(50))
            c.drawString(paddingx + (w / 2 * xn), 13 + (h / 2) * yn + nn,
                         "Л/врач: " + dir.doc.get_fio())
    else:
        c.drawString(paddingx + (w / 2 * xn), 31 + (h / 2) * yn + nn,
                     "РМИС#" + dir.rmis_number)
        c.drawString(paddingx + (w / 2 * xn), 22 + (h / 2) * yn + nn,
                     "Создал направление: " + dir.doc_who_create.get_fio())
        c.drawString(paddingx + (w / 2 * xn), 13 + (h / 2) * yn + nn,
                     dir.doc_who_create.podrazdeleniye.title)

    c.setFont('OpenSans', 7)
    c.setLineWidth(0.25)
示例#12
0
def generate_cheatsheet(fname, profile):
    """Generates a cheatsheet of the provided profile.

    :param fname the file to store the cheatsheet in
    :param profile the profile to process
    """

    width, height = A4

    styles = getSampleStyleSheet()
    main_frame = Frame(cm, cm, width-2*cm, height-2*cm, showBoundary=False)
    main_template = PageTemplate(id="main", frames=[main_frame])
    doc = BaseDocTemplate(fname, pageTemplates=[main_template])

    story = []
    style = styles["Normal"]

    # Build device actions considering inheritance
    inheritance_tree = profile.build_inheritance_tree()
    device_storage = {}
    for key, device in profile.devices.items():
        device_storage[device] = {}
        recursive(device, inheritance_tree, device_storage[device])

    for dev, dev_data in device_storage.items():
        dev_float_added = False
        for mode_name, mode_data in dev_data.items():
            # Only proceed if we actually have input items available
            if len(mode_data.values()) == 0:
                continue

            if not dev_float_added:
                story.append(DeviceFloat(dev.name))
                story.append(Spacer(1, 0.25 * cm))
                dev_float_added = True

            # Add heading for device and mode combination
            story.append(ModeFloat(mode_name))
            table_data = [entry.table_data() for entry in mode_data.values()]

            table_style = style = [
                ("LINEBELOW", (0, 0), (-1, -2), 0.25, HexColor("#c0c0c0")),
                ("VALIGN", (0, 0), (-1, -1), "TOP")
            ]
            if len(table_data) == 1:
                table_style = []
            story.append(Table(
                table_data,
                colWidths=[
                    0.15 * (width - 2 * cm),
                    0.30 * (width - 2 * cm),
                    0.55 * (width - 2 * cm)
                ],
                rowHeights=[None] * len(table_data),
                style=table_style
            ))
            story.append(Spacer(1, 0.50 * cm))

        if dev_float_added:
            del story[-1]
            story.append(PageBreak())

    doc.build(story)
示例#13
0
def header(canvas, doc):
    global margin
    canvas.saveState()
    canvas.setFont('Helvetica-Bold', 11)
    canvas.drawString(
        margin, pagesizes.letter[1] - margin * 1.2,
        "%s: verses %d-%d words long, at least %d verses apart" %
        (TITLE, MIN_WORDS, MAX_WORDS, MIN_DISTANCE))
    canvas.drawString(margin, margin, "Page %d" % (doc.page))
    canvas.restoreState()


# convert verses into pdf paragraphs
selected = map(verse_to_table, selected)

# build pdf table
style = TableStyle()
style.add('VALIGN', (0, 0), (-1, -1), 'TOP')
style.add('GRID', (0, 0), (-1, -1), 1, colors.black)
table = Table(selected, [width * 0.2, width * 0.8])
table.setStyle(style)

# build pdf output
doc = SimpleDocTemplate("out_quotingbee.pdf",
                        pagesize=pagesizes.letter,
                        topMargin=margin * 1.5,
                        leftMargin=margin,
                        bottomMargin=margin * 1.5,
                        rightMargin=margin)
doc.build([table], onFirstPage=header, onLaterPages=header)
示例#14
0
文件: views.py 项目: Shirk/OpenSlides
    def append_to_pdf(self, story):
        imgpath = os.path.join(settings.SITE_ROOT, 'static/images/circle.png')
        circle = "<img src='%s' width='15' height='15'/>&nbsp;&nbsp;" % imgpath
        cell = []
        cell.append(Spacer(0,0.8*cm))
        cell.append(Paragraph(_("Election") + ": " + self.poll.assignment.name,
            stylesheet['Ballot_title']))
        cell.append(Paragraph(self.poll.assignment.polldescription,
            stylesheet['Ballot_subtitle']))
        options = self.poll.get_options().order_by('candidate')

        ballot_string = _("%d. ballot") % self.poll.get_ballot()
        candidate_string = ungettext("%d candidate", "%d candidates",
            len(options)) % len(options)
        available_posts_string = ungettext("%d available post", "%d available posts",
            self.poll.assignment.posts) % self.poll.assignment.posts
        cell.append(Paragraph("%s, %s, %s" % (ballot_string, candidate_string,
            available_posts_string), stylesheet['Ballot_description']))
        cell.append(Spacer(0, 0.4 * cm))

        data= []
        # get ballot papers config values
        ballot_papers_selection = config["assignment_pdf_ballot_papers_selection"]
        ballot_papers_number = config["assignment_pdf_ballot_papers_number"]

        # set number of ballot papers
        if ballot_papers_selection == "NUMBER_OF_DELEGATES":
            number = User.objects.filter(type__iexact="delegate").count()
        elif ballot_papers_selection == "NUMBER_OF_ALL_PARTICIPANTS":
            number = int(User.objects.count())
        else: # ballot_papers_selection == "CUSTOM_NUMBER"
            number = int(ballot_papers_number)
        number = max(1, number)

        # Choose kind of ballot paper
        if self.poll.yesnoabstain:
            for option in options:
                candidate = option.candidate
                cell.append(Paragraph(candidate.clean_name,
                    stylesheet['Ballot_option_name']))
                if candidate.name_suffix:
                    cell.append(Paragraph("(%s)" % candidate.name_suffix,
                        stylesheet['Ballot_option_group']))
                else:
                    cell.append(Paragraph("&nbsp;",
                        stylesheet['Ballot_option_group']))
                cell.append(Paragraph(circle + _("Yes") + "&nbsp; " * 3 + circle
                    + _("No") + "&nbsp; " * 3 + circle+ _("Abstention"),
                    stylesheet['Ballot_option_YNA']))
            # print ballot papers
            for user in xrange(number / 2):
                data.append([cell, cell])
            rest = number % 2
            if rest:
                data.append([cell, ''])
            if len(options) <= 2:
                t = Table(data, 10.5 * cm, 7.42 * cm)
            elif len(options) <= 5:
                t = Table(data, 10.5 * cm, 14.84 * cm)
            else:
                t = Table(data, 10.5 * cm, 29.7 * cm)
        else:
            for option in options:
                candidate = option.candidate
                cell.append(Paragraph(circle + candidate.clean_name,
                    stylesheet['Ballot_option_name']))
                if candidate.name_suffix:
                    cell.append(Paragraph("(%s)" % candidate.name_suffix,
                        stylesheet['Ballot_option_group_right']))
                else:
                    cell.append(Paragraph("&nbsp;",
                        stylesheet['Ballot_option_group_right']))
            # print ballot papers
            for user in xrange(number / 2):
                data.append([cell, cell])
            rest = number % 2
            if rest:
                data.append([cell, ''])
            if len(options) <= 4:
                t = Table(data, 10.5 * cm, 7.42 * cm)
            elif len(options) <= 8:
                t = Table(data, 10.5 * cm, 14.84 * cm)
            else:
                t = Table(data, 10.5 * cm, 29.7 * cm)

        t.setStyle(TableStyle([('GRID', (0, 0), (-1, -1), 0.25, colors.grey),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
        story.append(t)
示例#15
0
def draw_pdf(buffer, invoice):
    """ Draws the invoice """
    canvas = Canvas(buffer, pagesize=A4)
    canvas.translate(0, 29.7 * cm)
    canvas.setFont('Helvetica', 10)

    canvas.saveState()
    header_func(canvas)
    canvas.restoreState()

    canvas.saveState()
    footer_func(canvas)
    canvas.restoreState()

    canvas.saveState()
    address_func(canvas)
    canvas.restoreState()

    # Client address
    textobject = canvas.beginText(1.5 * cm, -2.5 * cm)
    try:
        if invoice.address.invoice_contact_name:
            textobject.textLine(invoice.address.invoice_contact_name)
        textobject.textLine(invoice.address.invoice_address_one)
        if invoice.address.invoice_address_two:
            textobject.textLine(invoice.address.invoice_address_two)
        textobject.textLine(invoice.address.invoice_town)
        if invoice.address.invoice_county:
            textobject.textLine(invoice.address.invoice_county)
        textobject.textLine(invoice.address.invoice_postcode)
        textobject.textLine(invoice.address.country.invoice_name)
    except:
        pass
    canvas.drawText(textobject)

    # Info
    textobject = canvas.beginText(1.5 * cm, -6.75 * cm)
    textobject.textLine(u'Invoice ID: %s' % invoice.invoice_id)
    textobject.textLine(u'Invoice Date: %s' % invoice.invoice_date.strftime(
        '%d %b %Y'))
    canvas.drawText(textobject)

    # Items
    data = [[u'Quantity', u'Description', u'Amount', u'Total'], ]
    for item in invoice.items.all():
        data.append([
            item.quantity,
            item.description,
            format_currency(item.unit_price, invoice.currency),
            format_currency(item.total(), invoice.currency)
        ])
    data.append([u'', u'', u'Total:', format_currency(invoice.total(),
                 invoice.currency)])
    table = Table(data, colWidths=[2 * cm, 11 * cm, 3 * cm, 3 * cm])
    table.setStyle([
        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('TEXTCOLOR', (0, 0), (-1, -1), (0.2, 0.2, 0.2)),
        ('GRID', (0, 0), (-1, -2), 1, (0.7, 0.7, 0.7)),
        ('GRID', (-2, -1), (-1, -1), 1, (0.7, 0.7, 0.7)),
        ('ALIGN', (-2, 0), (-1, -1), 'RIGHT'),
        ('BACKGROUND', (0, 0), (-1, 0), (0.8, 0.8, 0.8)),
    ])
    tw, th, = table.wrapOn(canvas, 15 * cm, 19 * cm)
    table.drawOn(canvas, 1 * cm, -8 * cm - th)

    canvas.showPage()
    canvas.save()

    return canvas
    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 TAFONOMICA<br/>" + str(self.datestrfdate()) + "</b>", styNormal)

        # intestazione2 = Paragraph("<b>pyArchInit</b><br/>pyarchinit", styNormal)

        # intestazione2  = Paragraph("<b>Ditta esecutrice</b><br/>", styNormal)
        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

        home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
        logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        # 1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        sigla_struttura = Paragraph("<b>Sigla struttura</b><br/>" + str(self.sigla_struttura) + str(self.nr_struttura),
                                    styNormal)
        nr_individuo = Paragraph("<b>Nr. Individuo</b><br/>" + str(self.nr_individuo), styNormal)
        nr_scheda = Paragraph("<b>Nr. Scheda</b><br/>" + str(self.nr_scheda_taf), styNormal)

        # 2 row
        periodizzazione = Paragraph("<b>PERIODIZZAZIONE DEL RITO DI SEPOLTURA</b><br/>", styNormal)

        # 3 row
        if str(self.periodo_iniziale) == "None":
            periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>", styNormal)
        else:
            periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>" + str(self.periodo_iniziale), styNormal)

        if str(self.fase_iniziale) == "None":
            fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>", styNormal)
        else:
            fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>" + str(self.fase_iniziale), styNormal)

        if str(self.periodo_finale) == "None":
            periodo_finale = Paragraph("<b>Periodo finale</b><br/>", styNormal)
        else:
            periodo_finale = Paragraph("<b>Periodo finale</b><br/>" + str(self.periodo_finale), styNormal)

        if str(self.fase_finale) == "None":
            fase_finale = Paragraph("<b>Fase finale</b><br/>", styNormal)
        else:
            fase_finale = Paragraph("<b>Fase finale</b><br/>" + str(self.fase_finale), styNormal)

        # 4 row
        if str(self.datazione_estesa) == "None":
            datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>", styNormal)
        else:
            datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>" + self.datazione_estesa, styNormal)

        # 5 row
        elementi_strutturali = Paragraph("<b>ELEMENTI STRUTTURALI</b><br/>", styNormal)

        # 6row
        tipo_contenitore_resti = Paragraph("<b>Tipo contenitore resti</b><br/>" + self.tipo_contenitore_resti,
                                           styNormal)
        tipo_copertura = Paragraph("<b>Tipo copertura</b><br/>" + self.copertura_tipo, styNormal)
        segnacoli = Paragraph("<b>Segnacoli</b><br/>" + self.segnacoli, styNormal)
        canale_libatorio = Paragraph("<b>Canale libatorio</b><br/>" + self.canale_libatorio_si_no, styNormal)

        # 7 row
        dati_deposizionali = Paragraph("<b>DATI DEPOSIZIONALI INUMATO</b><br/>", styNormal)

        # 8 row
        rito = Paragraph("<b>Rito</b><br/>" + self.rito, styNormal)
        orientamento_asse = Paragraph("<b>Orientamento asse</b><br/>" + str(self.orientamento_asse), styNormal)
        if str(self.orientamento_azimut) == "None":
            orientamento_azimut = Paragraph("<b>Azimut</b><br/>", styNormal)
        else:
            orientamento_azimut_conv = self.PU.conversione_numeri(self.orientamento_azimut)
            orientamento_azimut = Paragraph("<b>Azimut</b><br/>" + orientamento_azimut_conv + "°", styNormal)
        posizione_cranio = Paragraph("<b>Posizione cranio</b><br/>" + str(self.posizione_cranio), styNormal)

        # 9 row
        posizione_scheletro = Paragraph("<b>Posizione scheletro</b><br/>" + str(self.posizione_scheletro), styNormal)
        if str(self.lunghezza_scheletro) == "None":
            lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>", styNormal)
        else:
            lunghezza_scheletro_conv = self.PU.conversione_numeri(self.lunghezza_scheletro)
            lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>" + lunghezza_scheletro_conv + " m",
                                            styNormal)
        posizione_arti_superiori = Paragraph(
            "<b>Posizione arti superiori</b><br/>" + str(self.posizione_arti_superiori), styNormal)
        posizione_arti_inferiori = Paragraph(
            "<b>Posizione arti inferiori</b><br/>" + str(self.posizione_arti_inferiori), styNormal)

        # 10 row
        dati_postdeposizionali = Paragraph("<b>DATI POSTDEPOSIZIONALI</b><br/>", styNormal)

        # 11 row
        stato_conservazione = Paragraph("<b>Stato di conservazione</b><br/>" + str(self.stato_di_conservazione),
                                        styNormal)
        disturbato = Paragraph("<b>Disturbato</b><br/>" + str(self.segnacoli), styNormal)
        completo = Paragraph("<b>Completo</b><br/>" + str(self.canale_libatorio_si_no), styNormal)
        in_connessione = Paragraph("<b>In connessione</b><br/>" + str(self.oggetti_rinvenuti_esterno), styNormal)

        # 12 row
        caratteristiche_tafonomiche = ''
        caratteristiche_list = eval(self.caratteristiche)
        if len(caratteristiche_list) > 0:
            for i in caratteristiche_list:
                if caratteristiche_tafonomiche == '':
                    caratteristiche_tafonomiche = ("Tipo caratteristica: %s, posizione: %s") % (str(i[0]), str(i[1]))
                else:
                    caratteristiche_tafonomiche += ("<br/>Tipo caratteristica: %s, posizione: %s") % (
                    str(i[0]), str(i[1]))

        caratteristiche_tafonomiche_txt = Paragraph(
            "<b>CARATTERISTICHE TAFONOMICHE</b><br/>" + caratteristiche_tafonomiche, styNormal)

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

        interpretazione = ''
        try:
            interpretazione = Paragraph("<b>Interpretazione</b><br/>" + self.interpretazione_taf, styDescrizione)
        except:
            pass

        # 14 row
        corredo = Paragraph("<b>CORREDO</b><br/>", styNormal)

        # 15 row
        corredo_presente = Paragraph("<b>Presenza</b><br/>" + self.corredo_presenza, styDescrizione)

        # 16 row
        corredo_descrizione = Paragraph("<b>Descrizione</b><br/>" + self.corredo_descrizione, styDescrizione)

        # 17 row
        corredo_tipo = ''
        if len(self.corredo_tipo) > 0:
            for i in eval(self.corredo_tipo):
                if corredo_tipo == '':
                    try:
                        corredo_tipo += ("Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (
                        str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass
                else:
                    try:
                        corredo_tipo += ("<br/>Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (
                        str(i[0]), str(i[1]), str(i[2]))
                    except:
                        pass

        corredo_tipo_txt = Paragraph("<b>Singoli oggetti di corredo</b><br/>" + corredo_tipo, styNormal)

        # 18 row
        misure_tafonomia = ''
        if len(self.misure_tafonomia) > 0:
            for i in eval(self.misure_tafonomia):
                if misure_tafonomia == '':
                    try:
                        misure_tafonomia += ("%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
                    except:
                        pass
                else:
                    try:
                        misure_tafonomia += ("<br/>%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
                    except:
                        pass

        misure_tafonomia_txt = Paragraph("<b>Misurazioni</b><br/>" + misure_tafonomia, styNormal)

        # 19 row
        quote_tafonomia = Paragraph("<b>QUOTE INDIVIDUO E STRUTTURA</b><br/>", styNormal)

        # 20 row
        quota_min_ind = Paragraph("<b>Quota min individuo</b><br/>" + str(self.quota_min_ind), styNormal)
        quota_max_ind = Paragraph("<b>Quota max individuo</b><br/>" + str(self.quota_max_ind), styNormal)
        quota_min_strutt = Paragraph("<b>Quota min struttura</b><br/>" + str(self.quota_min_strutt), styNormal)
        quota_max_strutt = Paragraph("<b>Quota max struttura</b><br/>" + str(self.quota_max_strutt), styNormal)

        # schema
        cell_schema = [  # 00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [intestazione, '01', '02', '03', '04', '05', '06', logo, '08', '09'],  # 0 row  ok
            [sito, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 1 row ok
            [sigla_struttura, '01', '02', '03', '04', nr_individuo, '06', '07', nr_scheda, '09'],  # 1 row ok
            [periodizzazione, '01', '02', '03', '04', '07', '06', '07', '08', '09'],  # 2 row ok
            [periodo_iniziale, '01', '02', fase_iniziale, '04', periodo_finale, '06', fase_finale, '08', '09'],
            # 3 row ok
            [datazione_estesa, '01', '02', '03', '04', '07', '06', '07', '08', '09'],  # 4 row ok
            [elementi_strutturali, '01', '02', '03', '04', '07', '06', '07', '08', '09'],  # 5 row ok
            [tipo_contenitore_resti, '01', '02', tipo_copertura, '04', segnacoli, '06', canale_libatorio, '08'],
            # 6 row ok
            [dati_deposizionali, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 7 row ok
            [rito, '01', '02', orientamento_asse, '04', orientamento_azimut, '06', posizione_cranio, '08', '09'],
            # 8 row ok
            [posizione_scheletro, '01', lunghezza_scheletro, '03', posizione_arti_superiori, '05', '06',
             posizione_arti_inferiori, '08', '09'],  # 9 row ok
            [dati_postdeposizionali, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 10 row ok
            [stato_conservazione, '01', '02', disturbato, '04', completo, '06', in_connessione, '08'],  # 11 row ok
            [caratteristiche_tafonomiche_txt, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 12 row ok
            [descrizione, '01', '02', '03', '04', interpretazione, '06', '07', '08', '09'],  # 13 row ok
            [corredo, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 14 row ok
            [corredo_presente, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 15 ow
            [corredo_descrizione, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 16 row
            [corredo_tipo_txt, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 17 row
            [misure_tafonomia_txt, '01', '02', '03', '04', '05', '06', '07', '08', '09'],  # 18 row
            [quote_tafonomia, '01', '02', '03', '04', '07', '06', '07', '08', '09'],  # 19 row ok
            [quota_min_ind, '01', '02', quota_max_ind, '04', quota_min_strutt, '06', quota_max_strutt, '08', '09']
            # 20 row ok
        ]

        # table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # 0 row
            ('SPAN', (0, 0), (6, 0)),  # intestazione
            ('SPAN', (7, 0), (9, 0)),  # intestazione

            # 1 row
            ('SPAN', (0, 1), (9, 1)),  # sito

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

            # 2 row
            ('SPAN', (0, 3), (9, 3)),  # Periodizzazione

            # 3 row
            ('SPAN', (0, 4), (2, 4)),  #
            ('SPAN', (3, 4), (4, 4)),  #
            ('SPAN', (5, 4), (6, 4)),  #
            ('SPAN', (7, 4), (9, 4)),  #

            # 4 row
            ('SPAN', (0, 5), (9, 5)),  # datazione estesa
            ##################################
            # 5 row
            ('SPAN', (0, 6), (9, 6)),  # Elementi strutturali

            # 6 row
            ('SPAN', (0, 7), (2, 7)),  #
            ('SPAN', (3, 7), (4, 7)),  #
            ('SPAN', (5, 7), (6, 7)),  #
            ('SPAN', (7, 7), (9, 7)),  #

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

            # 8 row
            ('SPAN', (0, 9), (2, 9)),  #
            ('SPAN', (3, 9), (4, 9)),  #
            ('SPAN', (5, 9), (6, 9)),  #
            ('SPAN', (7, 9), (9, 9)),  #

            # 9 row
            ('SPAN', (0, 10), (1, 10)),  #
            ('SPAN', (2, 10), (3, 10)),  #
            ('SPAN', (4, 10), (6, 10)),  #
            ('SPAN', (7, 10), (9, 10)),  #

            # 10 row
            ('SPAN', (0, 11), (9, 11)),  #

            # 11 row
            ('SPAN', (0, 12), (2, 12)),  #
            ('SPAN', (3, 12), (4, 12)),  #
            ('SPAN', (5, 12), (6, 12)),  #
            ('SPAN', (7, 12), (9, 12)),  #

            # 12 row
            ('SPAN', (0, 13), (9, 13)),  #

            # 13 row
            ('SPAN', (0, 14), (4, 14)),  #
            ('SPAN', (5, 14), (9, 14)),  #

            # 14 row
            ('SPAN', (0, 15), (9, 15)),  #

            # 15 row
            ('SPAN', (0, 16), (9, 16)),  #

            # 16 row
            ('SPAN', (0, 17), (9, 17)),

            # 17 row
            ('SPAN', (0, 18), (9, 18)),  #

            # 18 row
            ('SPAN', (0, 19), (9, 19)),  #

            ('SPAN', (0, 20), (9, 20)),  # Periodizzazione

            # 3 row
            ('SPAN', (0, 21), (2, 21)),  #
            ('SPAN', (3, 21), (4, 21)),  #
            ('SPAN', (5, 21), (6, 21)),  #
            ('SPAN', (7, 21), (9, 21)),  #

            ('VALIGN', (0, 0), (-1, -1), 'TOP')

        ]

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

        return t
示例#17
0
    def __call__(self,
                 filename,
                 manuscript="",
                 journal="",
                 author=[],
                 publisher=""):
        """Generate the Retain CC agreement."""

        # check the parameters
        while len(author) < 4:
            author.append("")

        doc = getDocument(filename)

        Story = []

        # Section 1
        Story.append(
            Paragraph(
                """<seqreset id="main" /><seq id="main">. THIS ADDENDUM hereby modifies and supplements
            the attached Publication Agreement concerning the following
            Article:""", styles['outer_style']))

        journal_info_table = Table([
            [fillInRow(manuscript, "(manuscript title)", width=inch * 5)],
            [fillInRow(journal, "(journal name)", width=inch * 5)],
        ], )
        journal_info_table.hAlign = 'LEFT'
        Story.append(journal_info_table)

        # Section 2
        Story.append(
            Paragraph(
                """<seq id="main">. The parties to the Publication Agreement as
            modified and supplemented by this Addendum are:""",
                styles['outer_style']))

        journal_info_table = Table(
            [
                [fillInRow(
                    author[0],
                    "(corresponding author)",
                ), "", ""],
                [fillInRow(author[1], ""), "", ""],
                [fillInRow(author[2], ""), "", ""],
                [
                    fillInRow(
                        author[3],
                        """(Individually or, if more than one author, collectively, Author)"""
                    ), "",
                    fillInRow(publisher, "(Publisher")
                ],
            ],
            colWidths=[inch * 3, inch * 0.25, inch * 3],
        )
        journal_info_table.hAlign = 'LEFT'
        Story.append(journal_info_table)

        # Section 3
        Story.append(
            Paragraph(
                """<seq id="main">. This Addendum and the Publication Agreement, 
taken together, allocate all rights under copyright with respect to all 
versions of the Article.  The parties agree that wherever there is any 
conflict between this Addendum and the Publication Agreement, the provisions 
of this Addendum are paramount and the Publication Agreement shall be construed 
accordingly.""", styles['outer_style']))

        # Section 4
        Story.append(
            Paragraph(
                """<seq id="main">. <b>Author's Retention of Rights. </b>  
Notwithstanding any terms in the Publication Agreement to the contrary, 
AUTHOR and PUBLISHER agree that in addition to any rights under copyright 
retained by Author in the Publication Agreement, Author retains: (i) the 
rights to reproduce, to distribute, to publicly perform, and to publicly 
display the Article in any medium for non-commercial purposes; (ii) the right 
to prepare derivative works from the Article; and (iii) the right to authorize
 others to make any non-commercial use of the Article so long as Author
 receives credit as author and the journal in which the Article has been 
published is cited as the source of first publication of the Article.  For 
example, Author may make and distribute copies in the course of teaching and 
research and may post the Article on personal or institutional Web sites and 
in other open-access digital repositories.""", styles['outer_style']))

        # Section 5
        Story.append(
            Paragraph(
                """<seq id="main">. <b>Publisher's Additional Commitments.</b> 
Publisher agrees to provide to Author within 14 days of first publication 
and at no charge an electronic copy of the published Article in a format, 
such as the Portable Document Format (.pdf), that preserves final page 
layout, formatting, and content. No technical restriction, such as security 
settings, will be imposed to prevent copying or printing of the document.""",
                styles['outer_style']))

        # Section 6
        Story.append(
            Paragraph(
                """<seq id="main">. <b>Acknowledgment of Prior License Grants. </b>
            In addition, where applicable and without limiting the retention
            of rights above, Publisher acknowledges that Author's assignment
            of copyright or Author's grant of exclusive rights in the
            Publication Agreement is subject to Author's prior grant of a
            non-exclusive copyright license to Author's employing institution
            and/or to a funding entity that financially supported the research
            reflected in the Article as part of an agreement between Author
            or Author's employing institution and such funding entity, such as
            an agency of the United States government.""",
                styles['outer_style']))

        # Section 6
        Story.append(
            Paragraph(
                """<seq id="main">. For record keeping purposes, Author requests
            that Publisher sign a copy of this Addendum and return it to Author.
            However, if Publisher publishes the Article in the journal or in any
            other form without signing a copy of this Addendum, such publication
            manifests Publisher's assent to the terms of this Addendum.""",
                styles['outer_style']))

        # Signature
        journal_info_table = Table(
            [["AUTHOR", " ", "PUBLISHER"],
             [
                 fillInRow("",
                           "(corresponding author on behalf of all authors)"),
                 "",
                 fillInRow("", "")
             ], [fillInRow("", "Date"), "",
                 fillInRow("", "Date")]],
            colWidths=[inch * 3, inch * .25, inch * 3],
        )

        journal_info_table.hAlign = 'LEFT'
        Story.append(journal_info_table)

        # Disclaimer
        Story.append(Paragraph(Disclaimer, styles['disclaimer']))

        # SPARC box
        Story.append(
            BoxedText([
                [
                    Paragraph(
                        """SPARC (the Scholarly Publishing and Academic Resources Coalition) and the Association of Research Libraries (ARL) are not parties to this Addendum or to the Publication Agreement. SPARC and ARL make no warranty whatsoever in connection with the Article. SPARC and ARL will not be liable to Author or Publisher on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection with this Addendum or the Publication Agreement.""",
                        styles['boxed_paragraph'])
                ],
                [
                    Paragraph(
                        """SPARC and ARL make no warranties regarding the information provided in this Addendum and disclaims liability for damages resulting from the use of this Addendum. This Addendum is provided on an "as-is" basis. No legal services are provided or intended to be provided in connection with this Addendum.""",
                        styles['boxed_paragraph'])
                ],
            ]))

        agreement = "%s %s" % (self.NAME, self.VERSION)
        doc.build(Story,
                  onFirstPage=lambda x, y: sparcPageInfo(agreement, x, y),
                  onLaterPages=lambda x, y: sparcPageInfo(agreement, x, y))
    def build_index_Tafonomia(self, records, sito):

        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

        home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
        logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')

        logo = Image(logo_path)
        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        logo.hAlign = "LEFT"

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.fontSize = 8
        styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        ###################### ELENCO SCHEDE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(Paragraph("<b>ELENCO SCHEDE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 80, 80, 80, 100, 60, 50, 60, 60, 60, 60, 150]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        # lst.append(Spacer(0,2))

        filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_tafonomia.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex)

        f.close()

        ###################### ELENCO SCHEDE STRUTTURE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(
            Paragraph("<b>ELENCO SCHEDE STRUTTURE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data),
                      styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_II_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 50, 40, 100, 60, 50, 50, 60, 60, 60, 80]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        # lst.append(Spacer(0,2))

        filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_strutture_tafonomia.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex)

        f.close()
    def fill_frames(self, canvas):
          
        top_stats = [
            [
                Paragraph("<b>AC:</b> {}<br/><b>Speed:</b> {}".format(self.armor_class,self.speed), self.fonts.paragraph_styles["text"]),
                Paragraph("<b>HP:</b> {}".format(self.max_hit_points), self.fonts.paragraph_styles["text"]),
            ]
        ]
        ts = TableStyle([
            ("BOTTOMPADDING", (0, 0), (-1, -1), 0),
            ("TOPPADDING", (0, 0), (-1, -1), 0),
            ("LEFTPADDING", (0, 0), (-1, -1), 0),
            ("RIGHTPADDING", (0, 0), (-1, -1), 0),
            ("VALIGN",  (0, 0), (-1, -1), "TOP"),
        ])
        t = Table(top_stats, style=ts, spaceBefore=1*mm)
        self.elements.append(t)


        # Modifiers
        abilities = ["STR", "DEX", "CON", "INT", "WIS", "CHA"]
        modifiers = [self.strength, self.dexterity, self.constitution,
                self.intelligence, self.wisdom, self.charisma]
        modifier_table_data = [
            [Paragraph(a, self.fonts.paragraph_styles["modifier_title"])
                for a in abilities],
            [Paragraph(m, self.fonts.paragraph_styles["modifier"])
                for m in modifiers]
        ]

        t = Table(modifier_table_data, [self.BASE_WIDTH/(len(abilities)+1)]*5, style=ts,
                  spaceBefore=1*mm)
        self.elements.append(t)

        # Divider 1
        line_width = self.BASE_WIDTH - self.BORDER_BACK[Border.LEFT]
        self.elements.append(LineDivider(width=line_width,
                                         xoffset=-self.TEXT_MARGIN,
                                         fill_color=self.BORDER_COLOR))

        # Attributes
        # TODO: Handle list attributes
        text = ""
        for heading, body in (self.attributes or {}).items():
            text += "<b>{}:</b> {}<br/>".format(heading, body)
        self.elements.append(Paragraph(text, self.fonts.paragraph_styles["text"]))

        # Abilities
        for heading, body in (self.abilities or {}).items():
            paragraph = Paragraph("<i>{}:</i> {}".format(heading, body), self.fonts.paragraph_styles["text"])
            self.elements.append(paragraph)

        # Divider 2
        self.elements.append(LineDivider(width=line_width,
                                         xoffset=-self.TEXT_MARGIN,
                                         fill_color=self.BORDER_COLOR))

        # Actions
        title = Paragraph("ACTIONS", self.fonts.paragraph_styles["action_title"])
        first_action = True
        for heading, body in (self.actions or {}).items():
            paragraph = Paragraph("<i><b>{}:</b></i> {}".format(heading, body), self.fonts.paragraph_styles["text"])
            if first_action:
                element = KeepTogether([title, paragraph])
                first_action=False
            else:
                element = paragraph
            self.elements.append(element)

        if self.reactions is not None:
            # Divider 3
            self.elements.append(LineDivider(width=line_width,
                                            xoffset=-self.TEXT_MARGIN,
                                            fill_color=self.BORDER_COLOR))

            title = Paragraph("REACTIONS", self.fonts.paragraph_styles["action_title"])
            first_reaction = True
            for heading, body in (self.reactions or {}).items():
                paragraph = Paragraph("<i><b>{}:</b></i> {}".format(heading, body), self.fonts.paragraph_styles["text"])
                if first_reaction:
                    element = KeepTogether([title, paragraph])
                    first_reaction=False
                else:
                    element = paragraph
                self.elements.append(element)
示例#20
0
def _writeComponentEntryPointToPDF(section, pdf, doc):
    for component in section:
        componentSection = []
        name = component["COMPONENT/ENTRY POINT"]
        componentSection.append(
            Paragraph("%s : %s" % ("COMPONENT/ENTRY POINT", name),
                      STYLES['Heading3']))
        if 'COMPONENT DESCRIPTION' in component:
            # TODO: Each line should be its own Paragraph
            description = component["COMPONENT DESCRIPTION"]
            if type(description) is list:
                description = " ".join(description)
            componentSection.append(
                _convertIndividualFieldValuePDF('COMPONENT DESCRIPTION',
                                                description, True))
            componentSection.append(Spacer(1, 20))
        if 'VARIABLES' in component:
            variables = component["VARIABLES"]
            table = []
            table.append(
                generatePDFTableHeader(
                    ["VARIABLES", "TYPE", "VARIABLES DESCRIPTION"]))
            for variable in variables:
                if type(variable) is dict:
                    row = []
                    _variables = variable['VARIABLES']
                    if type(_variables) is list:
                        _variables = _variables[0]
                        if "-" in _variables:
                            # TODO: This is a workaround for an error in original
                            # file, see ICR-639.
                            variable['VARIABLES'] = _variables.split("-")[0]
                            variable[
                                'VARIABLES DESCRIPTION'] = _variables.split(
                                    "-")[1]
                        else:
                            # TODO: ICR-5317 VARIABLES are not
                            # parsed correctly. Skip them for now.
                            variable['VARIABLES'] = ""
                    row.append(
                        _convertIndividualFieldValuePDF(
                            'VARIABLES', variable['VARIABLES'], False))
                    if 'TYPE' in variable:
                        if type(variable['TYPE']) is list:
                            # TODO: ICR-6551 VARIABLES are not
                            # parsed correctly. Skip them for now.
                            variable['TYPE'] = ""
                        row.append(
                            _convertIndividualFieldValuePDF(
                                'TYPE', variable['TYPE'], False, False))
                    else:
                        row.append(Paragraph("", STYLES['Normal']))
                    if 'VARIABLES DESCRIPTION' in variable:
                        description = variable['VARIABLES DESCRIPTION']
                        if type(description) is list:
                            description = " ".join(description)
                            if len(description) > 1000:
                                # TODO: Skipping long descriptions for now
                                # See ICR-2916, ICR-3486, etc.
                                description = ""
                        row.append(
                            _convertIndividualFieldValuePDF(
                                'VARIABLES DESCRIPTION', description, False,
                                False))
                    else:
                        row.append(Paragraph("", STYLES['Normal']))
                    table.append(row)
                else:
                    # TODO: Parsing error! See ICR-28
                    pass
            columns = 10
            columnWidth = doc.width / columns
            t = Table(
                table,
                colWidths=[columnWidth * 2, columnWidth, columnWidth * 7])
            t.setStyle(
                TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))
            componentSection.append(t)
        pdf.append(KeepTogether(componentSection))
示例#21
0
def render_workout_day(day,
                       nr_of_weeks=7,
                       images=False,
                       comments=False,
                       only_table=False):
    '''
    Render a table with reportlab with the contents of the training day

    :param day: a workout day object
    :param nr_of_weeks: the numbrer of weeks to render, default is 7
    :param images: boolean indicating whether to also draw exercise images
           in the PDF (actually only the main image)
    :param comments: boolean indicathing whether the exercise comments will
           be rendered as well
    :param only_table: boolean indicating whether to draw a table with space
           for weight logs or just a list of the exercises
    '''

    # If rendering only the table, reset the nr of weeks, since these columns
    # will not be rendered anyway.
    if only_table:
        nr_of_weeks = 0

    data = []

    # Init some counters and markers, this will be used after the iteration to
    # set different borders and colours
    day_markers = []
    group_exercise_marker = {}

    # Background colour for days
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(
        int('73', 16) / 255.0,
        int('8a', 16) / 255.0,
        int('5f', 16) / 255.0)

    set_count = 1
    day_markers.append(len(data))

    p = Paragraph(
        u'<para align="center">%(days)s: %(description)s</para>' % {
            'days': day['days_of_week']['text'],
            'description': day['obj'].description
        }, styleSheet["Bold"])

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
    data.append([_('Nr.'), _('Exercise'), _('Reps')] +
                [_('Weight')] * nr_of_weeks)

    # Sets
    exercise_start = len(data)
    for set in day['set_list']:
        group_exercise_marker[set['obj'].id] = {
            'start': len(data),
            'end': len(data)
        }

        # Exercises
        for exercise in set['exercise_list']:
            group_exercise_marker[set['obj'].id]['end'] = len(data)

            # Process the settings
            if exercise['has_weight']:
                setting_out = []
                for i in exercise['setting_text'].split(u'–'):
                    setting_out.append(
                        Paragraph(i, styleSheet["Small"], bulletText=''))
            else:
                setting_out = Paragraph(exercise['setting_text'],
                                        styleSheet["Small"])

            # Collect a list of the exercise comments
            item_list = [Paragraph('', styleSheet["Small"])]
            if comments:
                item_list = [
                    ListItem(Paragraph(i,
                                       style=styleSheet["ExerciseComments"]))
                    for i in exercise['comment_list']
                ]

            # Add the exercise's main image
            image = Paragraph('', styleSheet["Small"])
            if images:
                if exercise['obj'].main_image:

                    # Make the images somewhat larger when printing only
                    # the workout and not also the columns for weight logs
                    if only_table:
                        image_size = 2
                    else:
                        image_size = 1.5

                    image = Image(exercise['obj'].main_image.image)
                    image.drawHeight = image_size * cm *\
                        image.drawHeight / image.drawWidth
                    image.drawWidth = image_size * cm

            # Put the name and images and comments together
            exercise_content = [
                Paragraph(exercise['obj'].name, styleSheet["Small"]), image,
                ListFlowable(item_list,
                             bulletType='bullet',
                             leftIndent=5,
                             spaceBefore=7,
                             bulletOffsetY=-3,
                             bulletFontSize=3,
                             start='square')
            ]

            data.append([set_count, exercise_content, setting_out] +
                        [''] * nr_of_weeks)
        set_count += 1

    table_style = [
        ('FONT', (0, 0), (-1, -1), 'OpenSans'),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 2),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 3),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

        # Header
        ('BACKGROUND', (0, 0), (-1, 0), header_colour),
        ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
        ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
        ('SPAN', (0, 0), (-1, 0)),

        # Cell with 'date'
        ('SPAN', (0, 1), (2, 1)),
        ('ALIGN', (0, 1), (2, 1), 'RIGHT')
    ]

    # Combine the cells for exercises on the same superset
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(
            ('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the
    # end of the data list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(
                ('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        if only_table:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 8 * cm  # Exercise
            t._argW[2] = 3.5 * cm  # Repetitions
        else:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 4 * cm  # Exercise
            t._argW[2] = 3 * cm  # Repetitions

    return KeepTogether(t)
示例#22
0
def info_zona_productor_pdf(request, pk):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "info-de-Productor.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    #response['Content-Disposition'] = 'filename="archivo.pdf"' 
    buff = BytesIO()

    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    styles = getSampleStyleSheet()
    p=  Productor.objects.get(pk=pk, habilitado=True)
    zonas = Productor.zona.contar_zonas(pk=pk)
    style_C= ParagraphStyle('Normal')
    style_C.alignment= TA_RIGHT
    style_C.fontSize= 14
    style_C.textColor= 'black'

    lista=[]
    lista.append(logo_pdf())
    fecha= Paragraph('<b><i>Fecha: %s/%s/%s</i></b>'%(tiempo.day,tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0,25))
    
    lista.append(fecha)
    lista.append(Spacer(0,30))

    lista.append(Paragraph("<font><b>CODIGO:</b></font> %s"%p.codigo_en_sistema().upper(), style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font ><b>PROOVEDOR:</b></font> %s"%p.codigo_en_sistema().upper(), style_C))
    lista.append(Spacer(0,10))
    
    lista.append(Paragraph("<font ><b>ASIGNADO:</b></font> %s"%p.nombre_o_razon_social.upper(), style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font><b>TOTAL DE ZONAS:</b></font> %s"%zonas['CantZonas'], style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font><b>HECTAREAS:</b></font> %s Hect."%zonas['CantHectareas'], style_C))
    #*****************************
    lista.append(Spacer(0,20))
    style= ParagraphStyle('Heading1')
    style.textColor= 'black'
    style.alignment= TA_CENTER
    style.fontSize= 18
    style.spaceAfter=15
    style.spaceBefore= 50
    style.spaceAfter=5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName='Helvetica'
    lista.append(Paragraph("<b>ZONAS ASIGANADAS</b>".upper(), style))
    lista.append(Spacer(0,10))

    #****************************
    style_table= ParagraphStyle('Default')

    #style_table.textColor= 'black'
    style_table.alignment= TA_CENTER
    style_table.fontSize= 10
    style_table.spaceAfter=15
    style_table.spaceBefore= 0
    style_table.spaceAfter=0
    style_table.leading = 20 # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName='Times-Roman'
   
    style_table.bulletAnchor= 'start',
    
    cont= 0
    array=[]
    headings = ['N','NOMBRE', 'ESTADO', 'MUNICIPIO', 'EXTENCION']
    for zona in zonas['zonas']:
        cont+=1
        array.append([Paragraph(str(cont), style_table),
        Paragraph(zona.zona, style_table),
        Paragraph(zona.estado, style_table),
        Paragraph(zona.municipio, style_table),
        Paragraph('%s Hect.'%zona.hectareas, style_table)])

    t = Table([headings] + array)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)), colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7

        ]
    ))
    lista.append(t)
    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#23
0
	def cabezera(self,c,wReal,hReal,obj_move,titulo):

		c.setFont("Calibri-Bold", 10)
		c.setFillColor(black)
		c.drawCentredString((wReal/2)+20,hReal, self.env["res.company"].search([])[0].name.upper())
		c.drawCentredString((wReal/2)+20,hReal-12, "ASIENTO CONTABLE: "+ obj_move.name + " - " + obj_move.journal_id.name )

		c.setFont("Calibri-Bold", 8)

		c.drawString( 10,hReal-48, 'Empresa:')
		c.drawString( 400,hReal-36, 'Referencia:')
		c.drawString( 400,hReal-48, 'Fecha:')


		c.setFont("Calibri", 8)
		c.drawString( 10+90,hReal-48, obj_move.partner_id.name if obj_move.partner_id.name else '')
		c.drawString( 400+60,hReal-36, obj_move.ref if obj_move.ref else '')
		c.drawString( 400+60,hReal-48, obj_move.date if obj_move.date else '')


		style = getSampleStyleSheet()["Normal"]
		style.leading = 8
		style.alignment= 1
		paragraph1 = Paragraph(
		    "<font size=8><b>Nombre</b></font>",
		    style
		)
		paragraph2 = Paragraph(
		    "<font size=8><b>Empresa</b></font>",
		    style
		)
		paragraph3 = Paragraph(
		    "<font size=8><b>Comprobante</b></font>",
		    style
		)
		paragraph4 = Paragraph(
		    "<font size=8><b>Cuenta</b></font>",
		    style
		)
		paragraph5 = Paragraph(
		    "<font size=8><b>Fecha V.</b></font>",
		    style
		)
		paragraph6 = Paragraph(
		    "<font size=8><b>Debe</b></font>",
		    style
		)
		paragraph7 = Paragraph(
		    "<font size=8><b>Haber</b></font>",
		    style
		)
		paragraph8 = Paragraph(
		    "<font size=8><b>Cta. Analítica</b></font>",
		    style
		)
		paragraph9 = Paragraph(
		    "<font size=8><b>Importe Divisa</b></font>",
		    style
		)
		paragraph10 = Paragraph(
		    "<font size=8><b>Divisa</b></font>",
		    style
		)
		paragraph11 = Paragraph(
		    "<font size=8><b>TC SUNAT</b></font>",
		    style
		)
		paragraph12 = Paragraph(
		    "<font size=8><b>TD</b></font>",
		    style
		)

		paragraph13 = Paragraph(
		    "<font size=8><b>Cuenta</b></font>",
		    style
		)
		paragraph14 = Paragraph(
		    "<font size=8><b>Descripción</b></font>",
		    style
		)
		paragraph15 = Paragraph(
		    "<font size=8><b>Debe</b></font>",
		    style
		)
		paragraph16 = Paragraph(
		    "<font size=8><b>Haber</b></font>",
		    style
		)

		if titulo == 1:
			data= [[ paragraph1 , paragraph2 , paragraph3 , paragraph4, paragraph5 , paragraph6 , paragraph7 ,paragraph12]]
			t=Table(data,colWidths=( 80,120, 80, 90, 50,60,60,25), rowHeights=(9))
			t.setStyle(TableStyle([
				('GRID',(0,0),(-1,-1), 1, colors.black),
				('ALIGN',(0,0),(-1,-1),'LEFT'),
				('VALIGN',(0,0),(-1,-1),'MIDDLE'),
				('TEXTFONT', (0, 0), (-1, -1), 'Calibri-Bold'),
				('FONTSIZE',(0,0),(-1,-1),4),
				('BACKGROUND', (0, 0), (-1, -1), colors.gray)
			]))
		elif titulo == 2:
			data= [[ paragraph8 ,paragraph9,paragraph10,paragraph11]]
			t=Table(data,colWidths=(100,100,50,60), rowHeights=(9))
			t.setStyle(TableStyle([
				('GRID',(0,0),(-1,-1), 1, colors.black),
				('ALIGN',(0,0),(-1,-1),'LEFT'),
				('VALIGN',(0,0),(-1,-1),'MIDDLE'),
				('TEXTFONT', (0, 0), (-1, -1), 'Calibri-Bold'),
				('FONTSIZE',(0,0),(-1,-1),4),
				('BACKGROUND', (0, 0), (-1, -1), colors.gray)
			]))
		else:
			data= [[ paragraph13 ,paragraph14,paragraph15,paragraph16]]
			t=Table(data,colWidths=(70,130,60,60), rowHeights=(9))
			t.setStyle(TableStyle([
				('GRID',(0,0),(-1,-1), 1, colors.black),
				('ALIGN',(0,0),(-1,-1),'LEFT'),
				('VALIGN',(0,0),(-1,-1),'MIDDLE'),
				('TEXTFONT', (0, 0), (-1, -1), 'Calibri-Bold'),
				('FONTSIZE',(0,0),(-1,-1),4),
				('BACKGROUND', (0, 0), (-1, -1), colors.gray)
			]))


		t.wrapOn(c,20,500)
		t.drawOn(c,20,hReal-85)
示例#24
0
def info_productor_pdf(request, pk):
   
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "info-de-Productor.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    print inch
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    #response['Content-Disposition'] = 'filename="archivo.pdf"' 

    buff = BytesIO()


    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            showBoundary=0,
                            title='Info-Productores',
                            onPage='doNothing',
                            onPageEnd='doNothing'
                            )

    lista = []
    styles = getSampleStyleSheet()
    #menbrete ************************
    lista.append(logo_pdf())
    fecha= Paragraph('<b><i>Fecha: %s/%s/%s</i></b>'%(tiempo.day,tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0,25))
    lista.append(fecha)
    lista.append(Spacer(0,20))
    style= ParagraphStyle('Heading1')
    style.textColor= 'black'
    style.alignment= TA_CENTER
    style.fontSize= 16
    style.spaceAfter=15
    style.spaceBefore= 15
    style.spaceAfter=5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    header = Paragraph("<b>Informacion del Proovedor</b>".upper(), style)

    #******Modelos********
    lista.append(header)
    lista.append(Spacer(0,25))

    p=  Productor.objects.get(pk=pk, habilitado=True, null=False)
    zona = Productor.zona.contar_zonas(pk=pk, null=False)

    #******Modelos********
   
    #
    style_C= ParagraphStyle('Normal')
    style_C.alignment= TA_RIGHT
    style_C.fontSize= 14
    style_C.textColor= 'black'


    style_N= ParagraphStyle('Normal')
    style_N.alignment= TA_LEFT
    style_N.fontSize= 12
    style_N.textColor= 'black'

    style_table= ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_table.fontSize= 10
    style_table.spaceAfter=15
    style_table.spaceBefore= 0
    style_table.spaceAfter=0
    style_table.leading = 20 # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName='Times-Roman'
   
    style_table.bulletAnchor= 'start',
    codigo_en_sistema = Paragraph('<font ><b>CODIGO EN SISTEMA:</b> %s</font>'%p.codigo_en_sistema(),style_C)
    lista.append(codigo_en_sistema)
    lista.append(Spacer(0, 5))
    lista.append(Paragraph('<b>NUMERO DE ZONAS:</b>%s'%zona['CantZonas'], style_N))
    lista.append(Spacer(0, 10))

    lista.append(Paragraph('<b> CANTIDAD DE HECTAREAS:</b> %s Hect.'%zona['CantHectareas'], style_N))
    lista.append(Spacer(0, 20))
    array_datos=[]

    lista.append(Paragraph('<font><b>INFORMACION BASICA</b></font>', style_N))
    lista.append(Spacer(0, 20))

    title_datos= ('Nombre o Razon Social', 'CI/RIF', 'Domicilio Fiscal')
    array_datos.append([
    Paragraph(p.nombre_o_razon_social.title(), style_table),
    Paragraph(p.documentoId.title(), style_table),
    Paragraph(p.domicilio_fiscal.title(), style_table)])
    t_datos=Table([title_datos]+ array_datos)
    tupla_tabla=  [
            ('GRID', (0, 1), (len(title_datos), -1), 1, colors.black),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),

            ('LINEBELOW', (1, 0), (-1, 0), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('BACKGROUND', (0, 1), (len(title_datos), len(array_datos)), colors.white)#HexColor(0x979494)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7

        ]
    t_datos.setStyle(TableStyle(tupla_tabla))#414141
    lista.append(t_datos)
    array_referencia=[]
    title_referencia= ('TELEFONO', 'CELULAR', 'E-MAIL')
    array_referencia.append([
    Paragraph(p.telefono, style_table),
    Paragraph(p.celular, style_table),
    Paragraph(p.e_mail, style_table)])
    t_referencia=Table([title_referencia]+ array_referencia)
    t_referencia.setStyle(TableStyle(tupla_tabla))
    lista.append(t_referencia)

    array_banco= []
    encabesado_banco=('', 'CUENTA PRINCIPAL', '')
    title_banco= ('CUENTA','BANCO', 'TIPO')
    array_banco.append([ Paragraph(p.cuenta_bancaria, style_table),
    Paragraph(p.banco.nombre.title(), style_table),
    Paragraph(p.tipo_cuenta.nombre.title(), style_table),
   ])
    t_banco=Table([title_banco]+ array_banco)
    t_banco.setStyle(TableStyle(tupla_tabla))
    lista.append(t_banco)

    array_afiliacion=[]
    title_afiliacion= ('FECHA DE AGREGADO', 'REFENCIA', 'OBSERVACION')
    array_afiliacion.append([
    Paragraph('%s/%s/%s'%(p.fecha_agregado.day, p.fecha_agregado.month,p.fecha_agregado.year), style_table),
    Paragraph(p.referencia_folder, style_table),
    Paragraph(p.observacion, style_table)])
    t_afiliacion=Table([title_afiliacion]+ array_afiliacion)
    t_afiliacion.setStyle(TableStyle(tupla_tabla))
    lista.append(t_afiliacion)
 

    
   





    doc.build(lista)#, onFirstPage = myFirstPage, onLaterPages = myLaterPages)#doc.build(story, onFirstPage = myFirstPage, onLaterPages = myLaterPages)

    response.write(buff.getvalue())
    buff.close()
    return response
示例#25
0
def report(request):
    response = HttpResponse(content_type='application/pdf')
    # response['Content-Disposition'] = 'attachement; filename=Archivo.pdf'

    # a = canvas.Canvas()
    # a.drawText("Hola mundo!")
    buffer = BytesIO()

    doc = SimpleDocTemplate("test_report_lab.pdf", pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60,
                            bottomMargin=18)
    # doc.pagesize = landscape(A4)

    elements = []
    styles = getSampleStyleSheet()

    styles = styles["BodyText"]

    description = Paragraph("CENSOS NACIONALES 2017; XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÉGENAS",
                            styles)
    subtitle = Paragraph("LISTADO DE VIVIENDAS DEL ÁREA DE EMPADRONAMIENTO URBANO (A.E.U.)", styles)

    headings = (
    'VIV Nº', 'MANZANA Nº', 'FRENTE Nº', 'DIRECCIÒN DE LA VIVIENDA', 'Apellidos y Nombres del JEFE DEL HOGAR')

    data = [
        ["(1)", "(2)", "(3)", "(4)", "(5)"],
        ["A", "01", "ABCD", "Anthony"],
        ["B", "02", "CDEF", "Brian"],
        ["C", "03", "SDFSDF", "Carlos"],
        ["D", "04", "SDFSDF", "Luis"],
        ["E", "05", "GHJGHJGHJ", "Farfan"],
    ]

    # TODO: Get this line right instead of just copying it from the docs

    alldatas = [[Paragraph(cell, styles) for cell in row] for row in data]

    t = Table([headings] + alldatas)
    t.setStyle(TableStyle(
        [
            ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ('TEXTCOLOR', (1, 1), (-2, -2), colors.red),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
            ('ALIGN', (0, -1), (-1, -1), 'CENTER'),
            ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),
            ('TEXTCOLOR', (0, -1), (-1, -1), colors.green),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]
    ))

    # style = getSampleStyleSheet()
    # t = styles["BodyText"]

    # t.wordWrap = 'CJK'

    # c.drawString(275, 725, 'AMOUNT OWED:')
    # c.drawString(500, 725, "$1,000.00")
    # c.line(378, 723, 580, 723)
    # c.drawString(30, 703, 'RECIBIDO DE:')
    # c.line(120, 700, 580, 700)
    # c.drawString(120, 703, "ANTHONY CARRILLO")
    elements.append(description)
    elements.append(subtitle)
    elements.append(t)
    doc.build(elements)
    # t.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
示例#26
0
def lista_productores_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Listado-de-Proovedores.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    buff = BytesIO()

    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    styles = getSampleStyleSheet()
    lista = []
    lista.append(logo_pdf())
    fecha= Paragraph('<b><i>Fecha: %s/%s/%s</i></b>'%(tiempo.day,tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0,40))
    lista.append(fecha)

    lista.append(Spacer(0,10))
    style= ParagraphStyle('Heading1')
    style.textColor= 'black'
    style.alignment= TA_CENTER
    style.fontSize= 18
    style.spaceAfter=15
    style.spaceBefore= 30
    style.spaceAfter=5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName='Helvetica'
    header = Paragraph("<b>Listado de Proovedores</b>".upper(), style)
    lista.append(header)
    lista.append(Spacer(0,10))

    #************Tabla****************************
    style_table= ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_table.fontSize= 10
    style_table.spaceAfter=15
    style_table.spaceBefore= 0
    style_table.spaceAfter=0
    style_table.leading = 20 # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName='Times-Roman'
   
    style_table.bulletAnchor= 'start',
    cont= 0
    array=[]
    headings = ('N','CODIGO', 'NOMBRE', 'CI/RIF', 'DOMICILIO FISCAL','TELEFONO', 'CELULAR')
    for p in Productor.objects.filter(habilitado=True).order_by('fecha_agregado'):
        cont+=1
        array.append([Paragraph(str(cont), style_table),
        Paragraph(p.codigo_en_sistema(), style_table),
        Paragraph(p.nombre_o_razon_social.title(), style_table),
        Paragraph(p.documentoId.title(), style_table),
        Paragraph(p.domicilio_fiscal.title(), style_table),
        Paragraph(p.telefono, style_table),
        Paragraph(p.celular, style_table)])

    t = Table([headings] + array)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)), colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7

        ]
    ))
    lista.append(t)
    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
def generar_pdf(request, ubigeo, zonal, aeut):
    print "Se va a generar el PDF de Ubigeo: "+ str(ubigeo)+ " de zona: " + str(zonal) + " y AE: "+str(aeut)
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename=" + ubigeo + "001" + str(aeut) + ".pdf"
    # response['Content-Disposition'] = "attachment; filename="+ubigeo+"001"+".pdf"
    pdf_name = "clientes.pdf"
    styles = getSampleStyleSheet()
    stylesTitle = getSampleStyleSheet()
    stylesCabe = getSampleStyleSheet()

    styleTitle = stylesTitle["Normal"]
    styleTitle.alignment = TA_CENTER
    styleBH = styles["Normal"]
    styleBH.alignment = TA_LEFT
    styleCa = stylesCabe["Normal"]
    styleCa.alignment = TA_CENTER

    buff = BytesIO()
    # destino = "Lista/" + str(ubigeo)+"00100"+ str(aeut)+ ".pdf"
    #
    # doc2 = SimpleDocTemplate(destino, pagesize=A4,
    #                          rightMargin=70,
    #                          leftMargin=70,
    #                          topMargin=0.5 *cm,
    #                          bottomMargin=0.5 *cm, )
    doc = SimpleDocTemplate(buff,
                            pagesize=A4,
                            rightMargin=65,
                            leftMargin=65,
                            topMargin=0.5 *cm,
                            bottomMargin=0.5 *cm,
                            )

    h_sub_tile = PS(
        name='Heading1',
        fontSize=10,
        leading=14,
        alignment=TA_CENTER
    )

    h_sub_tile_2 = PS(
        name='Heading1',
        fontSize=11,
        leading=14,
        alignment=TA_CENTER
    )

    h_center = PS(
        name='Heading1',
        fontSize=7,
        leading=8,
        alignment=TA_CENTER
    )

    h1 = PS(
        name='Heading1',
        fontSize=7,
        leading=8
    )

    h11 = PS(
        name='Heading1',
        fontSize=7,
        leading=8,
        alignment=TA_CENTER
    )

    h2 = PS(
        name='Normal',
        fontSize=6,
        leading=16
    )

    h3 = PS(
        name='Normal',
        fontSize=7,
        leading=14,
        alignment=TA_CENTER)

    h4 = PS(
        name='Normal',
        fontSize=6,
        leading=16
    )

    h5 = PS(
        name='Normal',
        fontSize=8,
        leading=16,
        alignment=TA_CENTER
    )

    h_obser = PS(
        name='Normal',
        fontSize=8,
        leading=16
    )

    h_bar = PS(
        name='Normal',
        fontSize=7,
        leading=14,
        alignment=TA_CENTER
    )

    story = []

    distrito = Distrito.objects.get(ubigeo=ubigeo)  # ubigeo

    # vivi = ViviendaUrbana.objects.get(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut)



    # cond_viv = Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut)

    # total = Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut).count()

    # viv_u = ViviendaU.objects.filter(ubigeo=ubigeo)

    rango_equivalencia = [[1, 'A'], [2, 'B'], [3, 'C'], [4, 'D'], [5, 'E'], [6, 'F'], [7, 'G'], [8, 'H'], [9, 'I'],
                          [10, 'J'], [11, 'K'], [12, 'L'], [13, 'M'], [14, 'N'], [15, 'O'], [16, 'P'], [17, 'Q'], [18, 'R'],
                          [19, 'S'], [20, 'T'], [21, 'U'], [22, 'V'], [23, 'W'], [24, 'X'], [25, 'Y'], [26, 'Z']
                          ]


    Z2 = Paragraph("<strong>EMPADRONADOR</strong>", h5)

    Z3 = Paragraph("<strong>Todas las viviendas que estén dentro de los límites de tu A.E.U. deben ser empadronadas. Debes tener<br/>cuidado de no omitir ninguna vivienda</strong>",h5)

    table_empa_cuerp = Table(
        data=[
            [Z2],
            [Z3]
        ],
        colWidths=[18.8 * cm],
        rowHeights=[0.7 * cm, 1.5 * cm],
        style=[
            ('GRID', (0, 0), (0, 0), 1, colors.black),
            ('GRID', (0, 1), (0, 1), 1, colors.black),
            ('ALIGN', (0, 0), (0, 0), 'CENTER')
        ]
    )
    cond =v_ReporteCabViviendasTab.objects.filter(ubigeo=ubigeo, zona=zonal, aeu_final=aeut)
    x = 0

    lista_zonas = []
    for aeu in cond:
        x = x + 1
        y = x

        secc = str(aeu.seccion).zfill(3)
        aeus = str(aeu.aeu_final).zfill(3)
        aeut_conv = str(aeu.aeu_final).zfill(3)

        lista_distritos = []
        lista_distritos.append(ubigeo)
        listin = []
        tam_dis = 1
        for ubigein in range(tam_dis):

            if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein])) == False:
                os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]))

            total_zonas = int(str(Esp_Aeus.objects.filter(ubigeo=lista_distritos[ubigein]).values_list('zona',flat=True).distinct().count()))
            total_zonales = Esp_Aeus.objects.filter(ubigeo=lista_distritos[ubigein]).values_list('zona', flat=True)
            cuchi = list(set(total_zonales))
            lista_zonas.append(total_zonas)

            for zona_t in range(total_zonas):
                #zoner = str(zona_t + 1).zfill(3) + "00"
                listin.append(str(lista_distritos[ubigein]) + ": " + cuchi[zona_t] + "<br/>")
                if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + cuchi[zona_t]) == False:
                    os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + cuchi[zona_t])
                    # destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + zoner+ "\\" + str(ubigeo) + zonal + str(secc)+str(aeut) + ".pdf"
                    #
                    #
                    #
                    # doc2 = SimpleDocTemplate(destino, pagesize=A4,
                    #                                        rightMargin=70,
                    #                                        leftMargin=70,
                    #                                        topMargin=0.5 * cm,
                    #                                        bottomMargin=0.5 * cm, )

        destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(ubigeo) + "\\" + zonal+ "\\" + str(ubigeo) + zonal + str(secc) + str(aeut_conv) + ".pdf"
        doc2 = SimpleDocTemplate(destino, pagesize=A4,
                                          rightMargin=70,
                                          leftMargin=70,
                                          topMargin=0.5 * cm,
                                          bottomMargin=0.5 * cm,)
        # destino =  "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(ubigeo) + zonal + str(secc)+str(aeut) + ".pdf"
        #
        # doc2 = SimpleDocTemplate(destino, pagesize=A4,
        #                          rightMargin=70,
        #                          leftMargin=70,
        #                          topMargin=0.5 * cm,
        #                          bottomMargin=0.5 * cm, )

        p = Paragraph(str(1) + " - " + str(1), h2)
        extra = Paragraph("-", h2)
        p_page = Table(
            data=[
                [extra, p]
            ],
            colWidths=[17 * cm, 2.3 * cm],
            style=[
                ('GRID', (0, 0), (-1, -1), 1, colors.white),
                ('ALIGN', (0, 0), (1, 0), 'RIGHT'),
            ]
        )
        string = str(ubigeo)+zonal+str(secc)+str(aeut)
        st = code39.Extended39(string)
        bar_string = Paragraph(string, h_bar)
        pi = Paragraph("-", h2)
        st_b = st
        table_bar = Table(
            data = [
                [pi, st_b],
                ['', bar_string]
            ],
            colWidths= [13 * cm, 5 * cm],
            style=[
                ('ALIGN', (0, 0), (-1, -1),'CENTER')
            ]
        )
        #story.append(table_bar)
        # zona_temp = aeu.zona[0:3]
        # zona_int = int(aeu.zona[3:])
        # zona_int_eq = ""
        # for el in rango_equivalencia:
        #     if (el[0] == zona_int):
        #         zona_int_eq = el[1]
        # zona_temp = zona_temp + str(zona_int_eq)
        data = [
            ['', '', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4)],
            [Paragraph('<strong>A. UBICACIÓN GEOGRÁFICA</strong>', h11), '', '', '',
             Paragraph('<strong>B. UBICACIÓN CENSAL</strong>', h11), ''],
            [Paragraph('<strong>DEPARTAMENTO</strong>', h1),Paragraph(str(aeu.ccdd), h_center),
             Paragraph(str(aeu.departamento), h1), '',
             Paragraph('<strong>ZONA Nº</strong>', h1),Paragraph(aeu.zona_convert, h_center)],
            [Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(aeu.ccpp, h_center),
             Paragraph(str(aeu.provincia).decode('latin-1'), h1), '', Paragraph(str('<strong>SECCIÓN Nº</strong>'), h1), Paragraph(str(aeu.seccion_convert), h_center)],
            [Paragraph('<strong>DISTRITO</strong>', h1), Paragraph(aeu.ccdi, h_center), Paragraph(aeu.distrito, h1),
             '', Paragraph('<strong>A.E.U. Nº</strong>', h1), Paragraph(aeus, h_center)],
            [Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph(aeu.nomccpp, h1), '', '', '', ''],
            [Paragraph('<strong>CATEGORÍA DEL CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '',
             Paragraph('<strong>TOTAL DE VIVIENDAS<br/>DEL A.E.U.</strong>', h1),Paragraph(str(aeu.cant_viv), h_center)],
        ]
        tables = Table(data, colWidths=[3.7 * cm, 1 * cm, 8.1 * cm, 0.3 * cm, 4.7 * cm, 2 * cm],
                       rowHeights=[0.4 * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.7  * cm])
        tables.setStyle(TableStyle([
            ('TEXTCOLOR', (0, 0), (5, 0), colors.black),
            ('ALIGN', (4, 0), (5, 0), 'RIGHT'),
            ('ALIGN', (1, 2), (1, 4), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 1), (2, 6), 1, colors.black),
            ('GRID', (4, 1), (5, 4), 1, colors.black),
            ('GRID', (-2, -1), (-1, -1), 1, colors.black),
            ('SPAN', (0, 1), (2, 1)),
            ('SPAN', (4, 1), (5, 1)),
            ('SPAN', (1, 5), (2, 5)),
            ('SPAN', (1, 6), (2, 6)),
            ('BACKGROUND', (0, 1), (0, 6), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (0, 1), (2, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (5, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (4, 4), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 6), (4, 6), colors.Color(219.0/255,229.0/255,241.0/255))
        ]))
        t1 = Paragraph("CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA<br/>Y III DE COMUNIDADES INDÍGENAS",h_sub_tile)
        t1_sub = Paragraph("<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO URBANO</strong>", h_sub_tile_2)

        obs_data = [
            [Paragraph(e, h3) for e in ["<strong>Viv Nº</strong>",
                                        "<strong>Mz Nº</strong>",
                                        "<strong>Ord Reg</strong>",
                                        "<strong>Frent Nº</strong>",
                                        "<strong>DIRECCIÓN DE LA VIVIENDA</strong>",
                                        "", "", "", "", "", "", "", "",
                                        "<strong>Nombres y Apellidos del JEFE DEL HOGAR</strong>"]],
            [Paragraph(e, h3) for e in ["", "", "", "",
                                        "<strong>Tipo de Vía</strong>",
                                        "<strong>Nombre de Vía</strong>",
                                        "<strong>Nº de Puerta</strong>",
                                        "<strong>Block</strong>",
                                        "<strong>Mz Nº</strong>",
                                        "<strong>Lote Nº</strong>",
                                        "<strong>Piso Nº</strong>",
                                        "<strong>Int. Nº</strong>",
                                        "<strong>Km. Nº</strong>",
                                        ""]],
            [Paragraph(e, h3) for e in ["<strong>(1)</strong>",
                                        "<strong>(2)</strong>",
                                        "<strong>(3)</strong>",
                                        "<strong>(4)</strong>",
                                        "<strong>(5)</strong>",
                                        "<strong>(6)</strong>",
                                        "<strong>(7)</strong>",
                                        "<strong>(8)</strong>",
                                        "<strong>(9)</strong>",
                                        "<strong>(10)</strong>",
                                        "<strong>(11)</strong>",
                                        "<strong>(12)</strong>",
                                        "<strong>(13)</strong>",
                                        "<strong>(14)</strong>"]],
         ]
        c = Table(obs_data,
                  colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.1 * cm, 1.8 * cm, 2.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm,
                             1 * cm, 0.9 * cm, 0.9 * cm, 4.7 * cm])
        c.setStyle(TableStyle(
            [
                ('GRID', (1, 1), (-2, -2), 1, colors.black),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                # ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTSIZE', (0, 0), (-1, -1), 7),
                ('BACKGROUND', (0, 0), (-1, 0), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (0, 0), (-1, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('SPAN', (4, 0), (12, 0)),
                ('SPAN', (0, 0), (0, 1)),
                ('SPAN', (1, 0), (1, 1)),
                ('SPAN', (2, 0), (2, 1)),
                ('SPAN', (3, 0), (3, 1)),
                ('SPAN', (13, 0), (13, 1)),
                ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                ('BACKGROUND', (0, 0), (13, 2), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            ]
        ))
        # viviendas = ViviendaUrbana.objects.filter(ubigeo=distrito.ubigeo, zona=aeu.zona, aeu_final=aeu.aeu_final).order_by('manzana','id_reg_or')
        # viviendas = ViviendaUrbana.objects.filter(
        #     Q(ubigeo=distrito.ubigeo), Q(zona=aeu.zona), Q(aeu_final=aeu.aeu_final)
        #     # Q(ubigeo='020601'), Q(zona='001'), Q(aeu_final='001')
        # ).order_by('ubigeo', 'zona', 'manzana', 'id_reg_or', 'uso_local')
        # vivi = ViviendaUrbana.objects.get(ubigeo=distrito.ubigeo, zona=aeu.zona,).values('id_reg_or', flat=True).distinct().order_by('manzana')
        # for viv in ViviendaUrbana.objects.values('or_viv_aeu').filter(
        #        Q(ubigeo=distrito.ubigeo), Q(zona= aeu.zona), Q(aeu_final= aeu.aeu_final)
        # ).distinct().order_by('or_viv_aeu'):
        i=0
        equi_pta = [[1, 'PF de:'], [2, 'PG de:'], [3, 'PB de:'], [4, 'PC de:'], [5, 'Frente, pared corrida'], [6, 'Frente sin construir'], [7, 'Otro'], [8, 'Sin Edificación']]
        # Bloque Croquis
        data_croq = [
            ['', '', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4)],
            [Paragraph('<strong>A. UBICACIÓN GEOGRÁFICA</strong>', h1), '', '', '',
             Paragraph('<strong>B. UBICACIÓN CENSAL</strong>', h1), ''],
            [Paragraph('<strong>DEPARTAMENTO</strong>', h1),Paragraph(str(aeu.ccdd), h1),
             Paragraph(str(aeu.departamento), h1), '',
             Paragraph('<strong>ZONA Nº</strong>', h1),Paragraph(aeu.zona_convert, h1)],
            [Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(aeu.ccpp, h1),
             Paragraph(str(aeu.provincia).decode('latin-1'), h1), '', Paragraph(str('<strong>SECCIÓN Nº</strong>'), h1), aeu.seccion_convert],
            [Paragraph('<strong>DISTRITO</strong>', h1), Paragraph(aeu.ccdi, h1), Paragraph(aeu.distrito, h1),
             '', Paragraph('<strong>A.E.U. Nº</strong>', h1), aeu.aeu_final],
            [Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph(aeu.nomccpp, h1), '', '', '', ''],
            [Paragraph('<strong>CATEGORÍA DEL<br/>CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '',
             Paragraph('<strong>TOTAL DE VIVIENDAS DEL A.E.U.</strong>', h1),Paragraph(str(int(aeu.cant_viv)), h1)],
        ]
        tables_croq = Table(data_croq, colWidths=[3.7 * cm, 1 * cm, 8.3 * cm, 0.3 * cm, 4.7 * cm, 1 * cm])
        tables_croq.setStyle(TableStyle([
            ('TEXTCOLOR', (0, 0), (5, 0), colors.black),
            ('ALIGN', (4, 0), (5, 0), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (1, 2), (1, 4), 'CENTER'),
            ('GRID', (0, 1), (2, 6), 1, colors.black),
            ('GRID', (4, 1), (5, 4), 1, colors.black),
            ('GRID', (-2, -1), (-1, -1), 1, colors.black),
            ('SPAN', (0, 1), (2, 1)),
            ('SPAN', (4, 1), (5, 1)),
            ('SPAN', (1, 5), (2, 5)),
            ('SPAN', (1, 6), (2, 6)),
            ('BACKGROUND', (4, 1), (5, 5), colors.white),
            ('BACKGROUND', (0, 1), (-1, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (0, 1), (0, 6), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (4, 4), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 6), (4, 6), colors.Color(219.0/255,229.0/255,241.0/255))
        ]))
        fichero_imagen_inei = 'Reporte/Img/inei.png'
        imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=40)
        P2 = Paragraph('', styleBH)
        fichero_imagen = 'Reporte/Img/escudo.png'
        imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50)
        # t = Table(
        #     data=[
        #         [[imagen_logo, P2], t1, [imagen_logo_inei, P2]],
        #         ['', t1_croq, '']
        #     ],
        #     colWidths=[2 * cm, 14 * cm, 2 * cm],
        #     style=[
        #         ('GRID', (1, 1), (-2, -2), 1, colors.white),
        #         ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
        #     ]
        # )
        t_croq = Table(
            data=[
                [[imagen_logo, P2], t1, [imagen_logo_inei, P2]],
                ['',t1_sub, '']
            ],
            colWidths=[2 * cm, 14 * cm, 2 * cm],
            style=[
                ('GRID', (1, 1), (-2, -2), 1, colors.white),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
            ]
        )
        # story.append(t)
        # story.append(Spacer(0, 1 * mm))
        # story.append(tables)
        # story.append(Spacer(0, 1 * mm))
        fichero_imagen = 'Reporte/Croquis/Zona' + ubigeo + '00100' + '/Croquis' + ubigeo + '00100' + str(aeut) + '.png'

        story.append(t_croq)
        story.append(Spacer(0, 2 * mm))
        story.append(tables)
        story.append(Spacer(0, 3 * mm))
        story.append(c)

        viviendas = v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal), Q(aeu_final=aeut)).order_by('manzana', 'id_reg_or')[0:18]

        toti_viv = int(v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal), Q(aeu_final=aeut)).count())
        for vivienda in viviendas:
            i=i+1
            pep = vivienda.p29_a
            for el in equi_pta:
                if (el[0] == pep):
                    pta_f = el[1]
            jefe_hogar = ""
            if vivienda.p29 == 1 or vivienda.p29 == 3:
                jefe_hogar = vivienda.p32

            elif vivienda.p29 == 5:
                if vivienda.p29_a in (1, 2, 3, 4):
                    jefe_hogar = pta_f + "" + vivienda.p29_p
                elif vivienda.p29_a in (5, 6):
                    jefe_hogar = pta_f
                elif vivienda.p29_a == 7:
                    jefe_hogar = vivienda.p29_o
                elif vivienda.p29_a == 8:
                    jefe_hogar = vivienda.p29_8_o
            elif vivienda.p29 == 2 or vivienda.p29 == 4:
                jefe_hogar = vivienda.p35
            else:
                print "No idea u.u"

            jefe_h = u'{}'.format(jefe_hogar)

            if jefe_h != None and jefe_h.count(' ') > 2 and len(jefe_h) > 26  and len(jefe_h) < 28:
                print "Mayor a 26 caracteres"
                jefe_jug = jefe_h.rsplit(' ', 1)
                jefe_home = jefe_jug[0] + '\n' + jefe_jug[1]
            # elif jefe_h != None and jefe_h!= type(1) and  jefe_h ==type('a') and jefe_h.count(' ') < 1:
            #     print "Entro segunda condicion"
            #
            #     jefe_home = jefe_hogar
            # elif jefe_h != None and jefe_h!= type(1) and  jefe_h ==type('a') and jefe_h.count(' ') == 0:
            #     print "Entro tercera condicion"
            #     # jefe_jug = jefe_h.rsplit(' ', 1)
            #     jefe_home = jefe_hogar
            if jefe_h != None and jefe_h.count(' ') > 2 and len(jefe_h) > 28:
                print "Mayor a 26 caracteres"
                jefe_jug = jefe_h.rsplit(' ', 2)
                jefe_home = jefe_jug[0] + '\n' + jefe_jug[1]+ ' '+ jefe_jug[2]
            elif jefe_h==type(1) or jefe_h==type('a'):
                print "Mayor a 26 caracteres enteero"

                jefe_home = jefe_hogar
            else:
                print "Entro cuarta"
                jefe_home = jefe_hogar
            # Bloque Listado
            if(vivienda.p22_a==None):
                p22_a = ''
            else:
                p22_a = vivienda.p22_a
            if(vivienda.p22_b==None):
                p22_b = ''
            else:
                p22_b = vivienda.p22_b
            if(vivienda.p24==None):
                p24 = ''
            else:
                p24 = vivienda.p24
            if (vivienda.p25 == None):
                p25 = ''
            else:
                p25 = vivienda.p25
            if (vivienda.p26 == None):
                p26 = ''
            else:
                p26 = vivienda.p26

            if vivienda.or_viv_aeu == 0:
                id_reg_or = ''
            else:
                id_reg_or = vivienda.id_reg_or

            p21 = vivienda.p21

            if len(p21) > 13 and p21.count(' ')==1:
                print "mas de 111111"
                jug_p21 = p21.rsplit(' ', 1)

                # firstblank_viviendap21 = (vivienda.p21).index(' ')
                p21 = jug_p21[0] + '\n' + jug_p21[1]
            elif len(p21)>13 and p21.count(' ')==2:
                jug_p21 = p21.rsplit(' ',2)
                p21 = jug_p21[0] + '\n' + jug_p21[1] + ' ' +jug_p21[2]
            elif len(p21)>13 and p21.count(' ')==3:
                jug_p21 = p21.rsplit(' ',3)
                p21 = jug_p21[0] + '\n' + jug_p21[1] + ' ' +jug_p21[2] +' ' +jug_p21[3]
            elif len(p21)>13 and p21.count(' ')==4:
                jug_p21 = p21.rsplit(' ',4)
                p21 = jug_p21[0] + '\n' + jug_p21[1] + ' ' +jug_p21[2] +' ' +jug_p21[3]+' ' +jug_p21[4]
            else:
                print "mas de 166666666666"
                p21 = vivienda.p21
                #p21 = jug_p21[0] + '\n' + jug_p21[1]

            table2 = [(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or vivienda.or_viv_aeu == '0'  else '' ,
                       vivienda.manzana,
                       id_reg_or,
                       vivienda.frente_ord,
                       vivienda.p20_nombre if vivienda.p20 else "",
                       p21,
                       p22_a + p22_b,
                       vivienda.p23 if vivienda.p23 == 0 else "",
                       p24,
                       p25,
                       p26,
                       vivienda.p27_a if not vivienda.p27_a == None else '' + vivienda.p27_b if not vivienda.p27_b == None else '',
                       # 1 if a > b else -1
                       vivienda.p28 if vivienda.p28 == 0 else "",
                       jefe_home if not jefe_home == None else '')
                      ]
            u = Table(table2,
                      colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.1 * cm, 1.8 * cm, 2.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm,
                             1 * cm, 0.9 * cm, 0.9 * cm, 4.7 * cm],
                      rowHeights=[1 *cm])
            u.setStyle(TableStyle(
                [
                    ('GRID', (1, 1), (-2, -2), 1, colors.black),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTSIZE', (0, 0), (13, 0), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ]
            ))
            #u.wrapOn(c, width, height)
            story.append(u)

        if toti_viv>18:
            story.append(c)
            # inicio = range(16, toti_viv, 24)
            # fin = range(40, toti_viv, 24)
            # ini = 18
            # rango = 24
            # dato = 18
            #
            # while dato<toti_viv:
            #     dato = dato + rango
            #
            #
            #
            # inicio = list(range(ini,dato-(rango-1),rango))
            # final = list(range(ini+rango, dato+1, rango))
            #
            # final[-1]= toti_viv
            #
            # largo = zip(inicio, final)
            largo = rangos_registros(toti_viv)

            for i in largo:



                viviendas_second = v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal),Q(aeu_final=aeut)).order_by('manzana',
                                                                                                     'id_reg_or')[i[0]:i[1]]


                for vivienda in viviendas_second:
                    #i = i + 1

                    pep2 = vivienda.p29_a

                    for el in equi_pta:
                        if (el[0] == pep2):
                            pta_f = el[1]

                    jefe_hogar = ""
                    if vivienda.p29 == 1 or vivienda.p29 == 3:
                        jefe_hogar = vivienda.p32
                    elif vivienda.p29 == 5:
                        if vivienda.p29_a in (1, 2, 3, 4):
                            jefe_hogar = pta_f + "" + vivienda.p29_p
                        elif vivienda.p29_a in (5, 6):
                            jefe_hogar = pta_f
                        elif vivienda.p29_a == 7:
                            jefe_hogar = vivienda.p29_o
                        elif vivienda.p29_a == 8:
                            jefe_hogar = vivienda.p29_8_o
                    elif vivienda.p29 == 2 or vivienda.p29 == 4:
                        jefe_hogar = vivienda.p35
                    else:
                        print "No idea u.u"



                    jefe_h = u'{}'.format(jefe_hogar)

                    if jefe_h != None and jefe_h.count(' ') > 2 and len(jefe_h) > 26 and len(jefe_h) < 28:
                        print "Mayor a 26 caracteres"
                        jefe_jug = jefe_h.rsplit(' ', 1)
                        jefe_home = jefe_jug[0] + '\n' + jefe_jug[1]
                    # elif jefe_h != None and jefe_h!= type(1) and  jefe_h ==type('a') and jefe_h.count(' ') < 1:
                    #     print "Entro segunda condicion"
                    #
                    #     jefe_home = jefe_hogar
                    # elif jefe_h != None and jefe_h!= type(1) and  jefe_h ==type('a') and jefe_h.count(' ') == 0:
                    #     print "Entro tercera condicion"
                    #     # jefe_jug = jefe_h.rsplit(' ', 1)
                    #     jefe_home = jefe_hogar
                    if jefe_h != None and jefe_h.count(' ') > 2 and len(jefe_h) > 28:
                        print "Mayor a 26 caracteres"
                        jefe_jug = jefe_h.rsplit(' ', 2)
                        jefe_home = jefe_jug[0] + '\n' + jefe_jug[1] + ' ' + jefe_jug[2]
                    elif jefe_h == type(1) or jefe_h == type('a'):
                        print "Mayor a 26 caracteres enteero"

                        jefe_home = jefe_hogar
                    else:
                        print "Entro cuarta"
                        jefe_home = jefe_hogar

                    # Bloque Listado
                    if (vivienda.p22_a == None):
                        p22_a = ''
                    else:
                        p22_a = vivienda.p22_a
                    if (vivienda.p22_b == None):
                        p22_b = ''
                    else:
                        p22_b = vivienda.p22_b
                    if (vivienda.p24 == None):
                        p24 = ''
                    else:
                        p24 = vivienda.p24
                    if (vivienda.p25 == None):
                        p25 = ''
                    else:
                        p25 = vivienda.p25
                    if (vivienda.p26 == None):
                        p26 = ''
                    else:
                        p26 = vivienda.p26

                    if vivienda.or_viv_aeu == 0:
                        id_reg_or = ''
                    else:
                        id_reg_or = vivienda.id_reg_or

                    p21 = vivienda.p21

                    if len(p21) > 13 and p21.count(' ') == 1:
                        print "mas de 111111"
                        jug_p21 = p21.rsplit(' ', 1)

                        # firstblank_viviendap21 = (vivienda.p21).index(' ')
                        p21 = jug_p21[0] + '\n' + jug_p21[1]
                    elif len(p21) > 13 and p21.count(' ') == 2:
                        jug_p21 = p21.rsplit(' ', 2)
                        p21 = jug_p21[0] + '\n' + jug_p21[1] + ' ' + jug_p21[2]
                    elif len(p21) > 13 and p21.count(' ') == 3:
                        jug_p21 = p21.rsplit(' ', 3)
                        p21 = jug_p21[0] + '\n' + jug_p21[1] + ' ' + jug_p21[2] + ' ' + jug_p21[3]
                    else:
                        print "mas de 166666666666"
                        p21 = vivienda.p21
                        # p21 = jug_p21[0] + '\n' + jug_p21[1]

                    table2 = [(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or vivienda.or_viv_aeu == '0'  else '' ,
                           vivienda.manzana,
                           id_reg_or,
                           vivienda.frente_ord,
                           vivienda.p20_nombre if vivienda.p20 else "",
                           p21,
                           p22_a + p22_b,
                           vivienda.p23 if vivienda.p23 == 0 else "",
                           p24,
                           p25,
                           p26,
                           vivienda.p27_a if not vivienda.p27_a == None else '' + vivienda.p27_b if not vivienda.p27_b == None else '',
                           vivienda.p28 if vivienda.p28 == 0 else "",
                           jefe_home if not jefe_home == None else '')
                          ]
                    u_second = Table(table2,
                              colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.1 * cm, 1.8 * cm, 2.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm,
                                 1 * cm, 0.9 * cm, 0.9 * cm, 4.7 * cm],
                              rowHeights=[1 * cm])

                    u_second.setStyle(TableStyle(
                        [
                            ('GRID', (1, 1), (-2, -2), 1, colors.black),
                            ('GRID', (0, 0), (-1, -1), 1, colors.black),
                            ('GRID', (0, 0), (-1, -1), 1, colors.black),
                            ('FONTSIZE', (0, 0), (13, 0), 7),
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ]
                    ))

                    story.append(u_second)
                story.append(PageBreak())
                story.append(c)
            del story[-1]
            del story[-1]

            # obs_data_two = [
            #     [Paragraph(e, h3) for e in ["<strong>Viv Nº</strong>",
            #                                 "<strong>Mz Nº</strong>",
            #                                 "<strong>Or Reg</strong>",
            #                                 "<strong>Frent Nº</strong>",
            #                                 "<strong>DIRECCIÓN DE LA VIVIENDA</strong>",
            #                                 "", "", "", "", "", "", "", "",
            #                                 "<strong>Nombres y Apellidos del JEFE DEL HOGAR</strong>"]],
            #     [Paragraph(e, h3) for e in ["", "", "", "",
            #                                 "<strong>Tipo de Vía</strong>",
            #                                 "<strong>Nombre de VÍa</strong>",
            #                                 "<strong>Nº de Puerta</strong>",
            #                                 "<strong>Block</strong>",
            #                                 "<strong>Mz Nº</strong>",
            #                                 "<strong>Lote Nº</strong>",
            #                                 "<strong>Piso Nº</strong>",
            #                                 "<strong>Int. Nº</strong>",
            #                                 "<strong>Km. Nº</strong>",
            #                                 ""]],
            #     [Paragraph(e, h3) for e in ["<strong>(1)</strong>",
            #                                 "<strong>(2)</strong>",
            #                                 "<strong>(3)</strong>",
            #                                 "<strong>(4)</strong>",
            #                                 "<strong>(5)</strong>",
            #                                 "<strong>(6)</strong>",
            #                                 "<strong>(7)</strong>",
            #                                 "<strong>(8)</strong>",
            #                                 "<strong>(9)</strong>",
            #                                 "<strong>(10)</strong>",
            #                                 "<strong>(11)</strong>",
            #                                 "<strong>(12)</strong>",
            #                                 "<strong>(13)</strong>",
            #                                 "<strong>(14)</strong>"]],
            # ]
            # c_2 = Table(obs_data_two,
            #           colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.1 * cm, 1.8 * cm, 2.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm,
            #                  1 * cm, 0.9 * cm, 0.9 * cm, 4.7 * cm])
            # c_2.setStyle(TableStyle(
            #     [
            #         ('GRID', (1, 1), (-2, -2), 1, colors.black),
            #         ('GRID', (0, 0), (-1, -1), 1, colors.black),
            #         ('GRID', (0, 0), (-1, -1), 1, colors.black),
            #         # ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
            #         ('FONTSIZE', (0, 0), (-1, -1), 7),
            #         ('BACKGROUND', (0, 0), (-1, 0), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            #         ('BACKGROUND', (0, 0), (-1, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            #         ('SPAN', (4, 0), (12, 0)),
            #         ('SPAN', (0, 0), (0, 1)),
            #         ('SPAN', (1, 0), (1, 1)),
            #         ('SPAN', (2, 0), (2, 1)),
            #         ('SPAN', (3, 0), (3, 1)),
            #         ('SPAN', (13, 0), (13, 1)),
            #         ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            #         ('BACKGROUND', (0, 0), (13, 2), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            #     ]
            # ))

            # viviendas_three = v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal),Q(aeu_final=aeut)).order_by('manzana',
            #                                                                                      'id_reg_or')[41:]
            #
            # if toti_viv > 41:
            #     story.append(c_2)
            #
            #     inicio = range(32, toti_viv, 52)
            #     fin = range(85, toti_viv, 52)
            #     nhojas = len(zip(inicio, fin))
            #     for vivienda in viviendas_three:
            #         i = i + 1
            #
            #         pep2 = vivienda.p29_a
            #
            #         for el in equi_pta:
            #             if (el[0] == pep2):
            #                 pta_f = el[1]
            #
            #         jefe_hogar = ""
            #         if vivienda.p29 == 1 or vivienda.p29 == 3:
            #             jefe_hogar = vivienda.p32
            #         elif vivienda.p29 == 5:
            #             if vivienda.p29_a in (1, 2, 3, 4):
            #                 jefe_hogar = pta_f + "" + vivienda.p29_p
            #             elif vivienda.p29_a in (5, 6):
            #                 jefe_hogar = pta_f
            #             elif vivienda.p29_a == 7:
            #                 jefe_hogar = vivienda.p29_o
            #             elif vivienda.p29_a == 8:
            #                 jefe_hogar = vivienda.p29_8_o
            #         elif vivienda.p29 == 2 or vivienda.p29 == 4:
            #             jefe_hogar = vivienda.p35
            #         else:
            #             print "No idea u.u"
            #
            #         jefe_h = jefe_hogar
            #
            #         if jefe_h != None and jefe_h == type('a') and  jefe_h ==type('a') and len(jefe_h) > 25 and jefe_h.count(' ') >= 3:
            #             print "Entroooooo  nombre 2222"
            #             jefe_jug = jefe_h.rsplit(' ', 2)
            #             jefe_home = jefe_jug[0] + '\n' + jefe_jug[1]
            #         elif jefe_h != None and jefe_h != type(1) and  jefe_h ==type('a') and jefe_h.count(' ') < 3:
            #             print "Entro nombre normal"
            #
            #             jefe_home = jefe_hogar
            #         elif jefe_h != None and jefe_h!= type(1) and  jefe_h ==type('a') and jefe_h.count(' ') == 0:
            #             print "Entro nombre normal"
            #             # jefe_jug = jefe_h.rsplit(' ', 1)
            #             jefe_home = jefe_hogar
            #         else:
            #             jefe_home = jefe_hogar
            #         # Bloque Listado
            #         if (vivienda.p22_a == None):
            #             p22_a = ''
            #         else:
            #             p22_a = vivienda.p22_a
            #         if (vivienda.p22_b == None):
            #             p22_b = ''
            #         else:
            #             p22_b = vivienda.p22_b
            #         if (vivienda.p24 == None):
            #             p24 = ''
            #         else:
            #             p24 = vivienda.p24
            #         if (vivienda.p25 == None):
            #             p25 = ''
            #         else:
            #             p25 = vivienda.p25
            #         if (vivienda.p26 == None):
            #             p26 = ''
            #         else:
            #             p26 = vivienda.p26
            #
            #         if vivienda.or_viv_aeu == 0:
            #             id_reg_or = ''
            #         else:
            #             id_reg_or = vivienda.id_reg_or
            #
            #         p21 = vivienda.p21
            #
            #         if len(p21) > 11 and p21.count(' ') > 2:
            #             print "mas de 111111"
            #             jug_p21 = p21.rsplit(' ', 2)
            #
            #             # firstblank_viviendap21 = (vivienda.p21).index(' ')
            #             p21 = jug_p21[0] + '\n' + jug_p21[1]
            #         else:
            #             print "mas de 166666666666"
            #             jug_p21 = p21.rsplit(' ', 1)
            #             p21 = jug_p21[0] + '\n' + jug_p21[1]
            #         table2 = [
            #             (vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or vivienda.or_viv_aeu == '0'  else '',
            #              vivienda.manzana,
            #              id_reg_or,
            #              vivienda.frente_ord,
            #              vivienda.p20_nombre if vivienda.p20 else "",
            #              p21,
            #              p22_a + p22_b,
            #              vivienda.p23 if vivienda.p23 == 0 else "",
            #              p24,
            #              p25,
            #              p26,
            #              vivienda.p27_a if not vivienda.p27_a == None else '' + vivienda.p27_b if not vivienda.p27_b == None else '',
            #              vivienda.p28 if vivienda.p28 == 0 else "",
            #              jefe_home if not jefe_home == None else '')
            #             ]
            #         u_three= Table(table2,
            #                          colWidths=[0.8 * cm, 0.8 * cm, 1 * cm, 1.1 * cm, 1.8 * cm, 2.6 * cm, 1.2 * cm, 1.1 * cm, 0.8 * cm, 1 * cm,
            #                  1 * cm, 0.9 * cm, 0.9 * cm, 4.7 * cm],
            #                          rowHeights=[1 * cm])
            #
            #         u_three.setStyle(TableStyle(
            #             [
            #                 ('GRID', (1, 1), (-2, -2), 1, colors.black),
            #                 ('GRID', (0, 0), (-1, -1), 1, colors.black),
            #                 ('GRID', (0, 0), (-1, -1), 1, colors.black),
            #                 ('FONTSIZE', (0, 0), (13, 0), 7),
            #                 ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            #             ]
            #         ))
            #         story.append(u_three)
        # if(PageBreak()):
        #     story.append(Spacer(0, 22 * cm))
        #     story.append(table_obs)
        #     story.append(Spacer(0, 1 * mm))
        #     story.append(table_empa_cuerp)
        # else:
        story.append(Spacer(0, 1 * cm))
        #story.append(table_obs)
        story.append(Spacer(0, 1 * mm))
        story.append(table_empa_cuerp)
        # Z_obs = Paragraph("<strong>OBSERVACIONES: ...................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    ".............................1</strong>", h_obser)
        #
        # table_obser = Table(
        #         data=[
        #             [Z_obs]
        #         ],
        #         colWidths=[18.3 * cm],
        #         style=[
        #             ('GRID', (0, 0), (-1, -1), 1, colors.black)
        #         ]
        # )
        # if (PageBreak()):
        # story.append(Spacer(0, 1.3 * cm))
        # story.append(Spacer(0, 1 * mm))
        # story.append(table_empa_cuerp)
        story.append(Spacer(0, 1 * mm))
        #story.append(p_page)
        # else:
        #     story.append(Spacer(0, 21 * cm))
        #     story.append(table_obs)
        #     story.append(Spacer(0, 1 * mm))
        #     sory.append(table_empa_cuerp)
        #     story.append(Spacer(0, 1 * mm))
        #     story.append(p_page)

    doc2.build(story)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#28
0
def makePdf(npm_mahasiswa, nama_mahasiswa, tipe_bimbingan,
            kode_dosen_pembimbing, nama_pembimbing, nidn_pembimbing,
            tahun_ajaran, photo, judul, total_nilai, elements, logo, styles,
            kode_dosen_koordinator):
    checkDir()
    makeQrcodeVerifySign(link=makeLinkVerify(kode_dosen=kode_dosen_pembimbing,
                                             npm_mahasiswa=npm_mahasiswa,
                                             tipe_bimbingan=tipe_bimbingan,
                                             total_nilai=total_nilai),
                         kode_dosen=kode_dosen_pembimbing,
                         npm_mahasiswa=npm_mahasiswa,
                         tipe_bimbingan=tipe_bimbingan)
    makeQrcodeVerifySign(link=makeLinkVerify(kode_dosen=kode_dosen_koordinator,
                                             npm_mahasiswa=npm_mahasiswa,
                                             tipe_bimbingan=tipe_bimbingan,
                                             total_nilai=total_nilai),
                         kode_dosen=kode_dosen_koordinator,
                         npm_mahasiswa=npm_mahasiswa,
                         tipe_bimbingan=tipe_bimbingan)
    bulan = date.today().strftime("%m")
    d2 = date.today().strftime(f"%d {bkd.bulanSwitcher(bulan)} %Y")
    elements.append(logo)

    ptext = '<font name="Times" size="14">BERITA ACARA</font>'
    elements.append(Paragraph(ptext, styles["Center"]))
    elements.append(Spacer(1, 12))

    ptext = f'<font name="Times" size="14">{switcherTipeBimbingan(tipe_bimbingan)}</font>'
    elements.append(Paragraph(ptext, styles["Center"]))
    elements.append(Spacer(1, 12))

    ptext = '<font name="Times" size="14">TA. ' + tahun_ajaran + '</font>'
    elements.append(Paragraph(ptext, styles["Center"]))
    elements.append(Spacer(1, 0.5 * inch))

    image = Image(photo, 1.1 * inch, 1.5 * inch)
    image.hAlign = "RIGHT"
    elements.append(image)
    elements.append(Spacer(1, 1.5 * inch))

    ptext = '<font size=12> </font>'
    elements.append(Paragraph(ptext, styles["Center"]))
    elements.append(Spacer(1, -3 * inch))

    table = [[
        '<font name="Times" size="12">Nama</font>',
        '<font name="Times" size="12">: ' + nama_mahasiswa + '</font>'
    ],
             [
                 '<font name="Times" size="12">Npm</font>',
                 '<font name="Times" size="12">: ' + npm_mahasiswa + '</font>'
             ],
             [
                 '<font name="Times" size="12">Judul</font>',
                 '<font name="Times" size="12">: ' + judul + '</font>'
             ],
             [
                 '<font name="Times" size="12">Pembimbing</font>',
                 '<font name="Times" size="12">: ' + nama_pembimbing +
                 '</font>'
             ]]

    style = TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
                        ('VALIGN', (0, 0), (0, -1), 'TOP'),
                        ('ALIGN', (0, -1), (-1, -1), 'LEFT'),
                        ('VALIGN', (0, -1), (-1, -1), 'MIDDLE')])

    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = 'CJK'
    data1 = [[Paragraph(cell, s) for cell in row] for row in table]
    tab = Table(data1, hAlign='LEFT', colWidths=[75, 290])
    tab.setStyle(style)

    elements.append(tab)
    elements.append(Spacer(1, 0.6 * inch))

    data = [[
        'Pertemuan', 'Tanggal', 'Sudah Dikerjakan', 'Pekerjaan Selanjutnya',
        'Nilai'
    ]]
    inner_data_list = makeListDataBimbinganByDosens(npm_mahasiswa,
                                                    kode_dosen_pembimbing)
    for i in inner_data_list:
        data.append(i)
    nilai_data_list = [
        '', '', '', 'Rata-Rata: ',
        "%.2f" % round(float(total_nilai), 2)
    ]
    data.append(nilai_data_list)

    style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                        ('VALIGN', (0, 0), (0, -1), 'MIDDLE'),
                        ('ALIGN', (0, 0), (0, -1), 'CENTER'),
                        ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])

    s = getSampleStyleSheet()
    s = s["Normal"]
    s.wordWrap = 'CJK'
    data2 = [[Paragraph(cell, s) for cell in row] for row in data]
    t = Table(data2, hAlign='CENTER', colWidths=[62.5, 65, 180, 180, 40])
    t.setStyle(style)

    elements.append(t)
    elements.append(Spacer(1, 10))

    # ptext = '<font size=12> </font>'
    # elements.append(Paragraph(ptext, styles["Right"]))
    # elements.append(Spacer(1, .5 * inch))

    bulan = date.today().strftime("%m")
    tanggal = date.today().strftime(f"%d {bkd.bulanSwitcher(bulan)} %Y")

    data = approve_kambing.getDataPembimbing(npm_mahasiswa,
                                             kode_dosen_pembimbing)
    pembimbingke = approve_kambing.pembimbingPositionAs(
        data, kode_dosen_pembimbing)
    qrcode_pembimbing = f"./beritaacarapitakqrcode/{npm_mahasiswa}-{kode_dosen_pembimbing}-{tipe_bimbingan}.png"
    if approve_kambing.cekApprovalTrueorFalse(
            npm_mahasiswa, pembimbingke.replace('pembimbing', 'koordinator')):
        qrcode_koordinator = f"./beritaacarapitakqrcode/{npm_mahasiswa}-{kode_dosen_koordinator}-{tipe_bimbingan}.PNG"
    else:
        qrcode_koordinator = f"./beritaacarapitakqrcode/whiteimage.png"

    image_pembimbing = Image(qrcode_pembimbing, 1.4 * inch, 1.4 * inch)
    image_pembimbing.vAlign = "CENTER"
    image_pembimbing.hAlign = "CENTER"
    image_koordinator = Image(qrcode_koordinator, 1.4 * inch, 1.4 * inch)
    image_koordinator.hAlign = "CENTER"
    image_koordinator.vAlign = "CENTER"

    data = [
        [
            '',
            Paragraph(f'<font name="Times">Bandung, {tanggal}</font>',
                      styles["Center"]), ''
        ],
        [
            Paragraph('<font name="Times"><b>Koordinator</b></font>',
                      styles["Center"]), '',
            Paragraph('<font name="Times"><b>Pembimbing</b></font>',
                      styles["Center"])
        ],
        [image_koordinator, '', image_pembimbing],
        [
            Paragraph(
                f'<font name="Times"><b>{kelas.getNamaDosen("TI041L")}</b></font>',
                styles["Justify"]), '',
            Paragraph(
                f'<font name="Times"><b>{kelas.getNamaDosen(kode_dosen_pembimbing)}</b></font>',
                styles["Justify"])
        ],
        [
            Paragraph(
                f'<font name="Times"><b>NIDN. {kelas.getAllDataDosens("TI041L")[2]}</b></font>',
                styles["Justify"]), '',
            Paragraph(
                f'<font name="Times"><b>NIDN. {nidn_pembimbing}</b></font>',
                styles["Justify"])
        ],
    ]

    table = Table(data, [7 * cm, 4.3 * cm, 7 * cm],
                  [1 * cm, .5 * cm, 3.5 * cm, .5 * cm, .5 * cm])
    table.setStyle(
        TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Times-Roman', 12),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            # ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
            # ('BOX', (0,0), (-1,-1), 0.25, colors.black),
        ]))

    elements.append(table)
示例#29
0
def _create_pdf(invoice_buffer, legal_case, request_data):
    try:
        # 'report' variable set according to whether document_type is 'brief_of_evidence' or 'prosecution_brief'
        # 'report_document_artifacts' variable set according to whether document_type is 'brief_of_evidence' or 'prosecution_brief'
        document_type = request_data.get('document_type')
        include_statement_of_facts = request_data.get(
            'include_statement_of_facts')
        include_case_information_form = request_data.get(
            'include_case_information_form')
        include_offences_offenders_roi = request_data.get(
            'include_offences_offenders_roi')
        include_witness_officer_other_statements = request_data.get(
            'include_witness_officer_other_statements')
        include_physical_artifacts = request_data.get(
            'include_physical_artifacts')
        include_document_artifacts = request_data.get(
            'include_document_artifacts')
        report = None
        report_document_artifacts = None
        report_physical_artifacts = None
        record_of_interviews = None
        other_statements = None
        if document_type == 'brief_of_evidence':
            report = legal_case.brief_of_evidence
            report_document_artifacts = legal_case.briefofevidencedocumentartifacts_set.all(
            )
            report_physical_artifacts = legal_case.briefofevidencephysicalartifacts_set.all(
            )
            record_of_interviews = legal_case.legal_case_boe_roi.all()
            other_statements = legal_case.legal_case_boe_other_statements.all()
        elif document_type == 'prosecution_brief':
            report = legal_case.prosecution_brief
            report_document_artifacts = legal_case.prosecutionbriefdocumentartifacts_set.all(
            )
            report_physical_artifacts = legal_case.prosecutionbriefphysicalartifacts_set.all(
            )
            record_of_interviews = legal_case.legal_case_pb_roi.all()
            other_statements = legal_case.legal_case_pb_other_statements.all()
        # physical artifacts used in case
        physical_artifacts_used_within_case = []
        for artifact in report_physical_artifacts:
            legal_case_physical_artifact_link = legal_case.physicalartifactlegalcases_set.get(
                legal_case_id=legal_case.id,
                physical_artifact_id=artifact.physical_artifact.id)
            if legal_case_physical_artifact_link.used_within_case:
                identifier = artifact.physical_artifact.identifier if artifact.physical_artifact.identifier else artifact.physical_artifact.number
                physical_artifacts_used_within_case.append(
                    [identifier, artifact.ticked])
        # sensitive physical artifacts not used in case
        physical_artifacts_sensitive_unused = []
        for artifact in report_physical_artifacts:
            legal_case_physical_artifact_link = legal_case.physicalartifactlegalcases_set.get(
                legal_case_id=legal_case.id,
                physical_artifact_id=artifact.physical_artifact.id)
            if (not legal_case_physical_artifact_link.used_within_case and
                    legal_case_physical_artifact_link.sensitive_non_disclosable
                ):
                identifier = artifact.physical_artifact.identifier if artifact.physical_artifact.identifier else artifact.physical_artifact.number
                physical_artifacts_sensitive_unused.append([
                    identifier, artifact.ticked,
                    artifact.reason_sensitive_non_disclosable
                ])
        # non sensitive physical artifacts not used in case
        physical_artifacts_non_sensitive_unused = []
        for artifact in report_physical_artifacts:
            legal_case_physical_artifact_link = legal_case.physicalartifactlegalcases_set.get(
                legal_case_id=legal_case.id,
                physical_artifact_id=artifact.physical_artifact.id)
            if (not legal_case_physical_artifact_link.used_within_case
                    and not legal_case_physical_artifact_link.
                    sensitive_non_disclosable):
                identifier = artifact.physical_artifact.identifier if artifact.physical_artifact.identifier else artifact.physical_artifact.number
                physical_artifacts_non_sensitive_unused.append(
                    [identifier, artifact.ticked])

        every_page_frame = Frame(
            PAGE_MARGIN,
            PAGE_MARGIN,
            PAGE_WIDTH - 2 * PAGE_MARGIN,
            PAGE_HEIGHT - 2 * PAGE_MARGIN,
            id='EveryPagesFrame',
        )  #showBoundary=Color(0, 1, 0))
        every_page_template = PageTemplate(
            id='EveryPages',
            frames=[
                every_page_frame,
            ],
        )
        doc = BaseDocTemplate(
            invoice_buffer,
            pageTemplates=[
                every_page_template,
            ],
            pagesize=A4,
        )  # showBoundary=Color(1, 0, 0))

        # Common
        col_width_head = [
            85 * mm,
            25 * mm,
            85 * mm,
        ]
        col_width_details = [27 * mm, 27 * mm, 71 * mm, 30 * mm, 36 * mm]
        col_width_for_court = [
            27 * mm, 24 * mm, 18 * mm, 58 * mm, 47 * mm, 17 * mm
        ]
        FONT_SIZE_L = 11
        FONT_SIZE_M = 10
        FONT_SIZE_S = 8

        styles = StyleSheet1()
        styles.add(
            ParagraphStyle(
                name='Normal',
                fontName='Helvetica',
                fontSize=FONT_SIZE_M,
                spaceBefore=7,  # space before paragraph
                spaceAfter=7,  # space after paragraph
                leading=12))  # space between lines
        styles.add(
            ParagraphStyle(name='BodyText',
                           parent=styles['Normal'],
                           spaceBefore=6))
        styles.add(
            ParagraphStyle(name='Italic',
                           parent=styles['BodyText'],
                           fontName='Helvetica-Italic'))
        styles.add(
            ParagraphStyle(name='Bold',
                           parent=styles['BodyText'],
                           fontName='Helvetica-Bold',
                           alignment=TA_CENTER))
        styles.add(
            ParagraphStyle(name='BoldLeft',
                           parent=styles['BodyText'],
                           fontName='Helvetica-Bold'))
        styles.add(
            ParagraphStyle(name='Right',
                           parent=styles['BodyText'],
                           alignment=TA_RIGHT))
        styles.add(
            ParagraphStyle(name='Centre',
                           parent=styles['BodyText'],
                           alignment=TA_CENTER))

        # Details of alleged offence
        #rowHeights = [6*mm, 6*mm, 6*mm, 30*mm, 6*mm]
        #style_tbl_details = TableStyle([
        #    ('VALIGN', (0, 0), (0, 0), 'TOP'),
        #    ('VALIGN', (1, 0), (-1, -1), 'MIDDLE'),
        #    ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        #    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        #    ('SPAN', (0, 0), (0, 4)),
        #    ('SPAN', (2, 0), (4, 0)),
        #    ('SPAN', (2, 1), (4, 1)),
        #    ('SPAN', (2, 2), (4, 2)),
        #    ('SPAN', (2, 3), (4, 3)),
        #    ('SPAN', (2, 4), (4, 4)),
        #])

        #case_information_header_data = []
        #case_information_header_data.append([
        #   Paragraph('Case Information Form', styles['Bold']),
        #])

        #tbl_details = Table(data, style=style_tbl_details, colWidths=col_width_details, rowHeights=rowHeights)
        #tbl_statement = Table(data, style=style_tbl_details, colWidths=col_width_details, rowHeights=rowHeights)
        #tbl_case_information_header = Table(case_information_header_data)

        #tbl_case_information_data = ListFlowable(
        #       [
        #          Paragraph
        statement_of_facts_data = []
        statement_of_facts_data.append([
            Paragraph('Statement of Facts', styles['BoldLeft']),
        ])
        string_field = report.statement_of_facts if report.statement_of_facts else ''
        statement_of_facts_data.append(
            [Paragraph(string_field, styles['Normal'])])
        tbl_statement_of_facts = Table(statement_of_facts_data)

        case_information_data = []
        case_information_data.append([
            Paragraph('Case Information Form', styles['BoldLeft']),
        ])

        case_information_data.append([
            ParagraphCheckbox("Victim impact statement to be taken?",
                              x_offset=5,
                              checked=report.victim_impact_statement_taken,
                              style=styles['Normal'])
        ])
        if report.victim_impact_statement_taken:
            string_field = report.victim_impact_statement_taken_details if report.victim_impact_statement_taken_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Witness (including expert statements) still to be taken?",
                x_offset=5,
                checked=report.statements_pending,
                style=styles['Normal'])
        ])
        if report.statements_pending:
            string_field = report.statements_pending_details if report.statements_pending_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox("Vulnerable / hostile witnesses?",
                              x_offset=5,
                              checked=report.vulnerable_hostile_witnesses,
                              style=styles['Normal'])
        ])
        if report.vulnerable_hostile_witnesses:
            string_field = report.vulnerable_hostile_witnesses_details if report.vulnerable_hostile_witnesses_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox("Witnesses refusing to make statements?",
                              x_offset=5,
                              checked=report.witness_refusing_statement,
                              style=styles['Normal'])
        ])
        if report.witness_refusing_statement:
            string_field = report.witness_refusing_statement_details if report.witness_refusing_statement_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Specific problems / needs of prosecution witnesses, e.g. interpreters?",
                x_offset=5,
                checked=report.problems_needs_prosecution_witnesses,
                style=styles['Normal'])
        ])
        if report.problems_needs_prosecution_witnesses:
            string_field = report.problems_needs_prosecution_witnesses_details if report.problems_needs_prosecution_witnesses_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "History of bad character / propensity (similar fact) evidence involving accused?",
                x_offset=5,
                checked=report.accused_bad_character,
                style=styles['Normal'])
        ])
        if report.accused_bad_character:
            string_field = report.accused_bad_character_details if report.accused_bad_character_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Further persons (witness or suspect) to be interviewed?",
                x_offset=5,
                checked=report.further_persons_interviews_pending,
                style=styles['Normal'])
        ])
        if report.further_persons_interviews_pending:
            string_field = report.further_persons_interviews_pending_details if report.further_persons_interviews_pending_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Other persons whose details do not appear on this brief who have been interviewed?",
                x_offset=5,
                checked=report.other_interviews,
                style=styles['Normal'])
        ])
        if report.other_interviews:
            string_field = report.other_interviews_details if report.other_interviews_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Other relevant persons charged or yet to be charged?",
                x_offset=5,
                checked=report.relevant_persons_pending_charges,
                style=styles['Normal'])
        ])
        if report.other_interviews:
            string_field = report.relevant_persons_pending_charges_details if report.relevant_persons_pending_charges_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Others receiving Infringement / Warning arising out of the same incident?",
                x_offset=5,
                checked=report.other_persons_receiving_sanction_outcome,
                style=styles['Normal'])
        ])
        if report.other_persons_receiving_sanction_outcome:
            string_field = report.other_persons_receiving_sanction_outcome_details if report.other_persons_receiving_sanction_outcome_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox("Matters of local / public interest?",
                              x_offset=5,
                              checked=report.local_public_interest,
                              style=styles['Normal'])
        ])
        if report.local_public_interest:
            string_field = report.local_public_interest_details if report.local_public_interest_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Other applications / orders on conviction requests?",
                x_offset=5,
                checked=report.applications_orders_requests,
                style=styles['Normal'])
        ])
        if report.applications_orders_requests:
            string_field = report.applications_orders_requests_details if report.applications_orders_requests_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Are there any other applications / orders on conviction required?",
                x_offset=5,
                checked=report.applications_orders_required,
                style=styles['Normal'])
        ])
        if report.applications_orders_required:
            string_field = report.applications_orders_required_details if report.applications_orders_required_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])
        case_information_data.append([
            ParagraphCheckbox(
                "Is there any statutory notice, DEC licence, ministerial statement or policy etc. re the matter, premise or person subject to this brief?",
                x_offset=5,
                checked=report.other_legal_matters,
                style=styles['Normal'])
        ])
        if report.other_legal_matters:
            string_field = report.other_legal_matters_details if report.other_legal_matters_details else ''
            case_information_data.append([
                ParagraphOffeset(
                    string_field,
                    styles['Normal'],
                    x_offset=25,
                )
            ])

        tbl_case_information = Table(case_information_data)
        record_of_interviews_data = []

        record_of_interviews_data.append([
            Paragraph('Offences, Offenders and Records of Interview',
                      styles['BoldLeft']),
        ])
        if not record_of_interviews:
            record_of_interviews_data.append([
                Paragraph('No Offences, Offenders or Records of Interview',
                          styles['Normal']),
            ])
        else:
            for offence_level_record in record_of_interviews.filter(
                    offender=None):

                record_of_interviews_data.append([
                    ParagraphCheckbox(offence_level_record.label,
                                      x_offset=5,
                                      checked=offence_level_record.ticked,
                                      style=styles['Normal']),
                ])
                for offender_level_record in offence_level_record.children.all(
                ):

                    record_of_interviews_data.append([
                        ParagraphCheckbox(offender_level_record.label,
                                          x_offset=15,
                                          checked=offender_level_record.ticked,
                                          style=styles['Normal']),
                    ])
                    for roi_level_record in offender_level_record.children.all(
                    ):

                        record_of_interviews_data.append([
                            ParagraphCheckbox(roi_level_record.label,
                                              x_offset=25,
                                              checked=roi_level_record.ticked,
                                              style=styles['Normal']),
                        ])

                        for doc_artifact_level_record in roi_level_record.children.all(
                        ):
                            record_of_interviews_data.append([
                                ParagraphCheckbox(
                                    doc_artifact_level_record.label,
                                    x_offset=35,
                                    checked=doc_artifact_level_record.ticked,
                                    style=styles['Normal']),
                            ])

        tbl_record_of_interviews = Table(record_of_interviews_data)

        other_statements_data = []
        other_statements_data.append([
            Paragraph(
                'Witness Statements, Officer Statements, Expert Statements',
                styles['BoldLeft']),
        ])
        if not other_statements:
            other_statements_data.append([
                Paragraph(
                    'No Witness Statements, Officer Statements or Expert Statements',
                    styles['Normal']),
            ])
        else:
            for person_level_record in other_statements.filter(statement=None):

                other_statements_data.append([
                    ParagraphCheckbox(person_level_record.label,
                                      x_offset=5,
                                      checked=person_level_record.ticked,
                                      style=styles['Normal']),
                ])
                for statement_level_record in person_level_record.children.all(
                ):

                    other_statements_data.append([
                        ParagraphCheckbox(
                            statement_level_record.label,
                            x_offset=15,
                            checked=statement_level_record.ticked,
                            style=styles['Normal']),
                    ])

                    for doc_artifact_level_record in statement_level_record.children.all(
                    ):
                        other_statements_data.append([
                            ParagraphCheckbox(
                                doc_artifact_level_record.label,
                                x_offset=35,
                                checked=doc_artifact_level_record.ticked,
                                style=styles['Normal']),
                        ])
        tbl_other_statements = Table(other_statements_data)
        physical_artifacts_data = []
        physical_artifacts_data.append([
            Paragraph(
                'List of Exhibits, Sensitive Unused and Non-sensitive Unused Materials',
                styles['BoldLeft']),
        ])
        # physical artifacts used in case
        if not physical_artifacts_used_within_case:
            physical_artifacts_data.append([
                Paragraph('No objects to be included on the list of exhibits',
                          styles['Normal']),
            ])
        else:
            physical_artifacts_data.append([
                Paragraph('Objects to be included on the list of exhibits',
                          styles['Normal']),
            ])
            for artifact in physical_artifacts_used_within_case:
                physical_artifacts_data.append([
                    ParagraphCheckbox(artifact[0],
                                      x_offset=5,
                                      checked=artifact[1],
                                      style=styles['Normal'])
                ])
        # physical artifacts sensitive unused
        if not physical_artifacts_sensitive_unused:
            physical_artifacts_data.append([
                Paragraph(
                    'No objects to be included on the sensitive unused list of materials',
                    styles['Normal']),
            ])
        else:
            physical_artifacts_data.append([
                Paragraph(
                    'Objects to be included on the sensitive unused list of materials',
                    styles['Normal']),
            ])
            for artifact in physical_artifacts_sensitive_unused:
                physical_artifacts_data.append([
                    ParagraphCheckbox(artifact[0],
                                      x_offset=5,
                                      checked=artifact[1],
                                      style=styles['Normal'])
                ])
                if artifact[2]:
                    physical_artifacts_data.append([
                        ParagraphOffeset(
                            artifact[2],
                            styles['Normal'],
                            x_offset=25,
                        )
                    ])
        # physical artifacts non sensitive unused
        if not physical_artifacts_non_sensitive_unused:
            physical_artifacts_data.append([
                Paragraph(
                    'No objects to be included on the non-sensitive unused list of materials',
                    styles['Normal']),
            ])
        else:
            physical_artifacts_data.append([
                Paragraph(
                    'Objects to be included on the non-sensitive unused list of materials',
                    styles['Normal']),
            ])
            for artifact in physical_artifacts_non_sensitive_unused:
                physical_artifacts_data.append([
                    ParagraphCheckbox(artifact[0],
                                      x_offset=5,
                                      checked=artifact[1],
                                      style=styles['Normal'])
                ])

        tbl_physical_artifacts = Table(physical_artifacts_data)

        #import ipdb; ipdb.set_trace();
        document_artifacts_data = []
        document_artifacts_data.append([
            Paragraph('List of Photographic, Video and Sound Exhibits',
                      styles['BoldLeft']),
        ])
        if not report_document_artifacts:
            document_artifacts_data.append([
                Paragraph('No Photographic, Video and Sound Exhibits',
                          styles['Normal']),
            ])
        else:
            for artifact in report_document_artifacts:
                identifier = artifact.document_artifact.identifier if artifact.document_artifact.identifier else artifact.document_artifact.number
                document_artifacts_data.append([
                    ParagraphCheckbox(identifier,
                                      x_offset=5,
                                      checked=artifact.ticked,
                                      style=styles['Normal'])
                ])
                for attachment in artifact.document_artifact.documents.all():
                    if attachment.name:
                        document_artifacts_data.append([
                            ParagraphOffeset(
                                attachment.name,
                                styles['Normal'],
                                x_offset=25,
                            )
                        ])

        tbl_document_artifacts = Table(document_artifacts_data)

        # Append tables to the elements to build
        gap_between_tables = 5.5 * mm
        elements = []
        #elements.append(tbl_case_information_header)
        if include_statement_of_facts:
            elements.append(tbl_statement_of_facts)
            elements.append(Spacer(0, gap_between_tables))
        if include_case_information_form:
            elements.append(tbl_case_information)
            elements.append(Spacer(0, gap_between_tables))
        if include_offences_offenders_roi:
            elements.append(tbl_record_of_interviews)
            elements.append(Spacer(0, gap_between_tables))
        if include_witness_officer_other_statements:
            elements.append(tbl_other_statements)
            elements.append(Spacer(0, gap_between_tables))
        if include_physical_artifacts:
            elements.append(tbl_physical_artifacts)
            elements.append(Spacer(0, gap_between_tables))
        if include_document_artifacts:
            elements.append(tbl_document_artifacts)
            elements.append(Spacer(0, gap_between_tables))
        doc.build(elements)
        return invoice_buffer
    except Exception as e:
        raise e
示例#30
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

        #format labels

        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA STRUTTURA<br/>" + str(self.datestrfdate()) + "</b>",
            styNormal)
        #intestazione2 = Paragraph("<b>pyArchInit</b><br/>www.pyarchinit.blogspot.com", styNormal)
        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

        home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
        logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + str(self.sito), styNormal)
        sigla_struttura = Paragraph(
            "<b>Sigla/Nr.</b><br/> %s%s" %
            (str(self.sigla_struttura), str(self.numero_struttura)), styNormal)

        #2 row
        categoria = Paragraph(
            "<b>Categoria</b><br/>" + self.categoria_struttura, styNormal)
        tipologia = Paragraph(
            "<b>Tipologia</b><br/>" + self.tipologia_struttura, styNormal)
        definizione = Paragraph(
            "<b>Definizione</b><br/>" + self.definizione_struttura, styNormal)

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

        interpretazione = ''
        try:
            interpretazione = Paragraph(
                "<b>Interpretazione</b><br/>" + str(self.interpretazione),
                styDescrizione)
        except:
            pass

        #4 row
        periodizzazione = Paragraph("<b>PERIODIZZAZIONE</b></b>", styNormal)

        #5 row
        iniziale = Paragraph("<b>INIZIALE</b>", styNormal)
        if self.periodo_iniziale == "None":
            periodo_iniziale = Paragraph("<b>Periodo</b><br/>", styNormal)
        else:
            periodo_iniziale = Paragraph(
                "<b>Periodo</b><br/>" + self.periodo_iniziale, styNormal)
        if self.fase_iniziale == "None":
            fase_iniziale = Paragraph("<b>Fase</b><br/>", styNormal)
        else:
            fase_iniziale = Paragraph("<b>Fase</b><br/>" + self.fase_iniziale,
                                      styNormal)

        finale = Paragraph("<b>FINALE</b>", styNormal)

        if self.periodo_finale == "None":
            periodo_finale = Paragraph("<b>Periodo</b><br/>", styNormal)
        else:
            periodo_finale = Paragraph(
                "<b>Periodo</b><br/>" + self.periodo_finale, styNormal)
        if self.fase_finale == "None":
            fase_finale = Paragraph("<b>Fase</b><br/>", styNormal)
        else:
            fase_finale = Paragraph("<b>Fase</b><br/>" + self.fase_finale,
                                    styNormal)

        #6 row
        datazione_estesa = Paragraph(
            "<b>DATAZIONE ESTESA</b><br/>" + self.datazione_estesa, styNormal)

        #7 row
        materiali_impiegati = ''
        if ast.literal_eval(self.materiali_impiegati) > 0:
            for i in ast.literal_eval(self.materiali_impiegati):
                if materiali_impiegati == '':
                    try:
                        materiali_impiegati += ("%s") % (str(i[0]))
                    except:
                        pass
                else:
                    try:
                        materiali_impiegati += (", %s") % (str(i[0]))
                    except:
                        pass

        materiali_impiegati = Paragraph(
            "<b>Materiali impiegati</b><br/>" + materiali_impiegati, styNormal)

        #8 row
        elementi_strutturali = ''
        if ast.literal_eval(self.elementi_strutturali) > 0:
            for i in ast.literal_eval(self.elementi_strutturali):
                if elementi_strutturali == '':
                    try:
                        elementi_strutturali += (
                            "Tipologia elemento: %s, quantita: %s") % (str(
                                i[0]), str(i[1]))
                    except:
                        pass
                else:
                    try:
                        elementi_strutturali += (
                            "<br/>Tipologia elemento: %s, quantita: %s") % (
                                str(i[0]), str(i[1]))
                    except:
                        pass

        elementi_strutturali = Paragraph(
            "<b>Elementi strutturali</b><br/>" + elementi_strutturali,
            styNormal)

        #9 row
        rapporti_struttura = ''
        if ast.literal_eval(self.rapporti_struttura) > 0:
            for i in ast.literal_eval(self.rapporti_struttura):
                if rapporti_struttura == '':
                    try:
                        rapporti_struttura += (
                            "Tipo rapporto: %s, sito: %s, sigla: %s, nr.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(i[3]))
                    except:
                        pass
                else:
                    try:
                        rapporti_struttura += (
                            "<br/>Tipo rapporto: %s, sito: %s, sigla: %s, nr.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(i[3]))
                    except:
                        pass

        rapporti_struttura = Paragraph(
            "<b>Rapporti struttura</b><br/>" + rapporti_struttura, styNormal)

        #10 row
        misure_struttura = ''
        if ast.literal_eval(self.misure_struttura) > 0:
            for i in ast.literal_eval(self.misure_struttura):
                if misure_struttura == '':
                    try:
                        misure_struttura += ("Tipo di misura: %s = %s %s") % (
                            str(i[0]), str(i[2]), str(i[1]))
                    except:
                        pass
                else:
                    try:
                        misure_struttura += (
                            "<br/>Tipo di misura: %s = %s %s") % (str(
                                i[0]), str(i[2]), str(i[1]))
                    except:
                        pass

        misure_struttura = Paragraph(
            "<b>Misurazioni</b><br/>" + misure_struttura, styNormal)

        #19 row
        quote_struttura = Paragraph("<b>QUOTE</b><br/>", styNormal)

        #20 row
        quota_min = Paragraph("<b>Quota min</b><br/>" + str(self.quota_min),
                              styNormal)
        quota_max = Paragraph("<b>Quota max</b><br/>" + str(self.quota_max),
                              styNormal)

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],  #0 row ok
            [
                sito, '01', '02', '03', '04', '05', '06', '07',
                sigla_struttura, '09'
            ],  #1 row ok
            [
                categoria, '01', '02', '03', tipologia, '05', '06', '07',
                definizione, '09'
            ],  #2 row ok
            [
                descrizione, '01', '02', '03', '04', interpretazione, '06',
                '07', '08', '09'
            ],  #3 row ok
            [
                periodizzazione, '02', '03', '04', '05', '06', '06', '07',
                '08', '09'
            ],  #4 row
            [
                iniziale, '01', periodo_iniziale, '03', fase_iniziale, finale,
                '06', periodo_finale, '08', fase_finale
            ],  #5 row
            [
                datazione_estesa, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #6 row
            [
                rapporti_struttura, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #7 row
            [
                materiali_impiegati, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #8 row
            [
                elementi_strutturali, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #9 row
            [
                misure_struttura, '01', '02', '03', '04', '05', '06', '07',
                '08', '09'
            ],  #10 row
            [
                quote_struttura, '01', '02', '03', '04', '07', '06', '07',
                '08', '09'
            ],  #19 row ok
            [quota_min, '01', '02', '03', quota_max, '06', '07', '08',
             '09']  #20 row ok
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione

            #1 row
            ('SPAN', (0, 1), (7, 1)),  #dati identificativi
            ('SPAN', (8, 1), (9, 1)),  #dati identificativi

            #2 row
            ('SPAN', (0, 2), (3, 2)),  #Definizione - interpretazone
            ('SPAN', (4, 2), (7, 2)),  #definizione - intepretazione
            ('SPAN', (8, 2), (9, 2)),  #definizione - intepretazione

            #3 row
            ('SPAN', (0, 3), (4, 3)),  #conservazione - consistenza - colore
            ('SPAN', (5, 3), (9, 3)),  #conservazione - consistenza - colore

            #4 row
            ('SPAN', (0, 4), (9, 4)),  #inclusi - campioni - formazione

            #5 row
            ('SPAN', (0, 5), (1, 5)),  #iniziale
            ('SPAN', (2, 5), (3, 5)),  #periodo inizlae
            ('SPAN', (5, 5), (6, 5)),  #fase iniziale
            ('SPAN', (7, 5), (8, 5)),  #finale
            ('VALIGN', (0, 5), (0, 5), 'TOP'),
            ('VALIGN', (5, 5), (5, 5), 'TOP'),

            #6 row
            ('SPAN', (0, 6), (9, 6)
             ),  #Attivita - Struttura - Quota min - Quota max

            #7 row
            ('SPAN', (0, 7), (9, 7)
             ),  #Attivita - Struttura - Quota min - Quota max

            #8 row
            ('SPAN', (0, 8), (9, 8)
             ),  #Attivita - Struttura - Quota min - Quota max

            #9 row
            ('SPAN', (0, 9), (9, 9)
             ),  #Attivita - Struttura - Quota min - Quota max

            #10 row
            ('SPAN', (0, 10), (9, 10)
             ),  #Attivita - Struttura - Quota min - Quota max

            #10 row
            ('SPAN', (0, 11), (9, 11)
             ),  #Attivita - Struttura - Quota min - Quota max

            #10 row
            ('SPAN', (0, 12), (3, 12)),  #conservazione - consistenza - colore
            ('SPAN', (4, 12), (9, 12)),  #conservazione - consistenza - colore
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

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

        return t