def makeBarcodeFile(brc, width, height): brc = str(brc) width = float(width) * mm height = float(height) * mm # generate a canvas (A4 in this case, size doesn"t really matter) c = canvas.Canvas(brc + ".pdf", pagesize=A4) # create a barcode object # (is not displayed yet) # The encode text is "123456789" # barHeight encodes how high the bars will be # barWidth encodes how wide the "narrowest" barcode unit is barcode = code39.Extended39(brc, barWidth=width * mm, barHeight=height * mm) # drawOn puts the barcode on the canvas at the specified coordinates x, y = (10 * mm, 10 * mm) while y + barcode.height < 290 * mm: while x + barcode.width < 200 * mm: barcode.drawOn(c, x, y) x = x + (1 + barcode.width) x = 10 * mm y = y + (1 + barcode.height) * mm # now create the actual PDF c.showPage() c.save()
def draw_barcode(self, barcode_value): bar_height = 25 barcode39 = code39.Extended39(barcode_value, barHeight=bar_height) self.y_cursor -= bar_height barcode39.drawOn(self.c, (self.page_width - barcode39.width) / 2.0, self.y_cursor) self.y_cursor -= 15
def createBarCodes(): """ Create barcode examples and embed in a PDF """ c = canvas.Canvas("barcodes.pdf", pagesize=A4) barcode_value = "1234567890" barcode39 = code39.Extended39(barcode_value) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) # code93 also has an Extended and MultiWidth version barcode93 = code93.Standard93(barcode_value) barcode128 = code128.Code128(barcode_value) # the multiwidth barcode appears to be broken #barcode128Multi = code128.MultiWidthBarcode(barcode_value) barcode_usps = usps.POSTNET("50158-9999") codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps] x = 1 * mm y = 285 * mm x1 = 6.4 * mm for code in codes: code.drawOn(c, x, y) y = y - 15 * mm # draw the eanbc8 code barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value) bounds = barcode_eanbc8.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc8) renderPDF.draw(d, c, 15, 555) # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc13) renderPDF.draw(d, c, 15, 465) # draw a QR code qr_code = qr.QrCodeWidget( 'https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python' ) bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0]) d.add(qr_code) renderPDF.draw(d, c, 15, 405) c.save()
def _flowable(self, n): tags = { 'name': lambda node: self.__name(node), 'para': lambda node: platypus.Paragraph(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'xpre': lambda node: platypus.XPreformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int', 'frags': 'int'}))), 'pre': lambda node: platypus.Preformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int'}))), 'illustration': lambda node: self._illustration(node), 'blockTable': lambda node: self._table(node), 'title': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Title'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h1': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading1'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h2': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading2'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h3': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading3'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'image': lambda node: platypus.Image(node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get(node, ['width', 'height', 'preserveAspectRatio', 'anchor']))), 'spacer': lambda node: platypus.Spacer( width=utils.unit_get(node.getAttribute('width') if node.hasAttribute('width') else '1cm'), height=utils.unit_get(node.getAttribute('length'))), 'barCode': lambda node: code39.Extended39(self._textual(node)), 'pageBreak': lambda node: platypus.PageBreak(), # FIXME: it is not in RML std 'nextPage': lambda node: platypus.PageBreak(), 'condPageBreak': lambda node: platypus.CondPageBreak(**(utils.attr_get(node, ['height']))), 'setNextTemplate': lambda node: platypus.NextPageTemplate(str(node.getAttribute('name'))), 'nextFrame': lambda node: platypus.CondPageBreak(1000), # TODO: change the 1000 ! 'ul': lambda node: self._list(node), 'keepInFrame': lambda node: self.__keep_in_frame(node), } retvalue = tags.get(n.localName) if retvalue: return retvalue(n) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (n.localName,))
def createBarCodes(): """ Create barcode examples and embed in a PDF """ c = canvas.Canvas("barcodes.pdf", pagesize=letter) barcode_value = "12345678999M" barcode39 = code39.Extended39(barcode_value) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) # code93 also has an Extended and MultiWidth version barcode93 = code93.Standard93(barcode_value) barcode128 = code128.Code128(barcode_value) # the multiwidth barcode appears to be broken #barcode128Multi = code128.MultiWidthBarcode(barcode_value) barcode_usps = usps.POSTNET("50158-9999") codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps] x = 1 * mm y = 260 * mm x1 = 6.4 * mm for code in codes: code.drawOn(c, x, y) y = y - 30 * mm barcode_value = "123456789990" # draw the eanbc8 code barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value) bounds = barcode_eanbc8.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc8) renderPDF.draw(d, c, 150 * mm, 150 * mm) # # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc13) renderPDF.draw(d, c, 150 * mm, 100 * mm) # # draw a QR code qr_code = qr.QrCodeWidget('www.ghf.com') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0]) d.add(qr_code) renderPDF.draw(d, c, 150 * mm, 50 * mm) c.save()
def process_order(request): date = datetime.now() if not request.user.is_authenticated: return render(request, 'myapp/login_error.html') else: print request.user tracking_id = request.GET.get('pesapal_transaction_tracking_id', '') reference = request.GET.get('pesapal_merchant_reference', '') errors = '' msg = '' if tracking_id and reference: params = { 'pesapal_merchant_reference': reference, 'pesapal_transaction_tracking_id': tracking_id } client = pesapal.PesaPal(consumer_key, consumer_secret, True) pesapal_request = client.queryPaymentStatus(params) url = pesapal_request.to_url() #print url pesapal_response = requests.get(url) pesapal_response_data = pesapal_response.text #print pesapal_response_data pesapal_status = pesapal_response_data.split('=')[1] #email = request.user #email = email.email confirmation_code = random.randint(1, 1000) if pesapal_status == 'COMPLETED': response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="barcode.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) p.setLineWidth(.3) p.setFont('Helvetica', 12) p.drawString(30, 750, 'KaribuPay Ticket') p.drawString(30, 735, 'Event Ticket') p.drawString(350, 750, str(date)) barcode = code39.Extended39(str(confirmation_code), barWidth=0.5 * mm, barHeight=20 * mm) barcode.drawOn(p, 30, 600) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) print confirmation_code msg = 'Transaction was successful' print 'Transaction was successful' else: msg = 'Transaction status is %s' % (pesapal_status) print 'Transaction status is %s' % (pesapal_status) p_ref = Pesapal(tracking_id=tracking_id, reference=reference, status=pesapal_status) #p_ref.save() else: errors = 'Please Try again' return response
def mark_dispatched(request): orders = request.GET.getlist('order') mailHost = "smtp.zoho.com" mailUsername = "******" mailPassword = "******" sender = "*****@*****.**" for orderUUID in orders: order = Order.objects.get(id=orderUUID) item_no = order.get_item_no() order.status = 4 order.dispatched_time = datetime.now() order.save() order_id = "order_id: " + order.id + "\n" order_destination = order.clinic.__str__()+ "\n" p = canvas.Canvas("ShippingLabel.pdf",pagesize=letter) barcode_value = order_id barcode39 = code39.Extended39(barcode_value) p.drawString(10*mm, 260*mm, "Order ID: " + order_id) barcode39.drawOn(p, 10*mm, 235*mm) order_detail = OrderContent.objects.filter(order=orderUUID) p.drawString(10*mm, 220*mm, "Destination (Clinic): " + str(order.clinic)) p.drawString(10*mm, 210*mm, "Items (" + str(order.get_total_weight()) + " kg): ") x = 10*mm y = 205*mm for item in order_detail: p.drawString(x, y, "(Type: " + str(item.medical_supply.type) + ") " + str(item.medical_supply.description) + ": " + str(item.quantity) + " X " + str(item.medical_supply.weight) + " kg = " + str(item.quantity * item.medical_supply.weight) + " kg") y -= 5*mm p.save() receiver= order.order_by.email print ( str(order.order_by.email)) msg = MIMEMultipart() msg['From']= formataddr(["Dispatcher",sender]) msg['To'] = receiver msg['Subject']= "Shipping label" body= "Below is the PDF file containing the shipping label" msg.attach(MIMEText(body,'plain')) filename = "ShippingLabel.pdf" attachment= open(filename, 'rb') part = MIMEBase('application','octect-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition',"attachment; filename= "+filename) msg.attach(part) try: smtpObj = SMTP_SSL(mailHost, 465) smtpObj.login(mailUsername, mailPassword) smtpObj.sendmail(sender, receiver, msg.as_string()) print("Email Sent") except SMTPException: print("Failed to send email") return redirect('dispatch:order_dispatch', permanent=True)
def getShippingLabel(request, order_id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename="'+order_id+'.pdf"' # Create a file-like buffer to receive PDF data. buffer = BytesIO() # logger.error(buffer) # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer, pagesize=letter) barcode_value = order_id barcode39 = code39.Extended39(barcode_value) # barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) # barcode93 = code93.Standard93(barcode_value) # barcode128 = code128.Code128(barcode_value) # barcode_usps = usps.POSTNET("50158-9999") # codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps] # x = 65*mm # y = 225*mm p.drawString(10*mm, 260*mm, "Order ID: " + order_id) barcode39.drawOn(p, 10*mm, 235*mm) # for code in codes: # code.drawOn(p, x, y) # y = y - 5*mm # p.drawString(x+10*mm, y, order_id) # y = y - 40*mm # get the information of the order overview = get_object_or_404(Order, id=order_id) order_detail = OrderContent.objects.filter(order=overview) p.drawString(10*mm, 220*mm, "Destination (Clinic): " + str(overview.clinic)) p.drawString(10*mm, 210*mm, "Items (" + str(overview.get_total_weight()) + " kg): ") x = 10*mm y = 205*mm for item in order_detail: p.drawString(x, y, "(Type: " + str(item.medical_supply.type) + ") " + str(item.medical_supply.description) + ": " + str(item.quantity) + " X " + str(item.medical_supply.weight) + " kg = " + str(item.quantity * item.medical_supply.weight) + " kg") y -= 5*mm # Close the PDF object cleanly, and we're done. p.showPage() p.save() # present the option to save the file. #return FileResponse(buffer, as_attachment=True, filename='hello.pdf') pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def _flowable(self, node, extra_style=None): if node.tag == 'para': style = self.styles.para_style_get(node) if extra_style: style.__dict__.update(extra_style) result = [] for i in self._textual(node).split('\n'): result.append( platypus.Paragraph( i, style, **(utils.attr_get(node, [], {'bulletText': 'str'})))) return result elif node.tag == 'barCode': try: from reportlab.graphics.barcode import code128 from reportlab.graphics.barcode import code39 from reportlab.graphics.barcode import code93 from reportlab.graphics.barcode import common from reportlab.graphics.barcode import fourstate from reportlab.graphics.barcode import usps except Exception, e: return None args = utils.attr_get( node, [], { 'ratio': 'float', 'xdim': 'unit', 'height': 'unit', 'checksum': 'int', 'quiet': 'int', 'width': 'unit', 'stop': 'bool', 'bearers': 'int', 'barWidth': 'float', 'barHeight': 'float' }) codes = { 'codabar': lambda x: common.Codabar(x, **args), 'code11': lambda x: common.Code11(x, **args), 'code128': lambda x: code128.Code128(x, **args), 'standard39': lambda x: code39.Standard39(x, **args), 'standard93': lambda x: code93.Standard93(x, **args), 'i2of5': lambda x: common.I2of5(x, **args), 'extended39': lambda x: code39.Extended39(x, **args), 'extended93': lambda x: code93.Extended93(x, **args), 'msi': lambda x: common.MSI(x, **args), 'fim': lambda x: usps.FIM(x, **args), 'postnet': lambda x: usps.POSTNET(x, **args), } code = 'code128' if node.get('code'): code = node.get('code').lower() return codes[code](self._textual(node))
def generarEtiqueta(request, ubigeo): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "attachment; filename="+ubigeo+".pdf" buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=70, leftMargin=70, topMargin=60, bottomMargin=18,) story = [] string = ubigeo st = code39.Extended39(string) story.append(st) doc.build(story) response.write(buff.getvalue()) buff.close() return response
def button_print_barcode(self): # Clear the message window self.parent.set_stat_message() if self.parent.currentGear: self.parent.set_stat_message( 'Writing barcode: {}, {} to directory: {}'.format( self.parent.currentGear.Name, self.parent.currentGear.ID, self.parent.barCodeDir)) # TODO: Figure out how many characters/line that can be written on under the bar code, then split the gear # name over however many lines are needed to write the whole name from reportlab.graphics.barcode import code39 from reportlab.lib.pagesizes import letter from reportlab.lib.units import mm from reportlab.pdfgen import canvas barcode_value = self.parent.currentGear.ID barcode_name = self.parent.currentGear.Name file_name = os.path.join( self.parent.barCodeDir, '{}_{}.pdf'.format(barcode_value, barcode_name)) c = canvas.Canvas(file_name, pagesize=letter) c.setFont('Helvetica-Bold', 6) barcode39 = code39.Extended39(barcode_value) x = 1 * mm y = 270 * mm barcode39.drawOn(c, x, y) w = barcode39.width / 2 c.drawCentredString(x + w, y - 2 * mm, barcode_value) c.drawCentredString(x + w, y - 4 * mm, barcode_name[:20]) c.save() else: self.parent.set_stat_message(Util.noActiveGear, c='red') self.gDissAmbSearch.showPopup() if self.gDissAmbSearch.count( ) > 1 and self.gDissAmbSearch.currentIndex() == 1: self.gDissAmbSearch.showPopup()
def code39_demo(barcode_value): doc = SimpleDocTemplate('code39_demo.pdf') styles = getSampleStyleSheet() flowables = [] flowables.append(Paragraph('Code 39 Standard:', style=styles['Normal'])) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) flowables.append(barcode39Std) flowables.append(Spacer(0, 25)) flowables.append(Paragraph('Code 39 Extended:', style=styles['Normal'])) barcode39 = code39.Extended39(barcode_value) flowables.append(barcode39) doc.build(flowables)
def render_page(self, batch_page, images): self.render_fixtures() # barcode barcode = code39.Extended39(barcode_encode(batch_page), barWidth=self.layout.bar_width, barHeight=self.layout.box_height) pdf = self.canvas pdf.setStrokeColorRGB(0, 0, 0) pdf.setFillColorRGB(0, 0, 0) barcode.drawOn(pdf, self.layout.barcode_x, self.layout.barcode_y) for image in images: pdf.drawImage(image.embed_path(image.rotate), image.page_x, image.page_y, width=image.page_w, height=image.page_h) pass pdf.showPage() pass
def barcode(request): date = datetime.now() print date response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="barcode.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) p.setLineWidth(.3) p.setFont('Helvetica', 12) p.drawString(30, 750, 'KaribuPay Ticket') p.drawString(30, 735, 'Event Ticket') p.drawString(350, 750, str(date)) barcode = code39.Extended39("123456789", barWidth=0.5 * mm, barHeight=20 * mm) barcode.drawOn(p, 30, 600) p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def createBarCodes(c): barcode_value = '0112358' barcode39 = code39.Extended39(barcode_value) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) barcode93 = code93.Standard93(barcode_value) barcode128 = code128.Code128(barcode_value) # barcode128Multi = code128.MultiWidthBarcode(barcode_value) barcode_usps = usps.POSTNET('50158-9999') codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps] x = 1 * mm y = 285 * mm for code in codes: code.drawOn(c, x, y) y = y - 15 * mm barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value) d = Drawing(50, 10) d.add(barcode_eanbc8) renderPDF.draw(d, c, 15, 555) barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) d = Drawing(50, 10) d.add(barcode_eanbc13) renderPDF.draw(d, c, 15, 465) qr_code = qr.QrCodeWidget('http://www.baidu.com') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(45, 45, transform=[45./width, 0,0,45./height, 0, 0]) d.add(qr_code) renderPDF.draw(d, c, 15, 405)
def get_certificado(datos, response): p = canvas.Canvas(response) # Draw things on the PDF. p.setFont("Courier", 18) p.drawString(50, 725, "Intercambio y manejo de Información") p.setFont("Courier", 14) p.drawString(50, 700, "Certificado de participación") p.setFont("Courier", 30) p.drawString(50, 650, "%s"%datos['jugador']) p.drawString(50, 600, "%s puntos"%datos['puntaje']) # codigo de barra barcode=code39.Extended39("%s"% datos['jugador'].split('.')[1],barWidth=0.5*mm,barHeight=20*mm) barcode.drawOn(p,30,480) #hash p.setFont("Courier", 20) p.drawString(50, 420, "%s"%datos['hash']) # Close the PDF object cleanly, and we're done. p.showPage() p.save()
def make_label(canvas, lines, bar_data, size): x_offset = size[0] / 15.0 y_offset = size[1] / 20.0 address = { "fontName" : "Helvetica", "fontSize" : 12 } small = { "fontName" : "Helvetica", "fontSize" : 8 } x = x_offset y = y_offset dy = 20 style = address for text in lines: canvas.setFont(style["fontName"], style["fontSize"]) canvas.drawString(x, size[1] - y, text) y += dy if not bar_data: return # Generate the unique barcode bar_width = 0.04 bar_height = 0.3 barcode = code39.Extended39(bar_data, barWidth=bar_width * cm, barHeight= bar_height * cm, checksum=0, bearers=0.5, quiet=0) barcode.drawOn(canvas, x, size[1] - y) tails = ( bar_data, ) y += 10 style = small for text in tails: canvas.setFont(style["fontName"], style["fontSize"]) canvas.drawString(x, size[1] - y, text) y += dy
def _flowable(self, node, extra_style=None): if node.tag=='pto': return self._pto(node) if node.tag=='para': style = self.styles.para_style_get(node) if extra_style: style.__dict__.update(extra_style) result = [] for i in self._textual(node).split('\n'): result.append(platypus.Paragraph(i, style, **(utils.attr_get(node, [], {'bulletText':'str'})))) return result elif node.tag=='barCode': try: from reportlab.graphics.barcode import code128 from reportlab.graphics.barcode import code39 from reportlab.graphics.barcode import code93 from reportlab.graphics.barcode import common from reportlab.graphics.barcode import fourstate from reportlab.graphics.barcode import usps from reportlab.graphics.barcode import createBarcodeDrawing except ImportError: _logger.warning("Cannot use barcode renderers:", exc_info=True) return None args = utils.attr_get(node, [], {'ratio':'float','xdim':'unit','height':'unit','checksum':'int','quiet':'int','width':'unit','stop':'bool','bearers':'int','barWidth':'float','barHeight':'float'}) codes = { 'codabar': lambda x: common.Codabar(x, **args), 'code11': lambda x: common.Code11(x, **args), 'code128': lambda x: code128.Code128(str(x), **args), 'standard39': lambda x: code39.Standard39(str(x), **args), 'standard93': lambda x: code93.Standard93(str(x), **args), 'i2of5': lambda x: common.I2of5(x, **args), 'extended39': lambda x: code39.Extended39(str(x), **args), 'extended93': lambda x: code93.Extended93(str(x), **args), 'msi': lambda x: common.MSI(x, **args), 'fim': lambda x: usps.FIM(x, **args), 'postnet': lambda x: usps.POSTNET(x, **args), 'ean13': lambda x: createBarcodeDrawing('EAN13', value=str(x), **args), 'qrcode': lambda x: createBarcodeDrawing('QR', value=x, **args), } code = 'code128' if node.get('code'): code = node.get('code').lower() return codes[code](self._textual(node)) elif node.tag=='name': self.styles.names[ node.get('id')] = node.get('value') return None elif node.tag=='xpre': style = self.styles.para_style_get(node) return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int','frags':'int'}))) elif node.tag=='pre': style = self.styles.para_style_get(node) return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int'}))) elif node.tag=='illustration': return self._illustration(node) elif node.tag=='blockTable': return self._table(node) elif node.tag=='title': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Title'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif re.match('^h([1-9]+[0-9]*)$', (node.tag or '')): styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading'+str(node.tag[1:])] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif node.tag=='image': image_data = False if not node.get('file'): if node.get('name'): if node.get('name') in self.doc.images: _logger.debug("Image %s read ", node.get('name')) image_data = self.doc.images[node.get('name')].read() else: _logger.warning("Image %s not defined", node.get('name')) return False else: import base64 newtext = node.text if self.localcontext: newtext = utils._process_text(self, node.text or '') image_data = base64.decodestring(newtext) if not image_data: _logger.debug("No inline image data") return False image = StringIO(image_data) else: _logger.debug("Image get from file %s", node.get('file')) image = _open_image(node.get('file'), path=self.doc.path) return platypus.Image(image, mask=(250,255,250,255,250,255), **(utils.attr_get(node, ['width','height']))) elif node.tag=='spacer': if node.get('width'): width = utils.unit_get(node.get('width')) else: width = utils.unit_get('1cm') length = utils.unit_get(node.get('length')) return platypus.Spacer(width=width, height=length) elif node.tag=='section': return self.render(node) elif node.tag == 'pageNumberReset': return PageReset() elif node.tag in ('pageBreak', 'nextPage'): return platypus.PageBreak() elif node.tag=='condPageBreak': return platypus.CondPageBreak(**(utils.attr_get(node, ['height']))) elif node.tag=='setNextTemplate': return platypus.NextPageTemplate(str(node.get('name'))) elif node.tag=='nextFrame': return platypus.CondPageBreak(1000) # TODO: change the 1000 ! elif node.tag == 'setNextFrame': from reportlab.platypus.doctemplate import NextFrameFlowable return NextFrameFlowable(str(node.get('name'))) elif node.tag == 'currentFrame': from reportlab.platypus.doctemplate import CurrentFrameFlowable return CurrentFrameFlowable(str(node.get('name'))) elif node.tag == 'frameEnd': return EndFrameFlowable() elif node.tag == 'hr': width_hr=node.get('width') or '100%' color_hr=node.get('color') or 'black' thickness_hr=node.get('thickness') or 1 lineCap_hr=node.get('lineCap') or 'round' return platypus.flowables.HRFlowable(width=width_hr,color=color.get(color_hr),thickness=float(thickness_hr),lineCap=str(lineCap_hr)) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.tag,)) return None
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib.units import mm from reportlab.graphics.barcode import code39 import os # generate a canvas pagesize = (50*mm, 25*mm) #Canvas Size c=canvas.Canvas("barcode_example1.pdf",pagesize=pagesize) Manufacture = "OPTILAB" barcodetext = "B6P755464454" pn = "IML-1550-PM-V" barcode=code39.Extended39(barcodetext,barWidth=0.15*mm,barHeight=5*mm) text = c.beginText(1*mm, 20*mm) text.setFont("Courier", 9) text.textLine("MANUFACTURE : {m}".format(m= Manufacture)) c.drawText(text) text0 = c.beginText(1*mm, 15*mm) text0.setFont("Courier", 9) text0.textLine("PN : {pn}".format(pn= pn)) c.drawText(text0) barcode.drawOn(c,1*mm,8*mm) text1 = c.beginText(13*mm, 5*mm) text1.setFont("Courier", 9)
def _flowable(self, node): if node.localName == 'para': style = self.styles.para_style_get(node) return platypus.Paragraph( self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'name': self.styles.names[node.getAttribute('id')] = node.getAttribute( 'value') return None elif node.localName == 'xpre': style = self.styles.para_style_get(node) return platypus.XPreformatted( self._textual(node), style, **(utils.attr_get(node, [], { 'bulletText': 'str', 'dedent': 'int', 'frags': 'int' }))) elif node.localName == 'pre': style = self.styles.para_style_get(node) return platypus.Preformatted( self._textual(node), style, **(utils.attr_get(node, [], { 'bulletText': 'str', 'dedent': 'int' }))) elif node.localName == 'illustration': return self._illustration(node) elif node.localName == 'blockTable': return self._table(node) elif node.localName == 'title': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Title'] return platypus.Paragraph( self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h1': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading1'] return platypus.Paragraph( self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h2': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading2'] return platypus.Paragraph( self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h3': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading3'] return platypus.Paragraph( self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'image': return platypus.Image( node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get( node, ['width', 'height', 'preserveAspectRatio', 'anchor']))) elif node.localName == 'spacer': if node.hasAttribute('width'): width = utils.unit_get(node.getAttribute('width')) else: width = utils.unit_get('1cm') length = utils.unit_get(node.getAttribute('length')) return platypus.Spacer(width=width, height=length) elif node.localName == 'barCode': return code39.Extended39(self._textual(node)) elif node.localName == 'pageBreak': return platypus.PageBreak() elif node.localName == 'condPageBreak': return platypus.CondPageBreak(**(utils.attr_get(node, ['height']))) elif node.localName == 'setNextTemplate': return platypus.NextPageTemplate(str(node.getAttribute('name'))) elif node.localName == 'nextFrame': return platypus.CondPageBreak(1000) # TODO: change the 1000 ! elif node.localName == 'ul': return self._list(node) elif node.localName == 'keepInFrame': substory = self.render(node) kwargs = { "maxWidth": 0, "maxHeight": 0, "content": substory, } mode = node.getAttribute("onOverflow") if mode: kwargs["mode"] = mode name = node.getAttribute("id") if name: kwargs["name"] = name kwargs.update( utils.attr_get(node, ['maxWidth', 'maxHeight', 'mergeSpace'], { 'maxWidth': 'int', 'maxHeight': 'int' })) return platypus.KeepInFrame(**kwargs) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.localName, )) return None
def createBarCodes(): """ Create barcode examples and embed in a PDF """ c = canvas.Canvas("barcodes.pdf", pagesize=letter) barcode_value = [ '0004-0000000001', '0004-0000000002', '0004-0000000003', '0004-0000000004', '0004-0000000005', '0004-0000000013', '0004-0000000028', '0004-0000000029', '0004-0000000030', '0004-0000000031', ] #barcode_value = "1234567890" barcode_value = "0004-0000000001" barcode39 = code39.Extended39(barcode_value, humanReadable=True) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1, humanReadable=True) # code93 also has an Extended and MultiWidth version barcode93 = code93.Standard93(barcode_value, humanReadable=True) barcode128 = code128.Code128(barcode_value, humanReadable=True) # the multiwidth barcode appears to be broken #barcode128Multi = code128.MultiWidthBarcode(barcode_value) barcode_usps = usps.POSTNET("50158-9999") codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps] x = 1 * mm y = 285 * mm x1 = 6.4 * mm for code in codes: code.drawOn(c, x, y) y = y - 15 * mm # draw the eanbc8 code """ barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value) bounds = barcode_eanbc8.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc8) renderPDF.draw(d, c, 15, 555) """ # draw the eanbc13 code """ barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc13) renderPDF.draw(d, c, 15, 465) """ c.save()
def createBarCodes(): """ Create barcode examples and embed in a PDF """ #Taking the filename from the user name = input('enter a filename(.pdf) :') c = canvas.Canvas(name, pagesize=letter) #Setting the 10 digit barcode value barcode_value = str(random_with_N_digits(12)) barcode39 = code39.Extended39(barcode_value) barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1) # code93 also has an Extended and MultiWidth version barcode93 = code93.Standard93(barcode_value) barcode128 = code128.Code128(barcode_value) # the multiwidth barcode appears to be broken #barcode128Multi = code128.MultiWidthBarcode(barcode_value) codes = [barcode39, barcode39Std, barcode93, barcode128] x = 1 * mm y = 285 * mm x1 = 6.4 * mm for code in codes: code.drawOn(c, x, y) y = y - 15 * mm # draw the eanbc8 code barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value) bounds = barcode_eanbc8.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc8) renderPDF.draw(d, c, 15, 555) # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(50, 10) d.add(barcode_eanbc13) renderPDF.draw(d, c, 15, 465) # draw a QR code qr_code = qr.QrCodeWidget(barcode_value) bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(45, 45, transform=[45. / width, 0, 0, 45. / height, 0, 0]) d.add(qr_code) renderPDF.draw(d, c, 15, 405) c.save()
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib.units import mm #I"ll be generating code39 barcodes, others are available from reportlab.graphics.barcode import code39 # generate a canvas (A4 in this case, size doesn"t really matter) c = canvas.Canvas("/tmp/barcode_example.pdf", pagesize=A4) c = canvas.Canvas("./barcode_example.pdf", pagesize=A4) # create a barcode object # (is not displayed yet) # The encode text is "123456789" # barHeight encodes how high the bars will be # barWidth encodes how wide the "narrowest" barcode unit is barcode = code39.Extended39("123456789", barWidth=0.5 * mm, barHeight=20 * mm) # drawOn puts the barcode on the canvas at the specified coordinates barcode.drawOn(c, 100 * mm, 100 * mm) # now create the actual PDF c.showPage() c.save()
def draw(self): barcode = code39.Extended39(self.encoded_all, barWidth=0.2 * mm, barHeight=20 * mm) barcode.drawOn(self.canv, 100 * mm, 100 * mm)
def afterDrawPage(self, canvas, doc): IDcompte_payeur = doc._nameSpace["IDcompte_payeur"] dictCompte = DICT_COMPTES[IDcompte_payeur] # Dessin du coupon-réponse vertical coupon_vertical = doc.modeleDoc.FindObjet("coupon_vertical") if DICT_OPTIONS["coupon"] == True and coupon_vertical != None: x, y, largeur, hauteur = doc.modeleDoc.GetCoordsObjet( coupon_vertical) canvas.saveState() # Ciseaux canvas.drawImage( Chemins.GetStaticPath("Images/Special/Ciseaux.png"), x + 1 * mm, y + hauteur - 5 * mm, 0.5 * cm, 1 * cm, preserveAspectRatio=True) # Rectangle canvas.setDash(3, 3) canvas.setLineWidth(0.25) canvas.setStrokeColorRGB(0, 0, 0) canvas.rect(x, y, largeur, hauteur, fill=0) # Textes canvas.rotate(90) canvas.setFont("Helvetica", 8) canvas.drawString( y + 2 * mm, -x - 4 * mm, _(u"Merci de joindre ce coupon à votre règlement")) canvas.setFont("Helvetica", 7) solde = dictCompte[ "solde_num"] #dictCompte["total"] - dictCompte["ventilation"] numero = dictCompte["numero"] nom = dictCompte["nomSansCivilite"] canvas.drawString(y + 2 * mm, -x - 9 * mm, u"%s - %.02f %s" % (numero, solde, SYMBOLE)) canvas.drawString(y + 2 * mm, -x - 12 * mm, u"%s" % nom) # Code-barres if DICT_OPTIONS[ "codeBarre"] == True and "{CODEBARRES_NUM_RAPPEL}" in dictCompte: barcode = code39.Extended39( dictCompte["{CODEBARRES_NUM_RAPPEL}"], humanReadable=False) barcode.drawOn(canvas, y + 36 * mm, -x - 13 * mm) canvas.restoreState() # Dessin du coupon-réponse horizontal coupon_horizontal = doc.modeleDoc.FindObjet("coupon_horizontal") if DICT_OPTIONS["coupon"] == True and coupon_horizontal != None: x, y, largeur, hauteur = doc.modeleDoc.GetCoordsObjet( coupon_horizontal) canvas.saveState() # Rectangle canvas.setDash(3, 3) canvas.setLineWidth(0.25) canvas.setStrokeColorRGB(0, 0, 0) canvas.rect(x, y, largeur, hauteur, fill=0) # Textes canvas.setFont("Helvetica", 8) canvas.drawString( x + 2 * mm, y + hauteur - 4 * mm, _(u"Merci de joindre ce coupon à votre règlement")) canvas.setFont("Helvetica", 7) solde = dictCompte[ "solde_num"] #dictCompte["total"] - dictCompte["ventilation"] numero = dictCompte["numero"] nom = dictCompte["nomSansCivilite"] canvas.drawString(x + 2 * mm, y + hauteur - 9 * mm, u"%s - %.02f %s" % (numero, solde, SYMBOLE)) canvas.drawString(x + 2 * mm, y + hauteur - 12 * mm, u"%s" % nom) # Code-barres if DICT_OPTIONS[ "codeBarre"] == True and "{CODEBARRES_NUM_RAPPEL}" in dictCompte: barcode = code39.Extended39( dictCompte["{CODEBARRES_NUM_RAPPEL}"], humanReadable=False) barcode.drawOn(canvas, x + 36 * mm, y + hauteur - 13 * mm) # Ciseaux canvas.rotate(-90) canvas.drawImage( Chemins.GetStaticPath("Images/Special/Ciseaux.png"), -y - hauteur + 1 * mm, x + largeur - 5 * mm, 0.5 * cm, 1 * cm, preserveAspectRatio=True) canvas.restoreState() canvas.saveState() # Insertion du code39 if DICT_OPTIONS["codeBarre"] == True: doc.modeleDoc.DessineCodesBarres(canvas, dictChamps=dictCompte) # Insertion des lignes de textes doc.modeleDoc.DessineImages(canvas, dictChamps=dictCompte) doc.modeleDoc.DessineTextes(canvas, dictChamps=dictCompte) canvas.restoreState()
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 zona_conv = str(zonaq).zfill(3) + "00" response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=" + 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_Tab.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_Tab.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_Tab.objects.filter(ubigeo=ubigeo, zona=zonaq).count()) resumen = v_ReporteResumenDistritoTab.objects.get(ubigeo=ubigeo, zona=zonaq) primero = v_ReporteSecciones_Tab.objects.filter( ubigeo=distrito.ubigeo, zona=zonaq).order_by('aeu_final').first() ultimo = v_ReporteSecciones_Tab.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')]) x = 0 for aeu in cond: # string = "02060100100" # st = code39.Extended39(string) # story.append(st) prim_secc = str(primero.seccion).zfill(3) ulti_secc = str(ultimo.seccion).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())) 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_tab\\" + str(lista_distritos[ubigein]) + "\\" + zoner) == False: os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + zoner) destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str( ubigeo) + "\\" + zonaq + "\\" + 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 = "" 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) # # # nombreccpp = Ccpp.objects.filter(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 áREAS 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>SECCIóN 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 = v_ReporteSecciones_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonaq)).order_by( 'seccion', 'aeu_final')[0:33] cant_secciones = int( v_ReporteSecciones_Tab.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) 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) aeusi_second = v_ReporteSecciones_Tab.objects.filter( Q(ubigeo=ubigeo), Q(zona=zonaq))[33:] if cant_secciones > 34: 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) # aeusi_three = v_ReporteSecciones_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonaq))[85:136] # if cant_secciones > 85: # story.append(c) # # Aca va el segundo for # for aeusis_second in aeusi_three: # 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
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'] ] 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') ] ) 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. 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(str(aeu.ccdi).decode('latin-1'), h1), '', Paragraph(str('<strong>SECCION Nº</strong>'), h1), Paragraph(aeu.seccion, 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>CATEGORIA 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) #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>Or Reg</strong>", "<strong>Frent. 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. 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.9 * cm, 1 * 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', (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. UBICACION GEOGRAFICA</strong>', h1), '', '', '', Paragraph('<strong>B. UBICACION 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>SECCION Nº</strong>'), h1), aeu.seccion], [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>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: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.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) + "" + vivienda.p29_p elif vivienda.p29_a in (5, 6): jefe_hogar = str(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" # 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 len_viviendap21 = len(vivienda.p21) - 1 if ' ' not in vivienda.p21: p21 = vivienda.p21 else: firstblank_viviendap21 = (vivienda.p21).index(' ') p21 = vivienda.p21[:firstblank_viviendap21] + '\n' + vivienda.p21[len_viviendap21 - firstblank_viviendap21:] 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_hogar if not jefe_hogar == None else '') ] u = Table(table2, colWidths=[0.8 * cm, 0.9 * cm, 1 * 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), (13, 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')[18:] if toti_viv>19: 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.p29 == 5: if vivienda.p29_a in (1, 2, 3, 4): jefe_hogar = str(pta_f) + "" + vivienda.p29_p elif vivienda.p29_a in (5, 6): jefe_hogar = str(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" # 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 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 "", vivienda.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_hogar if not jefe_hogar == None else '') ] u_second = Table(table2, colWidths=[0.8 * cm, 0.9 * cm, 1 * 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), (13, 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 gerar_envelope(self): try: tamanho_lista = len(self.lacres_atual) f = tempfile.NamedTemporaryFile() nome_pdf = f.name + '.pdf' pdf = canvas.Canvas(nome_pdf, pagesize=A4) y = 700 x_inicial = 40 * mm pdf.setTitle(nome_pdf) pdf.setFont("Helvetica-Bold", 22) pdf.drawString(x_inicial, y, 'Lacres') y = y - 25 pdf.setFont("Helvetica-Bold", 16) pdf.drawString(x_inicial, y, "Quantidade: {}".format(tamanho_lista)) y = y - 25 codigo = self.lacres_atual[0].codigo pdf.setFont("Helvetica-Bold", 16) pdf.drawString(x_inicial, y, 'Código: {}'.format(codigo)) pdf.setFont("Helvetica", 12) i = 0 f = 4 continuar = True lista_lacres = [] for lacre in self.lacres_atual: lista_lacres.append(lacre.numero) while continuar: y -= 25 s = ' / '.join(lista_lacres[i:f]) pdf.drawString(x_inicial, y, s) i += 4 f += 4 if i > tamanho_lista: continuar = False bc = code39.Extended39(codigo, barWidth=0.5 * mm, barHeight=20 * mm) y = y - 70 bc.drawOn(pdf, x_inicial - 20, y) pdf.setFont("Helvetica-Bold", 14) linha = '--------------------------------------------------------------------------------------------------' pdf.drawString(x_inicial - 50, 380, linha) # now create the actual PDF pdf.showPage() pdf.save() subprocess.Popen([nome_pdf], shell=True) except Exception as e: print('erro' + str(e))