Example #1
0
    def genPrintLabelPDFs(self, labelDataInput, defaultFileName = None, returnBytes = False):
        """labelDataInput = list of dictionaries formatted as: {DWC Column:'field value'}
           defaultFileName = the filename to use as the default when saving the pdf file.
           returnBytes = If the result should be a bytes object (used for label previews).
           Otherwise, produces (and attempts to open) a pdf file."""

        # strip out the site number rows
        try:
            labelDataInput = [x for x in labelDataInput if x.get('specimenNumber') != "#"]
        except AttributeError:
            labelDataInput = [x for x in labelDataInput if "#" not in x.get('recordNumber').split('-')[-1]]
        if len(labelDataInput) < 1:  # exit early if nothing is left
            return None

        # decent default values 140, 90
        self.xPaperSize = int(self.settings.get('value_X', 140)) * mm
        self.yPaperSize = int(self.settings.get('value_Y', 90)) * mm
        self.relFont = int(self.settings.get('value_RelFont', 12))
         # TODO explore adding font options which are already bundled with reportlab
        self.fontName = self.settings.get('value_fontName', 'Helvetica')
         
        self.allowSplitting = 0
        self.xMarginProportion = 0
        self.yMarginProportion = 0   #Padding on tables are functionally the margins in our use. (We're claiming most of paper)
        self.xMargin = self.xMarginProportion * self.xPaperSize        #Margin set up (dynamically depending on paper sizes.
        self.yMargin = self.xMarginProportion * self.yPaperSize
        self.customPageSize = (self.xPaperSize, self.yPaperSize)
        
        # check some of the optional label settings, & make adjustments.
        additionalData = {}
        if self.settings.get('value_inc_VerifiedBy'):
            additionalData['verifiedBy'] = self.settings.get('value_VerifiedBy')
        else:
            additionalData['verifiedBy'] = ''
        if self.settings.get('value_inc_CollectionName'):
            additionalData['collectionName'] = self.settings.get('value_CollectionName')
        else:
            additionalData['collectionName'] = ''
        # setting these now, to avoid redundant .get calls.
        incAssociated = self.settings.get('value_inc_Associated')
        maxAssociated = int(self.settings.get('value_max_Associated'))
        if not incAssociated:
            additionalData['associatedTaxa'] = ''
        for rowData in labelDataInput:
           if incAssociated:
                associatedTaxa = rowData['associatedTaxa']
                associatedTaxaItems = associatedTaxa.split(', ')
                if len(associatedTaxaItems) > maxAssociated: #if it is too large, trunicate it, and append "..." to indicate trunication.
                    associatedTaxa =  ', '.join(associatedTaxaItems[:maxAssociated])+' ...'
                    rowData['associatedTaxa'] = associatedTaxa
                for key, value in additionalData.items():
                    rowData[key] = value

        tableSty = [                                    #Default table style
                ('LEFTPADDING',(0,0),(-1,-1), 0),
                ('RIGHTPADDING',(0,0),(-1,-1), 0),
                ('TOPPADDING',(0,0),(-1,-1), 0),
                ('BOTTOMPADDING',(0,0),(-1,-1), 0)]
    
        #helper functions to keep the 'flowables' code more legible.
    
        def Para(textField1,styleKey,prefix = '',suffix = ''):
            if len(dfl(textField1)) > 0 :                #If the field has a value insert it, otherwise blank row
                return Paragraph(('<b>{}</b>'.format(prefix)) + dfl(textField1) + suffix,style = self.stylesheet(styleKey))
            else:
                return Paragraph('', style = self.stylesheet(styleKey))
    
        def verifiedByPara(textField1,styleKey):
            if len(dfl(textField1)) > 0 :                #If the field has a value insert it, otherwise blank row
                return Paragraph('<i>Verified by {}</i>'.format(dfl(textField1)),style = self.stylesheet(styleKey))
            else:
                return Paragraph('', style = self.stylesheet(styleKey))
    
        def sciName(textfield1,textfield2,styleKey,prefix = ''):
            if len(dfl(textfield1)) > 0 :
                return Paragraph(('<i>{}</i>'.format(dfl(textfield1))) + ' ' + dfl(textfield2),style = self.stylesheet(styleKey))
            else:
                return Paragraph('', style = self.stylesheet(styleKey))
    
        def collectedByPara(textfield1,textfield2,styleKey,prefix = ''):
            # break out the textValues
            textContent1 = dfl(textfield1)
            textContent2 = dfl(textfield2)
            
            if textContent1 != '': #  if textContent has content
                if ('|' in textfield1) & (textfield2 == ''): #  if it has a |
                    splitCollectors = textContent1.split('|',1) # split on |
                    #  if it is a list & it has 2 elements, assign them 
                    if len(splitCollectors) == 2:
                        textContent1, textContent2 = splitCollectors
            elif textContent2 != '':
                # if there is no primariy collector, but there are associated collector(s)
                if ('|' in textfield2):
                    splitCollectors = textContent2.split('|',1) # split on |
                    if len(splitCollectors) == 2:
                        textContent1, textContent2 = splitCollectors
            # condition of remaining collectors in textContent2 delimited by |
            if '|' in textContent2:
                #  split on | delimiter
                splitCollectors = textContent2.split('|')
                #  strip out trailing/leading spaces and empty strings.
                splitCollectors = [x.strip() for x in splitCollectors if x != '']
                #  rejoin as single, cleaned string.
                splitCollectors = ', '.join(splitCollectors)
                        
            if (isinstance(textContent1, str) & (textContent1 != '') & (textContent2 != '')):
                return Paragraph(('<b>{}</b>'.format(prefix)) + textContent1 + ' with ' + textContent2, style = self.stylesheet(styleKey))
            elif (isinstance(textContent1, str) & (textContent1 != '')):
                return Paragraph(('<b>{}</b>'.format(prefix)) + textContent1, style = self.stylesheet(styleKey))
            else:
                return Paragraph('', style = self.stylesheet(styleKey))

        def cultivationStatusChecker(textfield1, styleKey):
            if str(dfl(textfield1)) == 'cultivated':
                return Paragraph('<b>Cultivated specimen</b>', style = self.stylesheet(styleKey))
            else:
                return Paragraph('', style = self.stylesheet('default'))
            
        def gpsCoordStringer(textfield1,textfield2,textfield3,textfield4,styleKey):
            gpsString = []
            if len(dfl(textfield1)) > 0 :
                if (dfl(textfield1) and dfl(textfield2)):
                    # min([len(dfl(textfield1)),len(dfl(textfield2))]) testing length control.
                    gpsString.append('<b>GPS: </b>' + dfl(textfield1) + ', ' + dfl(textfield2))
                if dfl(textfield3):
                    gpsString.append(' ± ' + str(round(float(dfl(textfield3)),0)).split('.')[0] + 'm')
                if dfl(textfield4):
                    gpsString.append(', <b>Elevation: </b>' + dfl(textfield4) + 'm')
    
                return Paragraph(''.join(gpsString), style = self.stylesheet(styleKey))

        def newHumanText(self):
            return self.stop and self.encoded[1:-1] or self.encoded
    
        def createBarCodes():   #Unsure of the benefits downsides of using extended vs standard?
            if len(dfl('catalogNumber')) > 0:
                barcodeValue = dfl('catalogNumber')
            else:
                barcodeValue =  self.settings.dummyCatNumber
            if barcodeValue:
                code39._Code39Base._humanText = newHumanText  #Note, overriding the human text from this library to omit the stopcode ('+')
                barcode39Std = code39.Standard39(barcodeValue,barHeight=(self.yPaperSize * .10  ), barWidth=((self.xPaperSize * 0.28)/(len(barcodeValue)*13+35)), humanReadable=True, quiet = False, checksum=0)
                                                 #^^^Note width is dynamic, but I don't know the significe of *13+35 beyond making it work.
                return barcode39Std
            else:
                return ''
        elements = []      # a list to dump the flowables into for pdf generation
        for labelFieldsDict in labelDataInput:
            def dfl(key):                       # dict lookup helper function
                value = labelFieldsDict.get(key,'') # return empty string if no result from lookup.
                return str(value)

        #Building list of flowable elements below
            if (len(dfl('catalogNumber')) > 0) | (self.settings.dummyCatNumber != False):
                row0 = Table([[
                    Para('collectionName','collectionNameSTY'),
                    createBarCodes()
                              ]],
                colWidths = (self.xPaperSize * .67,self.xPaperSize * .29), rowHeights = None,
    
                style = [
                        ('VALIGN',(0,0),(0,-1),'TOP'),
                        ('ALIGN',(0,0),(0,0),'LEFT'),
                        ('ALIGN',(1,0),(1,0),'RIGHT'),
                         ])
            else:
                row0 = Para('collectionName','collectionNameSTY')
                    
    
            row1 = Table([
                [Para('labelProject','labelProjectSTY')],
                [verifiedByPara('verifiedBy','verifiedBySTY')]],
                         colWidths = self.xPaperSize *.98, rowHeights = None,
                         style = [
                        ('BOTTOMPADDING',(0,0),(-1,-1), 2)]
                         )
    #bookmark
    #ScientificName Row Dynamic Formatting
        
            scientificNameElement = sciName('scientificName','scientificNameAuthorship','sciNameSTY')
            try:            #Test if Scienftific Name can Share a row with Event Date.
                scientificNameElement.wrap(1400, 1400) #Test wrap the string in a large environment to get it's desired ideal width.
                sciNameParaWidth = scientificNameElement.getActualLineWidths0()[0]
                sciHeight = scientificNameElement.height
            
            except (AttributeError, IndexError) as e:
                sciNameParaWidth = 0
                sciHeight = 0
    
            if sciNameParaWidth > self.xPaperSize *.96:  #If the string is so large as to not fit, even alone then shrink font and split lines into two rows.
                row2 = Table([[
                    Para('eventDate','dateSTY')],
                    [Spacer(width = self.xPaperSize *.98, height = sciHeight)], #Add spacer between rows for formatting.
                    [sciName('scientificName','scientificNameAuthorship','sciNameSTYSmall')]],
                        colWidths = self.xPaperSize *.98 , rowHeights = None, style = tableSty)
                    
            elif sciNameParaWidth > self.xPaperSize * -1:   #If the string is too big to share row with event date, split lines into rows.
                row2 = Table([[
                    Para('eventDate','dateSTY')],
                    [Spacer(width = self.xPaperSize *.98, height = sciHeight)],  #Add spacer between rows for formatting.
                    [sciName('scientificName','scientificNameAuthorship','sciNameSTY')]],
                        colWidths = self.xPaperSize *.98, rowHeights = None, style = tableSty)               
            else:
                row2 = Table([[
                    sciName('scientificName','scientificNameAuthorship','sciNameSTY'),
                    Para('eventDate','dateSTY')]],
                        colWidths = (self.xPaperSize * .80,self.xPaperSize * .18),
                        rowHeights = None, style = tableSty)
    
            row3 = Table([[
                    Para('locality','default')]],
                         rowHeights=None, style = tableSty)
    
            #Associated Taxa Dynamic Formatting
            if dfl('associatedTaxa') == '':         #If associated taxa is not used, give up the y space.
                associatedTaxaHeight = 0
                associatedTaxaStyle = 'defaultSTYSmall'   #This entire block is not functioning the way it was planned to.
            else:
                associatedTaxaHeight = .15 * self.yPaperSize          #Otherwise, devote some space, then test it's useage.
                associatedTaxaElement = Para('associatedTaxa','default','Associated taxa: ') #Test build for height
                try:
                    associatedTaxaParaHeight = associatedTaxaElement.wrap(self.xPaperSize *.98, 1)[1] #Test wrap the string in a large environment to get necessary height.
                except (AttributeError, IndexError) as e:
                    print('error ',e)
                    associatedTaxaParaHeight = 0
    
                if associatedTaxaParaHeight > associatedTaxaHeight:  #If the string is too large, reduce the font size.
                    associatedTaxaStyle = 'defaultSTYSmall'
                else:
                    associatedTaxaStyle = 'default'             #otherwise, use the normal height
            row4 = Table([[
                Para('associatedTaxa',associatedTaxaStyle,'Associated taxa: ')]],
                rowHeights=None,
                style = tableSty)
    #Note, associatedTaxa only reduces size if it is too large. At some extream point we'll need to consider trunication.
            
            if dfl('individualCount') != '':
                row5 = Table([[
                    Para('habitat','default','Habitat: '),
                    Para('individualCount','rightSTY', 'Approx. ≥ ',' on site.')]],
                    colWidths = (self.xPaperSize * .68,self.xPaperSize * .30), rowHeights = None,
                    style = [
                        ('VALIGN',(1,0),(1,0),'CENTER'),
                        ('ALIGN',(0,0),(0,0),'LEFT'),
                        ('ALIGN',(1,0),(1,0),'RIGHT'),
                        ('LEFTPADDING',(0,0),(-1,-1), 0),
                        ('RIGHTPADDING',(0,0),(-1,-1), 0),
                        ('TOPPADDING',(0,0),(-1,-1), 0),
                        ('BOTTOMPADDING',(0,0),(-1,-1), 0)])
            else:
                row5 = Table([[
                    Para('habitat','default','Habitat: ')]], style=tableSty)
    
            if dfl('establishmentMeans') == 'cultivated':  #If establishmentMeans status is not 'cultivated' (based on cultivated status in mobile app) then forfit the space in case Substrate field is long.
                row6 = Table([[
                Para('substrate','default','Substrate: '),
                cultivationStatusChecker('establishmentMeans','rightSTY')]],    
                colWidths = (self.xPaperSize * .68,self.xPaperSize * .30), rowHeights = None,
                style=tableSty)
                
            else:
                row6 = Table([[
                Para('substrate','default','Substrate: ')]],style=tableSty)
    
            row7 = [collectedByPara('recordedBy','associatedCollectors','default','Collected by: ')]
    
            row6_5 = Table([[
                Para('locationRemarks','default','Location Remarks: ')]],style=tableSty)
          #Note locationRemarks is in testing, may not stay!
    
            row6_7 = Table([[
                        Para('occurrenceRemarks','default','Occurence Remarks: ')]],style=tableSty)
                
            if dfl('identifiedBy') != '':
                row7_5 = Table([[
                        Para('identifiedBy','default','Determined by: ')]],style=tableSty)
            # TODO: Add all tableList (row) objects to a loop which checks for content and appends else returns None 
            # ...  Then Clean tableList for None objects
            
            tableList = [[row0],
                          [row1],
                          [row2],
                          [row3],
                          [row4],
                          [row5],
                          [row6],
                          [row6_5],
                          [row6_7],
                          [row7]]
    
            #Testing if GPS String can fit on one row with the field number. If not, split them into two rows.
            gpsStrElement = gpsCoordStringer('decimalLatitude', 'decimalLongitude', 'coordinateUncertaintyInMeters', 'minimumElevationInMeters','rightSTYSmall')
            try:
                gpsStrElement.wrap(self.xPaperSize * .98 , self.yPaperSize * .98)
                try:
                    gpsParaWidth = gpsStrElement.getActualLineWidths0()[0]
                except IndexError:
                    gpsParaWidth = 0
            except AttributeError:
                gpsParaWidth = 0
                
            if gpsParaWidth > self.xPaperSize * .65:
                row8 = Table([[Para('recordNumber','default','Field Number: ')]], style = tableSty)
                row9 = Table([[gpsStrElement]],style = tableSty)
                tableList.append([row8])
    
                if dfl('identifiedBy') != '':
                    tableList.append([row7_5])
    
                tableList.append([row9])
                
            else:
                row8 = Table([[
                Para('recordNumber','default','Field Number: '),        
                gpsStrElement]],            
                colWidths = (self.xPaperSize * .33, self.xPaperSize * .65), rowHeights = None,style=tableSty)
                tableList.append([row8])
    
                if dfl('identifiedBy') != '':
                    tableList.append([row7_5])
    
            # append the determined by field
            
            
            docTableStyle = [                             #Cell alignment and padding settings (not text align within cells)
                    ('VALIGN',(0,3),(0,-1),'BOTTOM'),     #Rows 4-end align to bottom
                    ('ALIGN',(0,0),(-1,-1),'CENTER'),     #All rows align to center
                    ('LEFTPADDING',(0,0),(-1,-1), 0),     #ALL Rows padding on left to none
                    ('RIGHTPADDING',(0,0),(-1,-1), 0),    #ALL Rows padding on right to none
                    ('TOPPADDING',(0,0),(-1,-1), 3),      #ALL Rows padding on top to none
                    ('BOTTOMPADDING',(0,0),(-1,-1), 0),   #ALL Rows padding on Bottom to none
                    ('BOTTOMPADDING',(0,0),(0,0), 3),     #ALL Rows padding on Bottom to none
                    ('TOPPADDING',(0,1),(0,1), 6),        #Row 2 top padding to 6
                    ('TOPPADDING',(0,2),(0,2), 6),        #Row 3 top padding to 6
                    ('BOTTOMPADDING',(0,2),(0,2), 6),     #Row 3 bottom padding to 6
                    #('NOSPLIT', (0,0),(-1,-1)),          #Makes Error if it won't fit. We should raise this error to user!
                                ]
            
            docTable = Table(tableList, style = docTableStyle ) #build the table to test it's height
    
            wid, hei = docTable.wrap(0, 0)      #Determines how much space is used by the table
            spaceRemaining = (self.yPaperSize - hei - 10) #Determine how much is left on the page
            spaceFiller = [Spacer(width = 0, height = (spaceRemaining/3))] #assign half the remaining space to a filler (to distrib into two places.
            tableList.insert(4,spaceFiller)     #build from bottom up because it is less confusing for the index values.
            tableList.insert(3,spaceFiller)
            tableList.insert(2,spaceFiller)
    
            docTable = Table(tableList, style = docTableStyle ) #build the final table
    
            #Add the flowables to the elements list.
            elements.append(docTable)
            elements.append(PageBreak())

        #Build the base document's parameters.
        
        if returnBytes:  # if we only want to make a preview save it to a stream
            byteStream = io.BytesIO()
            labelFileName = byteStream

        elif defaultFileName:
            labelFileName = defaultFileName
            #labelFileName, _ = QFileDialog.getSaveFileName(None, 'Save Label PDF', defaultFileName, 'PDF(*.pdf)')
        else:
            labelFileName, _ = QFileDialog.getSaveFileName(None, 'Save Label PDF', os.getenv('HOME'), 'PDF(*.pdf)')

        if not labelFileName:  # If the user canceled the dialog
            return
        # TODO fill in title and author based on select form_view or settings info                
        doc = BaseDocTemplate(labelFileName,
                              pagesize=self.customPageSize,
                              pageTemplates=[],
                              showBoundary=0,
                              leftMargin=self.xMargin,
                              rightMargin=self.xMargin,
                              topMargin=self.yMargin,
                              bottomMargin=self.yMargin,
                              allowSplitting= self.allowSplitting,           
                              title=None,
                              author=None,
                              _pageBreakQuick=1,
                              encrypt=None)
    
        #Function to build the pdf
    
        def build_pdf(flowables):
            """ actually loads the flowables into the document """

            doc.addPageTemplates(
                [
                    PageTemplate(
                        onPage = self.labelSetup,
                        frames=[
                            platypusFrame(
                                doc.leftMargin,
                                doc.bottomMargin,
                                doc.width,
                                doc.height,
                                topPadding=0,
                                bottomPadding=0,
                                id=None
                            ),
                        ]
                    ),
                ]
            )
            try:
                doc.build(flowables)
            except LayoutError:
                raise LayoutError
        
        try:
            build_pdf(elements)
        except LayoutError:
            # if there is a layout error, raise it
            raise LayoutError
        
        if returnBytes:  # If a preview is being generated just return the bytes
            # calling the byte stream "labelFileName" is a fast and dirty 
            # workaround to keep existing code functional
            pdfBytes = labelFileName.getvalue()  # save the stream to a variable
            labelFileName.close()  # close the buffer down
            return pdfBytes  # return the results
        
        #Open the file after it is built (maybe change/remove this later? Idealy, a preview or something
    
        def open_file(filename):
            if sys.platform == "win32":
                os.startfile(filename)
            else:
                opener ="open" if sys.platform == "darwin" else "xdg-open"
                subprocess.call([opener, filename])
        open_file(labelFileName)
Example #2
0
    def _build(self, availWidth, availHeight):
        _tempEntries = self._getlastEntries()

        def getkey(seq):
            return [x.upper() for x in seq[0]]

        _tempEntries.sort(key=getkey)
        #was: _tempEntries.sort(lambda a,b: cmp([x.upper() for x in a[0]], [x.upper() for x in b[0]]))
        leveloffset = self.headers and 1 or 0

        def drawIndexEntryEnd(canvas, kind, label):
            '''Callback to draw dots and page numbers after each entry.'''
            style = self.getLevelStyle(leveloffset)
            pages = loads(decodestring(label))
            drawPageNumbers(canvas, style, pages, availWidth, availHeight,
                            self.dot)

        self.canv.drawIndexEntryEnd = drawIndexEntryEnd

        alpha = ''
        tableData = []
        lastTexts = []
        alphaStyle = self.getLevelStyle(0)
        for texts, pageNumbers in _tempEntries:
            texts = list(texts)
            #track when the first character changes; either output some extra
            #space, or the first letter on a row of its own.  We cannot do
            #widow/orphan control, sadly.
            nalpha = texts[0][0].upper()
            if alpha != nalpha:
                alpha = nalpha
                if self.headers:
                    header = alpha
                else:
                    header = ' '
                tableData.append([
                    Spacer(1, alphaStyle.spaceBefore),
                ])
                tableData.append([
                    Paragraph(header, alphaStyle),
                ])
                tableData.append([
                    Spacer(1, alphaStyle.spaceAfter),
                ])

            i, diff = listdiff(lastTexts, texts)
            if diff:
                lastTexts = texts
                texts = texts[i:]
            label = encodestring(dumps(list(pageNumbers))).strip()
            texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (
                texts[-1], label)
            for text in texts:
                #Platypus and RML differ on how parsed XML attributes are escaped.
                #e.g. <index item="M&S"/>.  The only place this seems to bite us is in
                #the index entries so work around it here.
                text = escapeOnce(text)

                style = self.getLevelStyle(i + leveloffset)
                para = Paragraph(text, style)
                if style.spaceBefore:
                    tableData.append([
                        Spacer(1, style.spaceBefore),
                    ])
                tableData.append([
                    para,
                ])
                i += 1

        self._flowable = Table(tableData,
                               colWidths=[availWidth],
                               style=self.tableStyle)
Example #3
0
def generar_pdf(request, ubigeo):
    print "generar_pdf"
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = "attachment; filename=" + ubigeo + "001" + ".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

    Z1 = Paragraph(
        "<strong>OBSERVACIONES: .............................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "................................................................................</strong>",
        h_obser)

    table_obs = Table(data=[[Z1]],
                      colWidths=[18.8 * cm],
                      rowHeights=[2 * cm],
                      style=[('GRID', (0, 0), (-1, -1), 1, colors.black)])

    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')])

    x = 0

    caso = Seg_R_Secc_Ccpp.objects.filter(ubigeo=ubigeo)[0:1]

    for aeu_v in caso:
        idaer = aeu_v.idaer
        idscr = aeu_v.idscr

        secc_ini = idscr[6:8]
        secc_fin = idscr[8:10]

        aer_ini = idaer[6:9]
        aer_fin = idaer[9:12]

        print idaer
        print idscr

        x = x + 1

        lista_distritos = []
        lista_distritos.append(ubigeo)

        for ubigein in range(len(lista_distritos)):

            if os.path.exists(
                    "\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" +
                    str(ubigeo)) == False:
                os.mkdir("\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" +
                         str(ubigeo))

        # pdf = "{}-{}-{}.pdf".format(ubigeo, idscr[6:8], idscr[8:10])
        #
        # print pdf

        destino = "\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" + str(
            ubigeo) + "\\" + str(ubigeo) + ".pdf"

        print destino

        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)+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)

        viviendas_totales = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).order_by('idscr', 'idaer', 'codccpp')

        total_secc_ini = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).values_list('scr_ini', flat=True)

        total_secc_fin = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).values_list('scr_fin', flat=True)

        cuchi_one = list(set(total_secc_ini))
        cuchi_two = list(set(total_secc_fin))

        secc_ini = min(cuchi_one)
        secc_fin = max(cuchi_two)

        total_aer_ini = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).values_list('aer_ini', flat=True)

        total_aer_fin = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).values_list('aer_fin', flat=True)

        cuchi_aer_one = list(set(total_aer_ini))
        cuchi_aer_two = list(set(total_aer_fin))

        aer_ini = min(cuchi_aer_one)
        aer_fin = max(cuchi_aer_two)

        total_viv = 0
        for viviendon in viviendas_totales:
            total_viv = total_viv + viviendon.viv_ccpp

        data = [
            ['', '', '', '',
             Paragraph('<strong>Doc. CPV</strong>', h4), ''],
            [
                Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '',
                '', '',
                Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), ''
            ],
            [
                Paragraph('<strong>DEPARTAMENTO</strong>', h1),
                Paragraph(str(distrito.ccdd.ccdd), h_center),
                Paragraph(str(distrito.ccdd.departamento), h1), '',
                Paragraph('<strong>SECCIÓN Nº</strong>', h1),
                Paragraph('Del ' + secc_ini + ' Al ' + secc_fin, h1)
            ],
            [
                Paragraph('<strong>PROVINCIA</strong>', h1),
                Paragraph(distrito.ccpp, h_center),
                Paragraph(distrito.cod_prov.provincia, h1), '',
                Paragraph('<strong>AER Nº</strong>', h1),
                Paragraph('Del ' + aer_ini + ' Al ' + aer_fin, h1)
            ],
            [
                Paragraph('<strong>DISTRITO</strong>', h1),
                Paragraph(distrito.ccdi, h_center),
                Paragraph(distrito.distrito, h1), '', '', ''
            ],
            [
                '', '', '', '',
                Paragraph(
                    '<strong>C. TOTAL DE VIVIENDAS DEL DISTRITO.</strong>',
                    h1),
                Paragraph(str(total_viv), h1)
            ],
            #Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL AER.</strong>', h1)
        ]

        tables = Table(data,
                       colWidths=[
                           3.7 * cm, 1 * cm, 7.1 * cm, 0.3 * cm, 4.5 * cm,
                           2.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),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('GRID', (0, 1), (2, 4), 1, colors.black),
                ('GRID', (4, 5), (5, 5), 1, colors.black),
                ('GRID', (4, 1), (5, 3), 1, colors.black),
                ('GRID', (4, 3), (5, 3), 1, colors.black),
                ('SPAN', (0, 1), (2, 1)),
                ('SPAN', (4, 1), (5, 1)),
                ('BACKGROUND', (0, 1), (2, 1),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (0, 2), (0, 4),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (4, 1), (4, 3),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (4, 5), (4, 5),
                 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)),
            ]))

        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 ÁREAS DE EMPADRONAMIENTO RURAL DEL DISTRO</strong>",
            h_sub_tile_2)

        fichero_imagen_inei = 'Reporte/Img/inei.png'
        imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei),
                                 width=50,
                                 height=50)

        P2 = Paragraph('', styleBH)
        fichero_imagen = 'Reporte/Img/escudo.png'
        imagen_logo = Image(os.path.realpath(fichero_imagen),
                            width=50,
                            height=50)

        t1_croq = Paragraph(
            "<strong>CROQUIS DEL ÁREA DE EMPADRONAMIENTO URBANO</strong>",
            h_sub_tile_2)
        t = Table(
            data=[
                # ['', t1, ''],
                [[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),
            ])

        obs_data = [
            [
                Paragraph(e, h3) for e in [
                    "<strong>D. INFORMACIÓN DE LAS SECCIONES CENSALES Y ÁREAS DE EMPADRONAMIENTO DEL DISTRITO</strong>",
                    "", "", "", "", "", ""
                ]
            ],
            [
                Paragraph(e, h3) for e in [
                    "<strong>SECCIÓN Nº</strong>", "<strong>AER N°</strong>",
                    "", "<strong>CENTRO POBLADO</strong>", "", "",
                    "<strong>N° ESTIMADOS DE VIVIENDAS</strong>"
                ]
            ],
            [
                Paragraph(e, h3) for e in [
                    "", "<strong>INICIAL</strong>", "<strong>FINAL</strong>",
                    "<strong>CÓDIGO</strong>", "<strong>NOMBRE</strong>",
                    "<strong>CATEGORÍA</strong>", ""
                ]
            ],
        ]
        c = Table(obs_data,
                  colWidths=[
                      2 * cm, 1.7 * cm, 1.7 * cm, 1.7 * cm, 7.3 * cm, 2 * cm,
                      2.3 * cm
                  ],
                  rowHeights=[0.6 * cm, 1.1 * cm, 0.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', (0, 0), (6, 0)),
                ('SPAN', (1, 1), (2, 1)),
                ('SPAN', (3, 1), (5, 1)),
                ('SPAN', (0, 1), (0, 2)),
                ('SPAN', (6, 1), (6, 2)),
                ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            ]))

        i = 0

        data_croq = [
            ['', '', '', '',
             Paragraph('<strong>Doc. CPV</strong>', h4), ''],
            [
                Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '',
                '', '',
                Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), ''
            ],
            [
                Paragraph('<strong>DEPARTAMENTO</strong>', h1),
                Paragraph(str(distrito.ccdd.ccdd), h_center),
                Paragraph(str(distrito.ccdd.departamento), h1), '',
                Paragraph('<strong>SECCIÓN Nº</strong>', h1), ''
            ],
            [
                Paragraph('<strong>PROVINCIA</strong>', h1),
                Paragraph(distrito.ccpp, h_center),
                Paragraph(
                    str(distrito.cod_prov.provincia).decode('latin-1'), h1),
                '',
                Paragraph(str('<strong>A.E.R. Nº</strong>'), h1), ''
            ],
            [Paragraph('<strong>DISTRITO</strong>', h1), '', '', '', '', ''],
            [
                '', '', '', '',
                Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL AER.</strong>',
                          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([
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('ALIGN', (1, 2), (1, 4), 'CENTER'),
                ('GRID', (0, 0), (2, 3), 1, colors.black),
                ('GRID', (4, 5), (1, 3), 1, colors.black),
                ('SPAN', (0, 1), (2, 1)),
                ('SPAN', (0, 1), (2, 1)),
                ('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)),
            ]))

        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))

        # story.append(Spacer(0, 1 * mm))
        # story.append(table_obs)
        # story.append(PageBreak())

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

        viviendas = Vw_Seg_Esp_R_Secdist_Secc.objects.filter(
            ubigeo=ubigeo).order_by('idscr', 'idaer', 'codccpp')

        #toti_viv = int(Vw_Seg_Esp_R_Secdist_Secc.objects.filter(idscr=idscr).count())

        for vivienda in viviendas:
            if vivienda.categoria_o == None:
                categoria_o = ''
            else:
                categoria_o = vivienda.categoria_o
            i = i + 1
            # Bloque Listado

            table2 = [(str(vivienda.scr_ini).decode('latin-1'),
                       str(vivienda.aer_ini).decode('latin-1'),
                       str(vivienda.aer_fin).decode('latin-1'),
                       str(vivienda.codccpp).decode('latin-1'),
                       vivienda.nomccpp, str(categoria_o).decode('latin-1'),
                       str(vivienda.viv_ccpp).decode('latin-1'))]
            u = Table(table2,
                      colWidths=[
                          2 * cm, 1.7 * cm, 1.7 * cm, 1.7 * cm, 7.3 * cm,
                          2 * cm, 2.3 * cm
                      ],
                      rowHeights=[0.5 * 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), (6, 0), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ]))
            story.append(u)

    doc2.build(story)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
    def test2(self):
        chapters = 20  #so we know we use only one page
        from reportlab.lib.colors import pink

        #TOC and this HParagraph class just handle the collection
        TOC = []
        fontSize = 14
        leading = fontSize * 1.2
        descent = 0.2 * fontSize
        x = 2.5 * cm  #these come from the frame size
        y = (25 + 2.5) * cm - leading
        x1 = (15 + 2.5) * cm

        class HParagraph(Paragraph):
            def __init__(self, key, text, *args, **kwds):
                self._label = text
                self._key = key
                Paragraph.__init__(self, text, *args, **kwds)

            def draw(self):
                Paragraph.draw(self)
                TOC.append((self._label, self.canv.getPageNumber(), self._key))
                self.canv.bookmarkHorizontal('TOC_%s' % self._key, 0, +20)

        class UseForm(Flowable):
            _ZEROSIZE = 1

            def __init__(self, formName):
                self._formName = formName
                self.width = self.height = 0

            def draw(self):
                self.canv.doForm(self._formName)
                for i in range(chapters):
                    yb = y - i * leading  #baseline
                    self.canv.linkRect('',
                                       'TOC_%s' % i,
                                       (x, yb - descent, x1, yb + fontSize),
                                       thickness=0.5,
                                       color=pink,
                                       relative=0)

            def drawOn(self, canvas, x, y, _sW=0):
                Flowable.drawOn(self, canvas, 0, 0, canvas._pagesize[0])

        class MakeForm(UseForm):
            def draw(self):
                canv = self.canv
                canv.saveState()
                canv.beginForm(self._formName)
                canv.setFont("Helvetica", fontSize)
                for i, (text, pageNumber, key) in enumerate(TOC):
                    yb = y - i * leading  #baseline
                    canv.drawString(x, yb, text)
                    canv.drawRightString(x1, y - i * leading, str(pageNumber))
                canv.endForm()
                canv.restoreState()

        headerStyle = makeHeaderStyle(0)
        S = [Spacer(0, 180), UseForm('TOC')]
        RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY'.split(
        )
        for i in range(chapters):
            S.append(PageBreak())
            S.append(HParagraph(i, 'This is chapter %d' % (i + 1),
                                headerStyle))
            txt = xmlEscape(randomtext.randomText(RT[i * 13 % len(RT)], 15))
            para = Paragraph(txt, makeBodyStyle())
            S.append(para)

        S.append(MakeForm('TOC'))

        doc = MyDocTemplate(outputfile('test_platypus_toc_simple.pdf'))
        doc.build(S)
def generar_pdf(request, ubigeo, aer, aer_fin):
    print "generar_pdf"
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = "attachment; filename=" + ubigeo + "001" + ".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']]

    Z1 = Paragraph(
        "<strong>OBSERVACIONES: .............................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "................................................................................</strong>",
        h_obser)

    table_obs = Table(data=[[Z1]],
                      colWidths=[18.8 * cm],
                      rowHeights=[2 * cm],
                      style=[('GRID', (0, 0), (-1, -1), 1, colors.black)])

    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')])

    x = 0

    #caso = Seg_Esp_R_Aer.objects.filter(ubigeo=ubigeo, emp_aer=1, aer_ini_17= aer)                         #HABILITAR
    caso = Seg_Esp_R_Aer.objects.filter(ubigeo=ubigeo, aer_ini_17=aer)  #BORRAR

    for aeu_v in caso:
        idaer = aeu_v.idaer
        idscr = aeu_v.idscr

        print idaer
        print idscr

        cond = Vw_Seg_Esp_R_Aer.objects.filter(idaer=idaer)

        x = x + 1
        y = x
        lista_distritos = []
        lista_distritos.append(ubigeo)

        for ubigein in range(len(lista_distritos)):

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

        # for ubigein in range(tam_dis):
        #
        #     if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_esp\\" + str(lista_distritos[ubigein])) == False:
        #         os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_esp\\" + str(lista_distritos[ubigein]))
        #
        #     total_zonas = int(str(Tab_Aeus.objects.filter(ubigeo=lista_distritos[ubigein]).values_list('zona',flat=True).distinct().count()))
        #
        #     for zona_t in range(total_zonas):
        #         zoner = str(zona_t + 1).zfill(3) + "00"
        #         listin.append(str(lista_distritos[ubigein]) + ": " + zoner + "<br/>")
        #         if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_esp\\" + str(lista_distritos[ubigein]) + "\\" + zoner) == False:
        #             os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_esp\\" + str(lista_distritos[ubigein]) + "\\" + zoner)

        pdf = "{}-{}-{}-{}-{}.pdf".format(ubigeo, idscr[6:8], idscr[8:10],
                                          idaer[6:9], idaer[9:12])

        print pdf

        destino = "\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" + str(
            ubigeo) + "\\" + str(pdf)

        print destino
        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)+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)

        viviendas_totales = Vw_Seg_Esp_R_Aer.objects.filter(
            Q(idaer=idaer)).order_by('or_viv_aer')

        total_viv = 0

        secc = aeu_v.scr_ini
        aer = aeu_v.aer_ini_17

        print secc
        print aer
        for viviendon in viviendas_totales:
            total_viv = total_viv + 1

        data = [
            ['', '', '', '',
             Paragraph('<strong>Doc. CPV</strong>', h4), ''],
            [
                Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '',
                '', '',
                Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), ''
            ],
            [
                Paragraph('<strong>DEPARTAMENTO</strong>', h1),
                Paragraph(str(distrito.ccdd.ccdd), h_center),
                Paragraph(str(distrito.ccdd.departamento), h1), '',
                Paragraph('<strong>SECCIÓN Nº</strong>', h1),
                Paragraph('Del ' + secc + ' Al ' + secc, h1)
            ],
            [
                Paragraph('<strong>PROVINCIA</strong>', h1),
                Paragraph(distrito.ccpp, h_center),
                Paragraph(
                    str(distrito.cod_prov.provincia).decode('latin-1'), h1),
                '',
                Paragraph(str('<strong>A.E.R. Nº</strong>'), h1),
                Paragraph('Del ' + aer + ' Al ' + aer_fin, h1)
            ],
            [
                Paragraph('<strong>DISTRITO</strong>', h1),
                Paragraph(distrito.ccdi, h_center),
                Paragraph(distrito.distrito, h1), '', '', ''
            ],
            [
                '', '', '', '',
                Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL AER.</strong>',
                          h1),
                Paragraph(str(total_viv), h1)
            ],
        ]

        tables = Table(data,
                       colWidths=[
                           3.7 * cm, 1 * cm, 8.1 * cm, 0.3 * cm, 4.5 * cm,
                           2.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', (0, 1), (2, 4), 1, colors.black),
                ('GRID', (4, 5), (5, 6), 1, colors.black),
                ('GRID', (4, 1), (5, 3), 1, colors.black),
                ('SPAN', (0, 1), (2, 1)),
                ('SPAN', (4, 1), (5, 1)),
                ('BACKGROUND', (0, 1), (2, 1),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (0, 2), (0, 4),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (4, 2), (4, 3),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (4, 5), (4, 5),
                 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), (5, 1),
                 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 CENTROS POBLADOS Y VIVIENDAS DEL ÁREA DE EMPADRONAMIENTO RURAL</strong>",
            h_sub_tile_2)

        fichero_imagen_inei = 'Reporte/Img/inei.png'
        imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei),
                                 width=50,
                                 height=50)

        P2 = Paragraph('', styleBH)
        fichero_imagen = 'Reporte/Img/escudo.png'
        imagen_logo = Image(os.path.realpath(fichero_imagen),
                            width=50,
                            height=50)

        t1_croq = Paragraph(
            "<strong>CROQUIS DEL ÁREA DE EMPADRONAMIENTO URBANO</strong>",
            h_sub_tile_2)
        t = Table(
            data=[
                # ['', t1, ''],
                [[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),
                # ('SPAN', (0, 1), (2, 1)),
                # ('BOX', (0, 0), (1, -1), 2, colors.black),
                # ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
                # ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
                # ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                # ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                # ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                # ('BOX', (0, 0), (-1, -1), 2, colors.black),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
            ])

        obs_data = [
            [
                Paragraph(e, h3) for e in [
                    "<strong>D. INFORMACIÓN DE CENTROS POBLADOS Y VIVIENDAS</strong>",
                    "", "", "", "", "", "", "", "", ""
                ]
            ],
            [
                Paragraph(e, h3) for e in [
                    "<strong>Viv Nº</strong>",
                    "<strong>CENTRO POBLADO</strong>", "", "",
                    "<strong>DIRECCIÓN DE LA VIVIENDA</strong>", "", "", "",
                    "",
                    "<strong>Nombres y Apellidos del JEFE DE HOGAR</strong>"
                ]
            ],
            [
                Paragraph(e, h3) for e in [
                    "", "<strong>CÓD.</strong>", "<strong>Or. Reg.</strong>",
                    "<strong>Nombre</strong>", "<strong>Tipo de Vía</strong>",
                    "<strong>Nombre de Vía</strong>",
                    "<strong>N° de Puerta</strong>",
                    "<strong>Piso 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>"
                ]
            ],
        ]
        c = Table(obs_data,
                  colWidths=[
                      0.9 * cm, 1.1 * cm, 1 * cm, 3.8 * cm, 1.8 * cm, 2.4 * cm,
                      1.1 * cm, 1 * cm, 0.9 * cm, 5.8 * 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', (0, 0), (9, 0)),
                ('SPAN', (1, 1), (3, 1)),
                ('SPAN', (4, 1), (8, 1)),
                ('SPAN', (9, 1), (9, 2)),
                ('SPAN', (0, 1), (0, 2)),
                ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0),
                 colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            ]))

        i = 0

        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))

        # story.append(Spacer(0, 1 * mm))
        # story.append(table_obs)
        # story.append(PageBreak())

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

        viviendas = Vw_Seg_Esp_R_Aer.objects.filter(
            Q(idaer=idaer)).order_by('or_viv_aer')[0:32]

        total_viviendas = int(
            Vw_Seg_Esp_R_Aer.objects.filter(
                Q(idaer=idaer)).order_by('or_viv_aer').count())

        for vivienda in viviendas:

            i = i + 1
            # Bloque Listado
            table2 = [
                (str(vivienda.or_viv_aer).decode('latin-1'),
                 str(vivienda.codccpp).decode('latin-1'), vivienda.id_reg_or,
                 vivienda.nomccpp, vivienda.p20_nombre, vivienda.p21,
                 vivienda.p22_a, vivienda.p26, vivienda.p28, vivienda.p32)
            ]
            u = Table(table2,
                      colWidths=[
                          0.9 * cm, 1.1 * cm, 1 * cm, 3.8 * cm, 1.8 * cm,
                          2.4 * cm, 1.1 * cm, 1 * cm, 0.9 * cm, 5.8 * cm
                      ],
                      rowHeights=[0.5 * 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), (9, 0), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ]))
            story.append(u)

        # viviendas_second = Vw_Seg_Esp_R_Aer.objects.filter(Q(idaer=idaer)).order_by('or_viv_aer')[32:]
        #

        if total_viviendas > 33:
            #num_vuelt = total_viviendas/42
            #ini_val = 48
            #fin_val = 47

            #for i in range(num_vuelt):
            #ini = 32+ini_val
            #fin = 79+fin_val
            inicio = range(32, total_viviendas, 46)
            fin = range(80, total_viviendas, 46)
            nhojas = len(zip(inicio, fin))
            for i in range(nhojas):
                #inicio_val = range(32, total_viviendas, 48)
                #fin_val = range(79, total_viviendas, 48)
                story.append(c)
                viviendas_second = Vw_Seg_Esp_R_Aer.objects.filter(
                    Q(idaer=idaer)).order_by('or_viv_aer')[inicio[i]:fin[i]]
                for vivienda in viviendas_second:
                    #i = i + 1
                    # Bloque Listado
                    table2 = [
                        (str(vivienda.or_viv_aer).decode('latin-1'),
                         str(vivienda.codccpp).decode('latin-1'),
                         vivienda.id_reg_or, vivienda.nomccpp,
                         vivienda.p20_nombre, vivienda.p21, vivienda.p22_a,
                         vivienda.p26, vivienda.p28, vivienda.p32)
                    ]
                    u_second = Table(table2,
                                     colWidths=[
                                         0.9 * cm, 1.1 * cm, 1 * cm, 3.8 * cm,
                                         1.8 * cm, 2.4 * cm, 1.1 * cm, 1 * cm,
                                         0.9 * cm, 5.8 * cm
                                     ],
                                     rowHeights=[0.5 * 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), (9, 0), 7),
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ]))
                    story.append(u_second)
    #print story[4:]

    doc2.build(story)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
Example #6
0
    def test7(self):
        "Added some new side labelled pies"

        story = self.story
        story.append(Paragraph('Side Labelled Pie', h2))
        story.append(Spacer(0, 1 * cm))
        story.append(
            Paragraph('Here are two examples of side labelled pies.', bt))

        story.append(Spacer(0, 0.5 * cm))
        from reportlab.graphics.charts.piecharts import sample5, sample6, sample7, sample8, sample9
        drawing5 = sample5()
        story.append(drawing5)

        story.append(Spacer(0, 0.5 * cm))
        drawing9 = sample9()
        story.append(drawing9)
        story.append(Spacer(0, 1 * cm))

        story.append(Paragraph('Moving the pie', h3))
        story.append(
            Paragraph(
                'Here is a pie that has pie.x = 0 and is moved sideways in order to make space for the labels.',
                bt))
        story.append(Paragraph('The line represents x = 0', bt))
        story.append(
            Paragraph(
                'This has not been implemented and is on line 863 in piecharts.py',
                bt))

        story.append(Spacer(0, 0.5 * cm))
        drawing6 = sample6()
        story.append(drawing6)
        story.append(Spacer(0, 1 * cm))

        story.append(Paragraph('Case with overlapping pointers', h3))
        story.append(
            Paragraph(
                'If there are many slices then the pointer labels can end up overlapping as shown below.',
                bt))

        story.append(Spacer(0, 0.5 * cm))
        drawing7 = sample7()
        story.append(drawing7)
        story.append(Spacer(0, 1 * cm))

        story.append(Paragraph('Case with overlapping labels', h3))
        story.append(
            Paragraph(
                'Labels overlap if they do not belong to adjacent pie slices.',
                bt))

        story.append(Spacer(0, 0.5 * cm))
        drawing8 = sample8()
        story.append(drawing8)
        story.append(Spacer(0, 1 * cm))
        story.append(
            Paragraph(
                'The drawing is set as zero size, but the widget can still draw where you want it.',
                bt))

        def makeArrow(scale=0.2, boxAnchor='c', **kwds):
            A = AdjustableArrowDrawing()
            A.width = A.height = 0
            A._ZEROSIZE = True
            A.adjustableArrow.scale = scale
            A.adjustableArrow.boxAnchor = boxAnchor
            for k, v in kwds.items():
                setattr(A.adjustableArrow, k, v)
            return A

        A = makeArrow()
        bb = A.getBounds()
        deltax = 2 + max(bb[2] - bb[0], bb[3] - bb[1])
        for i, angle in enumerate((0, 10, 20, 60, 90, 120, 180, 270, 315)):
            story.append(
                makeArrow(y=-10,
                          x=deltax * i,
                          angle=angle,
                          strokeColor=colors.black,
                          strokeWidth=0.5,
                          headSweep=-i * 0.6))
        story.append(Spacer(0, 1 * cm))
Example #7
0
 def start(self, c):
     c.addPara()
     c.addStory(Spacer(1, self.attr.height))
Example #8
0
class GraphPdfDocBuilder0(PdfDocBuilder0):
    """A PDF document builder displaying widgets and drawings.

    This generates a PDF file where only methods named 'demo' are
    listed for any class C. If C happens to be a subclass of Widget
    and has a 'demo' method, this method is assumed to generate and
    return a sample widget instance, that is then appended graphi-
    cally to the Platypus story.

    Something similar happens for functions. If their names start
    with 'sample' they are supposed to generate and return a sample
    drawing. This is then taken and appended graphically to the
    Platypus story, as well.
    """

    fileSuffix = '.pdf'

    def begin(self, name='', typ=''):
        styleSheet = getSampleStyleSheet()
        self.code = styleSheet['Code']
        self.bt = styleSheet['BodyText']
        self.story = []

        # Cover page
        t = time.gmtime(time.time())
        timeString = time.strftime("%Y-%m-%d %H:%M", t)
        self.story.append(Paragraph('<font size=18>Documentation for %s "%s"</font>' % (typ, name), self.bt))
        self.story.append(Paragraph('<font size=18>Generated by: graphdocpy.py version %s</font>' %  __version__, self.bt))
        self.story.append(Paragraph('<font size=18>Date generated: %s</font>' % timeString, self.bt))
        self.story.append(Paragraph('<font size=18>Format: PDF</font>', self.bt))
        self.story.append(PageBreak())

        # Table of contents
        toc = TableOfContents()
        self.story.append(toc)
        self.story.append(PageBreak())


    def end(self, fileName=None):
        if fileName:  # overrides output path
            self.outPath = fileName
        elif self.packageName:
            self.outPath = self.packageName + self.fileSuffix
        elif self.skeleton:
            self.outPath = self.skeleton.getModuleName() + self.fileSuffix
        else:
            self.outPath = ''

        if self.outPath:
            doc = MyTemplate(self.outPath)
            doc.multiBuild(self.story)


    def beginModule(self, name, doc, imported):
        story = self.story
        bt = self.bt

        # Defer displaying the module header info to later...
        self.shouldDisplayModule = (name, doc, imported)
        self.hasDisplayedModule = 0


    def endModule(self, name, doc, imported):
        if self.hasDisplayedModule:
            DocBuilder0.endModule(self, name, doc, imported)


    def beginClasses(self, names):
        # Defer displaying the module header info to later...
        if self.shouldDisplayModule:
            self.shouldDisplayClasses = names


    # Skip all methods.
    def beginMethod(self, name, doc, sig):
        pass


    def endMethod(self, name, doc, sig):
        pass


    def beginClass(self, name, doc, bases):
        "Append a graphic demo of a Widget or Drawing at the end of a class."

        if VERBOSE:
            print 'GraphPdfDocBuilder.beginClass(%s...)' % name

        aClass = eval('self.skeleton.moduleSpace.' + name)
        if issubclass(aClass, Widget):
            if self.shouldDisplayModule:
                modName, modDoc, imported = self.shouldDisplayModule
                self.story.append(Paragraph(modName, self.makeHeadingStyle(self.indentLevel-2, 'module')))
                self.story.append(XPreformatted(modDoc, self.bt))
                self.shouldDisplayModule = 0
                self.hasDisplayedModule = 1
                if self.shouldDisplayClasses:
                    self.story.append(Paragraph('Classes', self.makeHeadingStyle(self.indentLevel-1)))
                    self.shouldDisplayClasses = 0
            PdfDocBuilder0.beginClass(self, name, doc, bases)
            self.beginAttributes(aClass)

        elif issubclass(aClass, Drawing):
            if self.shouldDisplayModule:
                modName, modDoc, imported = self.shouldDisplayModule
                self.story.append(Paragraph(modName, self.makeHeadingStyle(self.indentLevel-2, 'module')))
                self.story.append(XPreformatted(modDoc, self.bt))
                self.shouldDisplayModule = 0
                self.hasDisplayedModule = 1
                if self.shouldDisplayClasses:
                    self.story.append(Paragraph('Classes', self.makeHeadingStyle(self.indentLevel-1)))
                    self.shouldDisplayClasses = 0
            PdfDocBuilder0.beginClass(self, name, doc, bases)


    def beginAttributes(self, aClass):
        "Append a list of annotated attributes of a class."

        self.story.append(Paragraph(
            'Public Attributes',
            self.makeHeadingStyle(self.indentLevel+1)))

        map = aClass._attrMap
        if map:
            map = map.items()
            map.sort()
        else:
            map = []
        for name, typ in map:
            if typ != None:
                if hasattr(typ, 'desc'):
                    desc = typ.desc
                else:
                    desc = '<i>%s</i>' % typ.__class__.__name__
            else:
                desc = '<i>None</i>'
            self.story.append(Paragraph(
                "<b>%s</b> %s" % (name, desc), self.bt))
        self.story.append(Paragraph("", self.bt))


    def endClass(self, name, doc, bases):
        "Append a graphic demo of a Widget or Drawing at the end of a class."

        PdfDocBuilder0.endClass(self, name, doc, bases)

        aClass = eval('self.skeleton.moduleSpace.' + name)
        if hasattr(aClass, '_nodoc'):
            pass
        elif issubclass(aClass, Widget):
            try:
                widget = aClass()
            except AssertionError, err:
                if _abstractclasserr_re.match(str(err)): return
                raise
            self.story.append(Spacer(0*cm, 0.5*cm))
            self._showWidgetDemoCode(widget)
            self.story.append(Spacer(0*cm, 0.5*cm))
            self._showWidgetDemo(widget)
            self.story.append(Spacer(0*cm, 0.5*cm))
            self._showWidgetProperties(widget)
            self.story.append(PageBreak())
        elif issubclass(aClass, Drawing):
            drawing = aClass()
            self.story.append(Spacer(0*cm, 0.5*cm))
            self._showDrawingCode(drawing)
            self.story.append(Spacer(0*cm, 0.5*cm))
            self._showDrawingDemo(drawing)
            self.story.append(Spacer(0*cm, 0.5*cm))
    def test0(self):
        "This makes one long multi-page paragraph."

        # Build story.
        story = []

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

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

        story.append(Spacer(18, 18))

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

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

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

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

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

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

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

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

        story.append(Indenter(-36, -72))
        story.append(
            Paragraph(
                "This should be back to normal at each edge. " +
                ("spam " * 25), bt))
        doc = MyDocTemplate(outputfile('test_platypus_indents.pdf'))
        doc.multiBuild(story)
Example #10
0
 def end(self, c):
     c.addPara()
     # XXX Simulate margin for the moment
     c.addStory(Spacer(width=1, height=c.fragBlock.spaceAfter))
     c.listCounter = self.counter
Example #11
0
def generar_pdf(request, ubigeo, zonal, aeut):
    print "generar_pdf"
    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 = Tab_Aeus.objects.filter(ubigeo=ubigeo, zona=zonal, 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']]

    Z1 = Paragraph(
        "<strong>OBSERVACIONES: .............................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "................................................................................</strong>",
        h_obser)

    table_obs = Table(data=[[Z1]],
                      colWidths=[18.8 * cm],
                      rowHeights=[2 * cm],
                      style=[('GRID', (0, 0), (-1, -1), 1, colors.black)])

    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')])

    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(
                    Tab_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. UBICACION GEOGRAFICA</strong>', h11), '',
                '', '',
                Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), ''
            ],
            [
                Paragraph('<strong>DEPARTAMENTO</strong>', h1),
                Paragraph(str(distrito.ccdd.ccdd), h_center),
                Paragraph(str(distrito.ccdd.departamento), h1), '',
                Paragraph('<strong>ZONA Nº</strong>', h1),
                Paragraph(zona_temp, h_center)
            ],
            [
                Paragraph('<strong>PROVINCIA</strong>', h1),
                Paragraph(distrito.ccpp, h_center),
                Paragraph(
                    str(distrito.cod_prov.provincia).decode('latin-1'), h1),
                '',
                Paragraph(str('<strong>SECCION Nº</strong>'), h1),
                Paragraph(secc, h_center)
            ],
            [
                Paragraph('<strong>DISTRITO</strong>', h1),
                Paragraph(distrito.ccdi, h_center),
                Paragraph(str(distrito.distrito).decode('latin-1'), h1), '',
                Paragraph('<strong>A.E.U. Nº</strong>', h1),
                Paragraph(aeus, h_center)
            ],
            [
                Paragraph('<strong>CENTRO POBLADO</strong>', h1),
                Paragraph(str(aeu.llave_ccpp.nomccpp).decode('latin-1'), h1),
                '', '', '', ''
            ],
            [
                Paragraph('<strong>CATEGORIA DEL CENTRO POBLADO</strong>', h1),
                Paragraph('CIUDAD', h1), '', '',
                Paragraph('<strong>TOTAL DE VIVIENDAS<br/>DEL A.E.U.</strong>',
                          h1),
                Paragraph(str(int(aeu.cant_viv)), h_center)
            ],
        ]
        tables = Table(
            data,
            colWidths=[3.7 * cm, 1 * cm, 7.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)
        fichero_imagen_inei = 'Reporte/Img/inei.png'
        imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei),
                                 width=50,
                                 height=50)
        P2 = Paragraph('', styleBH)
        fichero_imagen = 'Reporte/Img/escudo.png'
        imagen_logo = Image(os.path.realpath(fichero_imagen),
                            width=50,
                            height=50)
        t1_croq = Paragraph(
            "<strong>CROQUIS DEL ÁREA DE EMPADRONAMIENTO URBANO</strong>",
            h_sub_tile_2)
        t = Table(
            data=[
                # ['', t1, ''],
                [[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),
                # ('SPAN', (0, 1), (2, 1)),
                # ('BOX', (0, 0), (1, -1), 2, colors.black),
                # ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
                # ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
                # ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                # ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                # ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                # ('BOX', (0, 0), (-1, -1), 2, colors.black),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
                # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
                # ('BACKGROUND', (3, 0), (3, 0), colors.limegreen),
                # ('BACKGROUND', (3, 1), (3, 1), colors.khaki),
                # ('ALIGN', (3, 1), (3, 1), 'CENTER'),
                # ('BACKGROUND', (3, 2), (3, 2), colors.beige),
                # ('ALIGN', (3, 2), (3, 2), 'LEFT'),
            ])
        obs_data = [
            [
                Paragraph(e, h3) for e in [
                    "<strong>Viv Nº</strong>", "<strong>Mz Nº</strong>",
                    "<strong>Fren<br/>-<br/>te<br/>Nº</strong>",
                    "<strong>DIRECCION DE LA VIVIENDA</strong>", "", "", "",
                    "", "", "", "", "",
                    "<strong>Nombres y Apellidos del JEFE DEL HOGAR</strong>"
                ]
            ],
            [
                Paragraph(e, h3) for e in [
                    "", "", "", "<strong>Tipo de Via</strong>",
                    "<strong>Nombre de Via</strong>",
                    "<strong>Nº de Puerta</strong>", "<strong>Block</strong>",
                    "<strong>Man-<br/>zana Nº</strong>",
                    "<strong>Lote Nº</strong>", "<strong>Piso Nº</strong>",
                    "<strong>Inter. Nº</strong>",
                    "<strong>Km.<br/> Nº</strong>", ""
                ]
            ],
        ]
        c = Table(obs_data,
                  colWidths=[
                      0.8 * cm, 0.9 * cm, 1.2 * cm, 1.2 * cm, 2.5 * cm,
                      1.2 * cm, 1.1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.1 * cm,
                      0.9 * cm, 4.9 * 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', (3, 0), (11, 0)),
                ('SPAN', (0, 0), (0, 1)),
                ('SPAN', (1, 0), (1, 1)),
                ('SPAN', (2, 0), (2, 1)),
                ('SPAN', (12, 0), (12, 1)),
                ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0),
                 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. UBICACION GEOGRAFICA</strong>', h1), '',
                '', '',
                Paragraph('<strong>B. UBICACION CENSAL</strong>', h1), ''
            ],
            [
                Paragraph('<strong>DEPARTAMENTO</strong>', h1),
                Paragraph(str(distrito.ccdd.ccdd), h1),
                Paragraph(str(distrito.ccdd.departamento), h1), '',
                Paragraph('<strong>ZONA Nº</strong>', h1),
                Paragraph(zona_temp, h1)
            ],
            [
                Paragraph('<strong>PROVINCIA</strong>', h1),
                Paragraph(distrito.ccpp, h1),
                Paragraph(
                    str(distrito.cod_prov.provincia).decode('latin-1'), h1),
                '',
                Paragraph(str('<strong>SECCION Nº</strong>'), h1), secc
            ],
            [
                Paragraph('<strong>DISTRITO</strong>', h1),
                Paragraph(distrito.ccdi, h1),
                Paragraph(distrito.distrito, h1), '',
                Paragraph('<strong>A.E.U. Nº</strong>', h1), aeus
            ],
            [
                Paragraph('<strong>CENTRO POBLADO</strong>', h1),
                Paragraph(str(aeu.llave_ccpp.nomccpp).decode('latin-1'), h1),
                '', '', '', ''
            ],
            [
                Paragraph('<strong>CATEGORIA 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))
        viv_urb = ViviendaUrbana.objects.filter(
            Q(ubigeo=distrito.ubigeo), Q(zona=aeu.zona),
            Q(aeu_final=aeu.aeu_final)).order_by('or_viv_aeu')
        fichero_imagen = 'Reporte/Croquis/Zona' + ubigeo + '00100' + '/Croquis' + ubigeo + '00100' + str(
            aeut) + '.png'
        imagen_croquis = Image(os.path.realpath(fichero_imagen),
                               width=18.8 * cm,
                               height=18 * cm)
        data_img = [
            [Paragraph(e, h3) for e in ["<strong>Imagen de Croquis</strong>"]],
        ]
        croq = Table(data=[[imagen_croquis]],
                     colWidths=[18.8 * cm],
                     rowHeights=[18.8 * cm],
                     style=[
                         ('GRID', (1, 1), (-2, -2), 1, colors.black),
                         ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                         ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                     ])
        # story.append(croq)
        # story.append(Spacer(0, 1 * mm))
        # story.append(table_obs)
        # story.append(PageBreak())
        # story.append(table_bar)
        story.append(t_croq)
        story.append(Spacer(0, 2 * mm))
        story.append(tables)
        story.append(Spacer(0, 3 * mm))
        story.append(c)
        # 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')[0:32]
        viviendas = v_ReporteViviendas_Tab.objects.filter(
            Q(ubigeo=ubigeo), Q(zona=zonal),
            Q(aeu_final=aeut)).order_by('manzana', 'id_reg_or')[0:32]

        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.id_viv.p29 == 2 or vivienda.id_viv.p29 == 5:
            elif vivienda.p29 == 5:
                if vivienda.p29_a in (1, 2, 3, 4):
                    jefe_hogar = str(pta_f) + "" + str(vivienda.p29_p)
                elif vivienda.p29_a in (5, 6):
                    jefe_hogar = str(pta_f)
                elif vivienda.p29_a == 7:
                    jefe_hogar = str(vivienda.p29_o)
                elif vivienda.p29_a == 8:
                    jefe_hogar = str(vivienda.p29_8_o)
            elif vivienda.p29 == 2 or vivienda.p29 == 4:
                jefe_hogar = str(vivienda.p35)
            else:
                print "No idea u.u"
            # Bloque Listado
            if (vivienda.p22_a == None):
                p22_a = ''
            else:
                p22_a = str(vivienda.p22_a).decode('latin-1')
            if (vivienda.p22_b == None):
                p22_b = ''
            else:
                p22_b = str(vivienda.p22_b).decode('latin-1')
            if (vivienda.p24 == None):
                p24 = ''
            else:
                p24 = str(vivienda.p24).decode('latin-1')
            if (vivienda.p25 == None):
                p25 = ''
            else:
                p25 = str(vivienda.p25).decode('latin-1')
            if (vivienda.p26 == None):
                p26 = ''
            else:
                p26 = str(vivienda.p26).decode('latin-1')
            table2 = [(
                str(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0
                    or vivienda.or_viv_aeu == '0' else '').decode('latin-1'),
                str(vivienda.manzana).decode('latin-1'),
                str(vivienda.frente_ord).decode('latin-1'),
                str(vivienda.p20.p20_nombre).decode('latin-1')
                if vivienda.p20 else "",
                str(vivienda.p21).decode('latin-1'),
                str(
                    str(p22_a).decode('latin-1') +
                    str(p22_b).decode('latin-1')).decode('latin-1'),
                str(str(vivienda.p23) if vivienda.p23 == 0 else "").decode(
                    'latin-1'),
                str(p24.decode('latin-1')),
                str(p25).decode('latin-1'),
                str(p26).decode('latin-1'),
                str(
                    str(vivienda.p27_a if not vivienda.p27_a == None else '') +
                    str(vivienda.p27_b if not vivienda.p27_b == None else '')).
                decode('latin-1'),
                # 1 if a > b else -1
                str(str(vivienda.p28) if vivienda.p28 == 0 else "").decode(
                    'latin-1'),
                str(jefe_hogar if not jefe_hogar == None else '').decode(
                    'latin-1'))]
            u = Table(table2,
                      colWidths=[
                          0.8 * cm, 0.9 * cm, 1.2 * cm, 1.2 * cm, 2.5 * cm,
                          1.2 * cm, 1.1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.1 * cm,
                          0.9 * cm, 4.9 * 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), (12, 0), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ]))
            story.append(u)
        viviendas_second = v_ReporteViviendas_Tab.objects.filter(
            Q(ubigeo=ubigeo), Q(zona=zonal),
            Q(aeu_final=aeut)).order_by('manzana', 'id_reg_or')[32:]

        if toti_viv > 33:
            story.append(c)
            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.id_viv.p29 == 2 or vivienda.id_viv.p29 == 5:
                elif vivienda.p29 == 5:
                    if vivienda.p29_a in (1, 2, 3, 4):
                        jefe_hogar = str(pta_f) + "" + str(vivienda.p29_p)
                    elif vivienda.p29_a in (5, 6):
                        jefe_hogar = str(pta_f)
                    elif vivienda.p29_a == 7:
                        jefe_hogar = str(vivienda.p29_o)
                    elif vivienda.p29_a == 8:
                        jefe_hogar = str(vivienda.p29_8_o)
                elif vivienda.p29 == 2 or vivienda.p29 == 4:
                    jefe_hogar = str(vivienda.p35)
                else:
                    print "No idea u.u"

                # Bloque Listado
                # Bloque Listado
                if (vivienda.p22_a == None):
                    p22_a = ''
                else:
                    p22_a = str(vivienda.p22_a).decode('latin-1')
                if (vivienda.p22_b == None):
                    p22_b = ''
                else:
                    p22_b = str(vivienda.p22_b).decode('latin-1')
                if (vivienda.p24 == None):
                    p24 = ''
                else:
                    p24 = str(vivienda.p24).decode('latin-1')
                if (vivienda.p25 == None):
                    p25 = ''
                else:
                    p25 = str(vivienda.p25).decode('latin-1')
                if (vivienda.p26 == None):
                    p26 = ''
                else:
                    p26 = str(vivienda.p26).decode('latin-1')
                table2 = [(
                    str(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or
                        vivienda.or_viv_aeu == '0' else '').decode('latin-1'),
                    str(vivienda.manzana).decode('latin-1'),
                    str(vivienda.frente_ord).decode('latin-1'),
                    str(vivienda.p20.p20_nombre).decode('latin-1')
                    if vivienda.p20 else "",
                    str(vivienda.p21).decode('latin-1'),
                    str(str(p22_a) + str(p22_b)).decode('latin-1'),
                    str(str(vivienda.p23) if vivienda.p23 == 0 else "").decode(
                        'latin-1'),
                    str(p24).decode('latin-1'),
                    str(p25).decode('latin-1'),
                    str(p26).decode('latin-1'),
                    str(
                        str(vivienda.
                            p27_a if not vivienda.p27_a == None else '') +
                        str(vivienda.p27_b if not vivienda.p27_b == None else
                            '')).decode('latin-1'),
                    # 1 if a > b else -1
                    str(str(vivienda.p28) if vivienda.p28 == 0 else "").decode(
                        'latin-1'),
                    str(jefe_hogar if not jefe_hogar == None else '').decode(
                        'latin-1'))]
                u_second = Table(table2,
                                 colWidths=[
                                     0.8 * cm, 0.9 * cm, 1.2 * cm, 1.2 * cm,
                                     2.5 * cm, 1.2 * cm, 1.1 * cm, 1 * cm,
                                     1 * cm, 1 * cm, 1.1 * cm, 0.9 * cm,
                                     4.9 * 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), (12, 0), 7),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ]))
                story.append(u_second)
        # 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
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
    def test0(self):
        "This makes one long multi-page paragraph."

        # Build story.
        story = []

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

        story.append(Paragraph('Test of preformatted text wrapping', h1))

        story.append(Spacer(18, 18))

        txt = """Our Preformatted class can be used for printing simple blocks
of code. It respects whitespace and newlines, and will not normally attempt 
to wrap your code. However, if your individual lines are too long, this can 
overflow the width of the column and even run off the page. Three optional 
attributes - maximumLineLength, splitCharacters and newLineCharacter - 
can be used to do simple wrapping. maximumLineLength will force the text to
wrap. Note that this simply counts characters - it takes no account of
actual width on the page. The examples below wrap lines above a certain length
and add a '>' to the start of the following line.
"""

        story.append(Paragraph(txt, bt))

        story.append(Paragraph("", bt))

        code = """
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/platypus/xpreformatted.py
__version__='3.3.0'
__doc__='''A 'rich preformatted text' widget allowing internal markup'''

from reportlab.lib import PyFontify
from paragraph import Paragraph, cleanBlockQuotedText, _handleBulletWidth, ParaLines, _getFragWords, stringWidth, _sameFrag, getAscentDescent, imgVRange, imgNormV
from flowables import _dedenter

class XPreformatted(Paragraph):
    def __init__(self, text, style, bulletText = None, frags=None, caseSensitive=1, dedent=0):
        self.caseSensitive = caseSensitive
        cleaner = lambda text, dedent=dedent: ,'\\n'.join(_dedenter(text or '',dedent))
        self._setup(text, style, bulletText, frags, cleaner)

    def breakLines(self, width):
        if isinstance(width,list): maxWidths = [width]
        else: maxWidths = width
        lines = []
        lineno = 0
        maxWidth = maxWidths[lineno]
        style = self.style
        fFontSize = float(style.fontSize)
        requiredWidth = 0

        #for bullets, work out width and ensure we wrap the right amount onto line one
        _handleBulletWidth(self.bulletText,style,maxWidths)

        self.height = 0
        autoLeading = getattr(self,'autoLeading',getattr(style,'autoLeading',''))
        calcBounds = autoLeading not in ('','off')
        frags = self.frags
        nFrags= len(frags)
        if nFrags==1:
            f = frags[0]
            if hasattr(f,'text'):
                fontSize = f.fontSize
                fontName = f.fontName
                ascent, descent = getAscentDescent(fontName,fontSize)
                kind = 0
                L=f.text.split('\\n')
                for l in L:
                    currentWidth = stringWidth(l,fontName,fontSize)
                    requiredWidth = max(currentWidth,requiredWidth)
                    extraSpace = maxWidth-currentWidth
                    lines.append((extraSpace,l.split(' '),currentWidth))
                    lineno = lineno+1
                    maxWidth = lineno&lt;len(maxWidths) and maxWidths[lineno] or maxWidths[-1]
                blPara = f.clone(kind=kind, lines=lines,ascent=ascent,descent=descent,fontSize=fontSize)
            else:
                kind = f.kind
                lines = f.lines
                for L in lines:
                    if kind==0:
                        currentWidth = L[2]
                    else:
                        currentWidth = L.currentWidth
                    requiredWidth = max(currentWidth,requiredWidth)
                blPara = f.clone(kind=kind, lines=lines)

            self.width = max(self.width,requiredWidth)
            return blPara
        elif nFrags&lt;=0:
            return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName,
                            textColor=style.textColor, ascent=style.fontSize,descent=-0.2*style.fontSize,
                            lines=[])
        else:
            for L in _getFragLines(frags):
                currentWidth, n, w = _getFragWord(L,maxWidth)
                f = w[0][0]
                maxSize = f.fontSize
                maxAscent, minDescent = getAscentDescent(f.fontName,maxSize)
                words = [f.clone()]
                words[-1].text = w[0][1]
                for i in w[1:]:
                    f = i[0].clone()
                    f.text=i[1]
                    words.append(f)
                    fontSize = f.fontSize
                    fontName = f.fontName
                    if calcBounds:
                        cbDefn = getattr(f,'cbDefn',None)
                        if getattr(cbDefn,'width',0):
                            descent,ascent = imgVRange(imgNormV(cbDefn.height,fontSize),cbDefn.valign,fontSize)
                        else:
                            ascent, descent = getAscentDescent(fontName,fontSize)
                    else:
                        ascent, descent = getAscentDescent(fontName,fontSize)
                    maxSize = max(maxSize,fontSize)
                    maxAscent = max(maxAscent,ascent)
                    minDescent = min(minDescent,descent)

                lineno += 1
                maxWidth = lineno&lt;len(maxWidths) and maxWidths[lineno] or maxWidths[-1]
                requiredWidth = max(currentWidth,requiredWidth)
                extraSpace = maxWidth - currentWidth
                lines.append(ParaLines(extraSpace=extraSpace,wordCount=n, words=words, fontSize=maxSize, ascent=maxAscent,descent=minDescent,currentWidth=currentWidth))

            self.width = max(self.width,requiredWidth)
            return ParaLines(kind=1, lines=lines)

        return lines
"""

        story.append(
            Preformatted(code,
                         normalStyle,
                         dedent=0,
                         maxLineLength=60,
                         newLineChars='> '))

        doc = MyDocTemplate(outputfile('test_platypus_preformatted.pdf'))
        doc.multiBuild(story)
def generar_pdf(request):
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4
    #from django.db import connection
    print "Genero el PDF"
    response = HttpResponse(content_type='application/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
    # pdf_name = "clientes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    c = canvas.Canvas(buff, pagesize=A4)
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=70,
                            leftMargin=70,
                            topMargin=60,
                            bottomMargin=18,
                            )
    h1 = PS(
        name='Heading1',
        fontSize=9,
        leading=16)

    h2 = PS(
        name='centered',
        fontSize=7,
        leading=14,
        alignment = TA_CENTER)

    clientes = []
    story = []

    # allclientes = Pruebaaa.objects.filter(ubigeo='21806').order_by('id')
    # allclientes = [(p.zona, p.id, p.aeu) for p in Pruebaaa.objects.all()]
    # permisos = list(ViewPermisosMenuChild.objects.filter(id_usuario=id).values('cod_permiso', 'nom_permiso', 'des_rol', 'id_menu'))


    filtro = list(MaeProyecto.objects.filter(ubigeo='020601', frente_ord = '1', id_reg_or='23').values('or_viv_aeu', 'manzana', 'frente_ord', 'p20','p21','p22_a', 'p23','p24','p25','p26','p27_a','p32'))
    #allclientes = [(p.zona, p.id, p.aeu) for p in Pruebaaa.objects.filter(ubigeo='21806')]
    alltodo = [(str(a['or_viv_aeu']).decode('utf-8'),
                str(a['manzana']).decode('utf-8'),
                str(a['frente_ord']).decode('utf-8'),
                str(a['p20']).decode('utf-8'),
                str(a['p21']).decode('utf-8'),
                str(a['p22_a']).decode('utf-8'),
                str(a['p23']).decode('utf-8'),
                str(a['p24']).decode('utf-8'),
                str(a['p25']).decode('utf-8'),
                str(a['p26']).decode('utf-8'),
                str(a['p27_a']).decode('utf-8'),
                str(a['p32']).decode('utf-8'))
               for a in filtro]

    # Paragraph('a['p32']', styleTitle)
    # for i, e in enumerate(allclientes):
    # p.drawString(x + (18 * diff_x), y - diff_y, str(data_models.pub_date))
    # story.append(Paragraph(str(e.ubigeo), styleBH))
    # for a in allclientes:
    #    story.append(a.id)
    # Texts
    # descrpcion = Paragraph('long paragraph long paragraphlong paragraphlong paragraphlong paragraphlong paragraph',
    #                        DOCUMENT_STYLE["normal"])
    # partida = Paragraph('1', DOCUMENT_STYLE["normal"])
    # candidad = Paragraph('120', DOCUMENT_STYLE["normal"])
    # precio_unitario = Paragraph('$52.00', DOCUMENT_STYLE["normal"])
    # precio_total = Paragraph('$6240.00', DOCUMENT_STYLE["normal"])

    # data= [[hdescrpcion, hcandidad,hcandidad, hprecio_unitario, hprecio_total],
    #       [partida, candidad, descrpcion, precio_unitario, precio_total]]
    data = [
            [Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h1), '', '', '', Paragraph('<strong>B. UBICACION CENSAL</strong>', h1), ''],
            [Paragraph('<strong>DEPARTAMENTO</strong>', h1), Paragraph('15', h1), Paragraph('LIMA', h1), '', Paragraph('<strong>ZONA N</strong>', h1), Paragraph('001', h1)],
            [Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph('01', h1),Paragraph('LIMA', h1), '', Paragraph('<strong>SECCION N</strong>', h1), Paragraph('010', h1)],
            [Paragraph('<strong>DISTRITO</strong>', h1), Paragraph('15', h1),Paragraph('LA VICTORIA', h1), '', Paragraph('<strong>A.E.U. N</strong>', h1),Paragraph('008', h1)],
            [Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph('LA VICTORIA', h1),'', '', '', ''],
            [Paragraph('<strong>CATEGORIA CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '', Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL A.E.U.</strong>', h1),Paragraph('16', h1)],
    ]

    obs_data = [
        [Paragraph(e, h2) for e in["<strong>VIV. N</strong>", "<strong>MZ N</strong>", "<strong>FRENTE N</strong>", "<strong>DIRECCION DE LA VIVIENDA</strong>", "", "", "", "", "", "", "","<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>"]],
        [Paragraph(e, h2) for e in["", "", "", "<strong>Tipo de Via</strong>", "<strong>Nombre de Via</strong>", "<strong>N de Puerta</strong>", "<strong>Block</strong>", "<strong>Man-zana N</strong>", "<strong>Lote N</strong>", "<strong>Piso N</strong>","<strong>Interior N</strong>", ""]],
        #[Paragraph('<strong>VIV. N</strong>', styleTitle), Paragraph('<strong>MANZANA N</strong>', styleTitle), Paragraph('<strong>FRENTE N</strong>', styleTitle), Paragraph('<strong>DIRECCION DE LA VIVIENDA</strong>', styleTitle), '', '', '', '', '', '', '', Paragraph('<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>', styleTitle)],
        #['', '', '', Paragraph('<strong>Tipo de Via</strong>',styleTitle), Paragraph('<strong>Nombre de Via</strong>', styleTitle), Paragraph('<strong>N de Puerta</strong>', styleTitle), Paragraph('<strong>Block</strong>', styleTitle), Paragraph('<strong>Manzana N</strong>', styleTitle), Paragraph('<strong>Lote N</strong>', styleTitle),Paragraph( '<strong>Piso N</strong>', styleTitle),Paragraph('<strong>Interior N</strong>',styleTitle),''],
    ]
    obs = [
        [Paragraph('OBSERVACIONES', styleBH), ''],
        ['', '', ],
        ['', '', ],
        ['', '', ],
    ]
    headings = ('Nombre', 'zona', 'repo','Nombre', 'zona', 'repo','Nombre', 'zona', 'repo','Nombre', 'zona')
    #t = Table([headings] + allclientes)
    d = Table (obs_data + alltodo, colWidths=[0.9 * cm, 0.9 * cm, 1.5 * cm,1.4 * cm,None,1.2 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.3 * cm ,4.6 * cm])

    # t.setStyle(TableStyle(
    #     [
    #         ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
    #         ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
    #         ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
    #     ]
    # ))
    d.setStyle(TableStyle(
        [
            # ('GRID', (0, 0), (10, -1), 1, colors.black),
            # ('GRID', (4, 0), (5, 3), 1, colors.black)
            ('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), (-1, -1), 7),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue),
            ('BACKGROUND', (0, 0), (-1, 1), colors.lightskyblue),
            ('SPAN', (3, 0), (10, 0)),
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (1, 1)),
            ('SPAN', (2, 0), (2, 1)),
            ('SPAN', (11, 0), (11, 1)),
            # ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black)
            # ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue)
        ]
    ))

    # d.setStyle(TableStyle(
    #     [
    #         ('GRID', (0, 0), (10, -1), 1, colors.black),
    #         ('GRID', (4, 0), (5, 3), 1, colors.black),
    #         ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black)
    #         #('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue)
    #     ]
    # ))

    table = Table(data, colWidths=[6 * cm, 1 * cm, 3.5 * cm, 0.1 * cm, 6 * cm, 1.5 * cm])

    table.setStyle(TableStyle([
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (2, 5), 1, colors.black),
        ('GRID', (4, 0), (5, 3), 1, colors.black),
        ('GRID', (-2, -1), (-1, -1), 1, colors.black),
        ('SPAN', (0, 0), (2, 0)),
        ('SPAN', (4, 0), (5, 0)),
        ('SPAN', (1, 4), (2, 4)),
        ('SPAN', (1, 5), (2, 5)),
        ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue),
        ('BACKGROUND', (0, 0), (0, 5), colors.lightskyblue),
        ('BACKGROUND', (4, 0), (4, 5), colors.lightskyblue)
        # ('TEXTFONT',(0,0), (-1,-1), 'Roboto-Regular'),
        # ('FONTSIZE',(0,0), (-1,-1), 1),
    ]))

    otable = Table(obs_data, colWidths=[1 * cm, 1 * cm, 1.6 * cm, 1.4 * cm, None, 1.4 * cm, 1 * cm, 1.2 * cm, 1.2 * cm, 1.1 * cm, 1.5 * cm, 4 * cm])


    otable.setStyle(TableStyle([
                       ('TEXTCOLOR', (0, 0), (-1, -1), colors.blue),
                       ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                       ('GRID', (0, 0), (-1, -1), 1, colors.black),
                       ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue),
                       ('BACKGROUND', (0, 0), (-1, 1), colors.lightskyblue),
                       # ('FONTSIZE', (0, 0), (-1, -1), 7),
                       # ('FONTNAME', (0, 0), (-1, -1), 7),
                       ('SPAN', (0, 0), (0, 1)),
                       ('SPAN', (1, 0), (1, 1)),
                       ('SPAN', (2, 0), (2, 1)),
                       ('SPAN', (3, 0), (10, 0)),
                       ('SPAN', (11, 0), (11, 1))
        #('SPAN', (0, 0), (0, 1)),
        #('SPAN', (1, 0), (1, 1)),
        #('SPAN', (2, 0), (2, 1)),
        #('SPAN', (3, 0), (10, 0)),
        #('SPAN', (11, 0), (11, 1)),
    ]))

    t1 = Paragraph("<strong>INSTITUO NACIONAL DE ESTADISTICA E INFORMATICA CENSOS NACIONALES 2017: XII DE POBLACION, VII DE VIVIENDA</strong>",styleTitle)
    # story.append(Spacer(0, 001 * mm))
    t2 = Paragraph("<strong>Y III DE COMUNIDADES INDIGENAS</strong>", styleTitle)

    fichero_imagen_inei = 'Reporte/Img/inei.png'
    imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=50)
    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]],
            ['', t2, '']
        ],
        colWidths=[2 * cm, 12 * cm, 2*cm],
        style=[
            ('GRID', (1, 1), (-2, -2), 1, colors.white),

            #('BOX', (0, 0), (1, -1), 2, colors.black),
            #('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
            #('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
            #('BACKGROUND', (0, 0), (0, 1), colors.pink),
            #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
            #('BACKGROUND', (2, 2), (2, 3), colors.orange),
            #('BOX', (0, 0), (-1, -1), 2, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
            #('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
            #('BACKGROUND', (3, 0), (3, 0), colors.limegreen),
            #('BACKGROUND', (3, 1), (3, 1), colors.khaki),
            #('ALIGN', (3, 1), (3, 1), 'CENTER'),
            #('BACKGROUND', (3, 2), (3, 2), colors.beige),
            #('ALIGN', (3, 2), (3, 2), 'LEFT'),
        ]
    )


    t1 = Paragraph("<strong>VIV.N</strong>", h2)
    t2 = Paragraph("<strong>MZ N</strong>", h2)
    t3 = Paragraph("<strong>FRENTE N</strong>", h2)
    t4 = Paragraph("<strong>Tipo de Via</strong>", h2)
    t5 = Paragraph("<strong>Nombre de Via</strong>", h2)
    t6 = Paragraph("<strong>N de Puerta</strong>", h2)
    t7 = Paragraph("<strong>Block</strong>", h2)
    t8 = Paragraph("<strong>Man-zana N</strong>", h2)
    t9 = Paragraph("<strong>Lote N</strong>", h2)
    t10 = Paragraph("<strong>Piso N</strong>", h2)
    t11 = Paragraph("<strong>Interior N</strong>", h2)
    t12 = Paragraph("<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>", h2)
    t13 = Paragraph("<strong>DIRECCION DE LA VIVIENDA</strong>", h2)
    z = Table(
        data=[
            [t1, t2, t3, t13, '', '', '', '', '', '', '', t12],
            ['', '', '',t4,t5,t6,t7,t8,t9,t10,t11,'']
        ],
        colWidths=[0.9 * cm, 0.9 * cm, 1.5 * cm,1.4 * cm,None,1.2 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.3 * cm ,3.4 * cm],
        style=[
            ('GRID', (1, 1), (-2, -2), 1, colors.black),
            # ('BOX', (0, 0), (1, -1), 2, colors.black),
            # ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
            # ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
            # ('BACKGROUND', (0, 0), (0, 1), colors.pink),
            # ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
            # ('BACKGROUND', (2, 2), (2, 3), colors.orange),
            # ('BOX', (0, 0), (-1, -1), 2, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
            # ('BACKGROUND', (3, 0), (3, 0), colors.limegreen),
            # ('BACKGROUND', (3, 1), (3, 1), colors.khaki),
            # ('ALIGN', (3, 1), (3, 1), 'CENTER'),
            # ('BACKGROUND', (3, 2), (3, 2), colors.beige),
            # ('ALIGN', (3, 2), (3, 2), 'LEFT'),
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (1, 1)),
            ('SPAN', (2, 0), (2, 1)),
            ('SPAN', (11, 0), (11, 1)),
            ('SPAN', (3, 0), (10, 0))
        ]
    )

    # imagen_logo.drawOn(canvas,20,20)
    # imagen_logo.drawWidth(10)
    # imagen_logo.drawWidth(5)

    # drawImage(archivo, x, y, width=None, height=None)
    # c.drawImage(fichero_imagen, 2, 2, width=100, height=100)
    # # table.wrapOn(c, A4, A4)
    # # table.drawOn(c, 20, 650)
    # c.showPage()
    # c.save()

    story.append(t)
    # story.append(z)
    # story.append(imagen_logo_inei)
    story.append(Spacer(0,05 * mm))
    story.append(Paragraph("<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO URBANO (A.E.U.)</strong>", styleTitle))
    story.append(Spacer(0,5 * mm))
    story.append(table)
    story.append(dist)
    story.append(Spacer(0,5 * mm))
    # story.append(otable)
    # story.append(Spacer(0,01 * mm))
    story.append(d)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
Example #15
0
def generar_seccion(request, ubigeo, zonaq):
    print "Se va a generar el PDF de Ubigeo:" + str(
        ubigeo) + " y Zona: " + str(zonaq)
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename=" + str(
        ubigeo) + str(zonaq) + ".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 = "Secciones/" + str(ubigeo) + str(zona_conv)+".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_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=16, 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_sub_tile = PS(name='Heading1',
                    fontSize=10,
                    leading=14,
                    alignment=TA_CENTER)

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

    h_res = PS(name='Normal', fontSize=7, leading=7, alignment=TA_RIGHT)

    story = []
    # rutas = Rutas.objects.get(ubigeo=ubigeo)

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

    #cond = Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100')
    cond = Vw_Rep_Cab_Zona_Esp.objects.filter(ubigeo=ubigeo, zona=zonaq)

    #total_secc = str(Aeus.objects.filter(ubigeo='020601', zona='00100').values_list('seccion', flat=True).distinct().count())
    total_secc = str(
        v_ReporteSecciones.objects.filter(
            ubigeo=ubigeo,
            zona=zonaq).values_list('seccion', flat=True).distinct().count())

    #total_aeus = str(Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100').count())
    total_aeus = str(
        v_ReporteSecciones.objects.filter(ubigeo=ubigeo, zona=zonaq).count())

    resumen = v_ReporteResumenDistrito.objects.get(ubigeo=ubigeo, zona=zonaq)

    primero = v_ReporteSecciones.objects.filter(
        ubigeo=distrito.ubigeo, zona=zonaq).order_by('aeu_final').first()
    ultimo = v_ReporteSecciones.objects.filter(
        ubigeo=distrito.ubigeo, zona=zonaq).order_by('aeu_final').last()

    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']]

    Z1 = Paragraph(
        "<strong>OBSERVACIONES: .............................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "....................................................................................................."
        "................................................................................</strong>",
        h_obser)

    table_obs = Table(data=[[Z1]],
                      colWidths=[18.8 * cm],
                      rowHeights=[2 * cm],
                      style=[('GRID', (0, 0), (-1, -1), 1, colors.black)])

    tota_viv = 0

    string = str(ubigeo) + str(zonaq)
    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=[15 * cm, 4 * cm],
                      style=[('ALIGN', (0, 0), (-1, -1), 'CENTER')])

    total = 0
    x = 0

    for aeu in cond:
        # string = "02060100100"
        # st = code39.Extended39(string)
        # story.append(st)

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

        # prim = str(primero.aeu_final).zfill(3)
        # ult = str(ultimo.aeu_final).zfill(3)

        prim_secc = str(primero.seccion).zfill(3)
        ulti_secc = str(ultimo.seccion).zfill(3)

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

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

            total_zonas = int(
                str(
                    Tab_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_esp\\" +
                        str(lista_distritos[ubigein]) + "\\" +
                        cuchi[zona_t]) == False:
                    os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_esp\\" +
                             str(lista_distritos[ubigein]) + "\\" +
                             cuchi[zona_t])

        # destino = "Zonas/" + str(ubigeo) + zonaq + ".pdf"

        # destino = "Zonas/" + str(ubigeo) + zonaq + ".pdf"
        #
        # doc2 = SimpleDocTemplate(destino, pagesize=A4,
        #                          rightMargin=70,
        #                          leftMargin=70,
        #                          topMargin=0.5 * cm,
        #                          bottomMargin=0.5 * cm, )

        tota_viv = tota_viv + int(aeu.cant_viv)

        zona_temp = aeu.zona[0:3]
        zona_int = int(aeu.zona[3:])
        zona_int_eq = ""

    destino = "\\\srv-fileserver\\CPV2017\\list_segm_esp\\" + str(
        ubigeo) + "\\" + zonaq + "\\" + str(ubigeo) + zonaq + ".pdf"
    doc2 = SimpleDocTemplate(
        destino,
        pagesize=A4,
        rightMargin=70,
        leftMargin=70,
        topMargin=0.5 * cm,
        bottomMargin=0.5 * cm,
    )

    for el in rango_equivalencia:
        if (el[0] == zona_int):
            zona_int_eq = el[1]

    # zona_temp = zona_temp + str(zona_int_eq)
    #
    # aeu_tot = str(total_aeus).zfill(3)
    # secc_tot = str(total_secc).zfill(3)
    #
    # nombreccpp=Ccpp.objects.filter(ubigeo=ubigeo,codccpp=aeu.codccpp).values('nomccpp')
    data = [
        ['', '', '', '', '',
         Paragraph('<strong>Doc. CPV</strong>', h4)],
        [
            Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '', '',
            '',
            Paragraph('<strong>B. UBICACION 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(aeu.provincia, h1), '',
            Paragraph(str('<strong>SECCION Nº</strong>'), h1),
            Paragraph(
                'DEL ' + str(aeu.seccion_inicial) + ' AL ' +
                str(aeu.seccion_final), 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(
                "DEL " + str(aeu.aeu_inicial) + " AL " + str(aeu.aeu_final),
                h_center)
        ],
        [
            Paragraph('<strong>CENTRO POBLADO</strong>', h1),
            Paragraph(aeu.nomccpp, h1), '', '', '', ''
        ],
        [
            Paragraph('<strong>CATEGORIA DEL CENTRO POBLADO</strong>', h1),
            Paragraph('CIUDAD', h1), '', '',
            Paragraph('<strong>TOTAL DE VIVIENDAS DE LA ZONA</strong>', h1),
            Paragraph(str(aeu.cant_viv), h1)
        ],
    ]

    tables = Table(
        data,
        colWidths=[3.7 * cm, 1 * cm, 7.1 * cm, 0.3 * cm, 4 * cm, 2.7 * 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'),
                    ('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', (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))]))

    t2 = Paragraph("CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA",
                   h_sub_tile)

    t3 = Paragraph("Y III DE COMUNIDADES INDÍGENAS", h_sub_tile)

    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], t2, [imagen_logo_inei, P2]],
                    ['', t3, '']],
              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(table_bar)
    story.append(t)
    story.append(Spacer(0, 5 * mm))
    story.append(
        Paragraph(
            "<strong>LISTADO DE LA ZONA CENSAL POR SECCIONES Y AREAS DE EMPADRONAMIENTO URBANO</strong>",
            styleTitle))
    story.append(Spacer(0, 5 * mm))
    story.append(tables)
    story.append(Spacer(0, 3 * mm))

    obs_data = [
        [
            Paragraph(e, h3) for e in [
                "<strong>D. INFORMACIÓN DE LA ZONA CENSAL</strong>",
                "",
                "",
            ]
        ],
        [
            Paragraph(e, h3) for e in [
                "<strong>SECCION Nª</strong>", "<strong>A.E.U. Nº</strong>",
                "<strong>MANZANA Nº</strong>",
                "<strong>Nº DE VIVIENDAS POR A.E.U.</strong>"
            ]
        ],
    ]
    c = Table(obs_data, colWidths=[4.9 * cm, 4.5 * cm, 4.5 * cm, 4.9 * 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),
            ('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', (0, 0), (3, 0)),
            ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0),
             colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
        ]))
    story.append(c)
    #aeusi = Aeus.objects.filter(Q(ubigeo=distrito.ubigeo),Q(zona='00100'))
    aeusi = v_ReporteSecciones.objects.filter(Q(ubigeo=ubigeo),
                                              Q(zona=zonaq)).order_by(
                                                  'seccion', 'aeu_final')[0:33]

    aeusi_second = v_ReporteSecciones.objects.filter(Q(ubigeo=ubigeo),
                                                     Q(zona=zonaq)).order_by(
                                                         'seccion',
                                                         'aeu_final')[33:]

    cant_secciones = int(
        v_ReporteSecciones.objects.filter(Q(ubigeo=ubigeo),
                                          Q(zona=zonaq)).count())
    total_page = 1

    total_secciones = 0
    total_mznsr = 0
    total_aeusr = 0

    for aeusis in aeusi:
        total_secciones = total_secciones + 1
        total_mznsr = total_mznsr + 1
        total_aeusr = total_aeusr + 1

    for aeusis in aeusi:
        x = x + 1
        y = x
        secc = str(aeusis.seccion).zfill(3)
        aeus = str(aeusis.aeu_final).zfill(3)
        # str(vivienda.p28) if vivienda.p28 == 0 else ""
        mzn = str(
            aeusis.manzanas.zfill(3) if not aeusis.manzanas == None else "")
        table2 = [(str(secc).decode('latin-1'), str(aeus).decode('latin-1'),
                   str(mzn).decode('latin-1'),
                   str(int(aeusis.cant_viv)).decode('latin-1'))]
        s = Table(table2,
                  colWidths=[4.9 * cm, 4.5 * cm, 4.5 * cm, 4.9 * cm],
                  rowHeights=[0.5 * cm])

        s.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), (-1, -1), 7),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ]))
        story.append(s)

    if cant_secciones > 33:
        story.append(c)
        # Aca va el segundo for
        for aeusis_second in aeusi_second:
            x = x + 1
            y = x
            secc = str(aeusis_second.seccion).zfill(3)
            aeus = str(aeusis_second.aeu_final).zfill(3)
            mzn = str(aeusis_second.manzanas).zfill(3)
            table2 = [(str(secc).decode('latin-1'),
                       str(aeus).decode('latin-1'), str(mzn).decode('latin-1'),
                       str(int(aeusis_second.cant_viv)).decode('latin-1'))]
            s = Table(table2,
                      colWidths=[4.9 * cm, 4.5 * cm, 4.5 * cm, 4.9 * cm],
                      rowHeights=[0.5 * cm])

            s.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), (-1, -1), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ]))
            story.append(s)

    data_res = [
        ['',
         Paragraph('<strong>C. RESUMEN DE LA ZONA</strong>', h11), '', ''],
        [
            '',
            Paragraph('<strong>TOTAL DE SECCIONES</strong>', h1),
            Paragraph(str(resumen.cant_secciones), h_res), ''
        ],
        [
            '',
            Paragraph('<strong>TOTAL DE MANZANAS.</strong>', h1),
            Paragraph(str(resumen.cant_mzs), h_res), ''
        ],
        [
            '',
            Paragraph('<strong>TOTAL DE AEUS</strong>', h1),
            Paragraph(str(resumen.cant_aeus), h_res), ''
        ],
    ]

    tables_res = Table(data_res,
                       colWidths=[3 * cm, 6 * cm, 2.5 * cm, 3 * cm],
                       rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm])

    tables_res.setStyle(
        TableStyle([
            ('TEXTCOLOR', (0, 0), (2, 0), colors.black),
            # ('ALIGN', (4, 0), (5, 0), 'RIGHT'),
            # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (1, 0), (2, 3), 1, colors.black),
            # ('ALIGN', (2, 1), (2, 5), 'LEFT'),
            # ('GRID', (2, 1), (2, 3), 1, colors.black),
            # ('GRID', (-2, -1), (-1, -1), 1, colors.black),
            ('SPAN', (1, 0), (2, 0)),
            # ('SPAN', (1, 4), (2, 4)),
            # ('SPAN', (1, 5), (2, 5)),
            # ('SPAN', (1, 6), (2, 6)),
            # ('BACKGROUND', (4, 1), (5, 5), colors.white),
            ('BACKGROUND', (1, 0), (2, 0),
             colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
        ]))

    story.append(Spacer(0, 2 * cm))

    story.append(tables_res)

    if (PageBreak()):
        total_page = total_page + 1
        # story.append(Paragraph("<strong>Hice salto</strong>", styleTitle))

    p = Paragraph(str(1) + " - " + str(1), h2)
    extra = Paragraph("-", h2)

    p_page = Table(data=[[extra, p]],
                   colWidths=[19 * cm, 2.3 * cm],
                   style=[
                       ('GRID', (0, 0), (-1, -1), 1, colors.white),
                       ('ALIGN', (0, 0), (1, 0), 'RIGHT'),
                   ])

    story.append(Spacer(0, 5 * cm))
    # story.append(table_obs)
    story.append(Spacer(0, 1 * mm))
    story.append(p_page)

    story.append(PageBreak())

    doc2.build(story)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response