def draw_code128_global_id(canvas, survey): if survey.global_id is None: raise AssertionError # Only allow ascii barcode_value = survey.global_id.encode('ascii') barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = (survey.defs.paper_width - defs.corner_mark_right + defs.corner_mark_left) / 2 barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x # Center barcode_x = barcode_x - barcode.width / mm / 2.0 renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def addCPIPage(canvas_para, length): """ 函数功能:增加CPI页 :param canvas_para: :return: """ c = canvas_para cpi_df = ts.get_cpi() cpi_df['month'] = cpi_df.apply(lambda x:stdMonthDate(x['month']), axis=1) cpi_df = cpi_df.sort_values(by='month',ascending=False).head(length).sort_values(by='month',ascending=True) cpi = ExtractPointFromDf_DateX(df_origin=cpi_df, date_col='month', y_col='cpi', timeAxis='month') gdp_pull_drawing = genLPDrawing([tuple(cpi)], data_note=['CPI增长率'], timeAxis='month') renderPDF.draw(drawing=gdp_pull_drawing, canvas=c, x=10, y=letter[1] * 0.6) c.showPage() return c
def respond_with_permit_pdf(permit): """ :param permit: The permit for which to generate the PDF :return: An HTTP response """ # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = 'attachment; filename="permit_%05d.pdf"' % permit.pk # Produce PDF using ReportLab: p = canvas.Canvas(response) pageW = defaultPageSize[0] pageH = defaultPageSize[1] refX = pageW / 2 refY = pageH - 6.25 * inch # The tag that gets placed near the location. p.rect(refX - 2.0 * inch, refY - 0 * inch, 4 * inch, 5 * inch) refY += 4.5 * inch # Static header: p.setFont("Helvetica", 14) p.drawCentredString(refX, refY - 0.00 * inch, "XEROCRAFT HACKERSPACE") p.setFont("Helvetica-Bold", 28) p.drawCentredString(refX, refY - 0.40 * inch, "PARKING PERMIT") p.setFont("Helvetica", 14) p.drawCentredString(refX, refY - 0.66 * inch, "MEMBER-CLAIMED PROPERTY") # Changing refY allows the follwoing to be moved up/down as a group, w.r.t. the text above. refY -= 3.0 * inch # QR Code: qr = QrCodeWidget('{"permit":%d}' % permit.id) qrSide = 2.5 * inch # REVIEW: This isn't actually 2.3 inches. What is it? bounds = qr.getBounds() qrW = bounds[2] - bounds[0] qrH = bounds[3] - bounds[1] drawing = Drawing(1000, 1000, transform=[qrSide / qrW, 0, 0, qrSide / qrH, 0, 0]) drawing.add(qr) renderPDF.draw(drawing, p, refX - qrSide / 2, refY) p.setFont("Helvetica", 10) p.drawCentredString(refX, refY - 0.00 * inch, permit.short_desc) u = permit.owner.auth_user p.drawCentredString(refX, refY - 0.20 * inch, "Parked by: %s %s" % (u.first_name, u.last_name)) p.drawCentredString(refX, refY - 0.40 * inch, "Permit #%05d" % permit.id) p.setFont("Helvetica", 14) if permit.ok_to_move: p.drawCentredString(refX, refY - 0.80 * inch, "It is OK to carefully move this item") p.drawCentredString(refX, refY - 1.00 * inch, "to another location, if required.") else: p.drawCentredString(refX, refY - 0.80 * inch, "This item is fragile. Please attempt") p.drawCentredString(refX, refY - 1.00 * inch, "to contact me before moving it.") p.showPage() p.save() return response
def IdentificaListaPresenca(myCanvas, disciplina, pagina): margin = 2 * cm marginleft = margin margintop = height - 1.1 * margin codigo = DataInvertida(disciplina.data) + '-' + disciplina.polo + \ '-' + disciplina.disciplina + '-' + disciplina.prova + '-' + \ 'presenca' + '-' + format(pagina, '02d') # Dados do aluno e da prova myCanvas.setFont('Helvetica-Bold', 12) myCanvas.drawString(marginleft + 1.1 * cm, 26 * cm, disciplina.nomePolo) myCanvas.drawString(marginleft + 1.6 * cm, 25.4 * cm, codigo) myCanvas.drawString(marginleft + 11.6 * cm, 25.4 * cm, disciplina.data) myCanvas.drawString(marginleft + 2 * cm, 24.8 * cm, disciplina.disciplina + ' - ' + disciplina.nomeDisciplina) # Coloca QR-Code no canto superior direito qrw = QrCodeWidget(codigo) qrsize = 100.0 b = qrw.getBounds() w = b[2] - b[0] h = b[3] - b[1] d = Drawing(qrsize, qrsize, transform=[qrsize/w, 0, 0, qrsize/h, 0, 0]) d.add(qrw) renderPDF.draw(d, myCanvas, 16 * cm, margintop - h + 28) return
def generateQR(value, file): packet = io.BytesIO() can = canvas.Canvas(packet) qrcode = qr.QrCodeWidget(value) bounds = qrcode.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(100, 100, transform=[300. / width, 0, 0, 300. / height, 0, 0]) d.add(qrcode) renderPDF.draw(d, can, 390, 430) can.save() packet.seek(0) new_pdf = PdfFileReader(packet) pdf = PdfFileReader(open(file, 'rb')) page = pdf.getPage(0) page2 = new_pdf.getPage(0) page.mergePage(page2) return page
def test_ean13(): # generate a canvas (A4 in this case, size doesn"t really matter) tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") # generate a canvas (A4 in this case, size doesn"t really matter) canvas1 = canvas.Canvas(tmpfile, (2.4 * inch, 2 * inch)) canvas1.saveState() canvas1.saveState() # create a barcode object # (is not displayed yet) # barHeight encodes how high the bars will be # barWidth encodes how wide the "narrowest" barcode unit is ean13 = "9781583228708" barcode1 = barcode.createBarcodeDrawing( "EAN13", value=str(ean13), validate=True, width=2.4 * inch, height=1.4 * inch, humanReadable=True, fontName="Helvetica", ) renderPDF.draw(barcode1, canvas1, 0, 0) canvas1.restoreState() canvas1.showPage() canvas1.save()
def draw_to_file(self, output_file, title): """Write the comparative plot to a file. Arguments: o output_file - The name of the file to output the information to, or a handle to write to. o title - A title to display on the graphic. """ width, height = self.page_size cur_drawing = Drawing(width, height) self._draw_title(cur_drawing, title, width, height) start_x = inch * .5 end_x = width - inch * .5 end_y = height - 1.5 * inch start_y = .5 * inch self._draw_scatter_plot(cur_drawing, start_x, start_y, end_x, end_y) if self.output_format == 'pdf': out_canvas = canvas.Canvas(output_file, pagesize = self.page_size) renderPDF.draw(cur_drawing, out_canvas, 0, 0) out_canvas.showPage() out_canvas.save() elif self.output_format == 'eps': renderPS.drawToFile(cur_drawing, output_file) else: raise ValueError("Invalid output format %s" % self.output_format)
def _draw_barcodearea(self, canvas: Canvas, op: OrderPosition, o: dict): content = o.get('content', 'secret') if content == 'secret': content = op.secret elif content == 'pseudonymization_id': content = op.pseudonymization_id level = 'H' if len(content) > 32: level = 'M' if len(content) > 128: level = 'L' reqs = float(o['size']) * mm kwargs = {} if o.get('nowhitespace', False): kwargs['barBorder'] = 0 qrw = QrCodeWidget(content, barLevel=level, barHeight=reqs, barWidth=reqs, **kwargs) d = Drawing(reqs, reqs) d.add(qrw) qr_x = float(o['left']) * mm qr_y = float(o['bottom']) * mm renderPDF.draw(d, canvas, qr_x, qr_y)
def create_diagram(cnarr, segarr, threshold, min_probes, outfname, male_reference): """Create the diagram.""" if cnarr and segarr: do_both = True # Draw segments on left, probes on right. cnarr_is_seg = False # Are probes actually the segmented values? else: if cnarr: cnarr_is_seg = False elif segarr: cnarr = segarr cnarr_is_seg = True else: raise ValueError("Must specify a filename as an argument or with " "the '-s' option, or both. You did neither.") do_both = False # Label genes where copy ratio value exceeds threshold cnarr = cnarr.shift_xx(male_reference) if cnarr_is_seg: gainloss = [] elif segarr: segarr = segarr.shift_xx(male_reference) gainloss = reports.gainloss_by_segment(cnarr, segarr, threshold) else: gainloss = reports.gainloss_by_gene(cnarr, threshold) gene_labels = [gl_row[0] for gl_row in gainloss if gl_row[5] >= min_probes] # Consolidate genes & coverage values as chromosome features features = collections.defaultdict(list) strand = 1 if do_both else None # Draw on the chr. right half or full width chrom_sizes = plots.chromosome_sizes(cnarr) if not cnarr_is_seg: cnarr = cnarr.squash_genes() for row in cnarr: if row.start - 1 >= 0 and row.end <= chrom_sizes[ row.chromosome]: # Sanity check feat_name = row.gene if row.gene in gene_labels else None features[row.chromosome].append( (row.start - 1, row.end, strand, feat_name, colors.Color(*plots.cvg2rgb(row.log2, not cnarr_is_seg)))) if do_both: # Draw segments in the left half of each chromosome (strand -1) for chrom, segrows in segarr.by_chromosome(): for srow in segrows: if srow.start - 1 >= 0 and srow.end <= chrom_sizes[ chrom]: # Sanity check features[chrom].append( (srow.start - 1, srow.end, -1, None, colors.Color(*plots.cvg2rgb(srow.log2, False)))) # Generate the diagram PDF if not outfname: outfname = cnarr.sample_id + '-diagram.pdf' drawing = build_chrom_diagram(features, chrom_sizes, cnarr.sample_id) cvs = canvas.Canvas(outfname, pagesize=PAGE_SIZE) renderPDF.draw(drawing, cvs, 0, 0) cvs.showPage() cvs.save() return outfname
def draw_code128_questionnaire_id(canvas, survey, id): # Only supports ascii for now (see also defs.py) barcode_value = unicode(id).encode('ascii') barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = defs.corner_mark_left barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x + defs.code128_hpad # The barcode should be flush left. barcode_x = barcode_x renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + \ defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def send_pdf1(bill_object): username = bill_object.user.username month = bill_object.month bill_unit = bill_object.billing_units bill_amount = bill_object.bill_amount billname = str(username) + str(month) + ".pdf" path = os.path.join(dir_path + "/static", billname) c = canvas.Canvas(path, pagesize=letter) #c= canvas.Canvas("Qrcodes1.pdf", pagesize=letter) c.setFontSize(size=20) c.drawString(20, 600, "Username:"******"Month:") c.drawString(250, 560, month) c.drawString(20, 520, "Billing_units:") c.drawString(250, 520, str(bill_unit)) c.drawString(20, 480, "Billing Amount:") c.drawString(250, 480, str(bill_amount)) qr_code = qr.QrCodeWidget(str(bill_object.id)) bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(60, 60, transform=[60. / width, 0, 0, 60. / height, 0, 0]) d.add(qr_code) renderPDF.draw(d, c, 500, 560) c.save() return billname
def draw_code128_sdaps_info(canvas, survey, page): # The page number is one based here already # The survey_id is a 32bit number, which means we need # 10 decimal digits to encode it, then we need to encode the # the page with at least 3 digits(just in case someone is insane enough # to have a questionnaire with more than 99 pages. # So use 10+4 digits barcode_value = "%010d%04d" % (survey.survey_id, page) barcode = createBarcodeDrawing("Code128", value=barcode_value, barWidth=defs.code128_barwidth / 25.4 * 72.0, height=defs.code128_height / 25.4 * 72.0, quiet=False) y = survey.defs.paper_height - defs.corner_mark_bottom x = survey.defs.paper_width - defs.corner_mark_right barcode_y = y - defs.code128_vpad - defs.code128_height barcode_x = x - defs.code128_hpad # The barcode should be flush left. barcode_x = barcode_x - barcode.width / mm renderPDF.draw(barcode, canvas, barcode_x * mm, barcode_y * mm) # Label text_x = barcode_x + barcode.width / mm / 2.0 text_y = barcode_y + defs.code128_height + 1 + defs.code128_text_font_size / 72.0 * 25.4 / 2.0 canvas.saveState() canvas.setFont(defs.code128_text_font, defs.code128_text_font_size) canvas.drawCentredString(text_x * mm, text_y * mm, barcode_value) canvas.restoreState()
def draw_qrcode(self, value, x, y, size=40, halign=None, valign=None): """ Helper function to draw a QR code @param value: the string to encode @param x: drawing position @param y: drawing position @param size: the size (edge length) of the QR code @param halign: horizontal alignment ("left"|"center"|"right"), default left @param valign: vertical alignment ("top"|"middle"|"bottom"), default bottom """ qr_code = qr.QrCodeWidget(value) bounds = qr_code.getBounds() w = bounds[2] - bounds[0] h = bounds[3] - bounds[1] transform = [float(size) / w, 0, 0, float(size) / h, 0, 0] d = Drawing(size, size, transform=transform) d.add(qr_code) hshift = vshift = 0 if halign == "right": hshift = size elif halign == "center": hshift = float(size) / 2.0 if valign == "top": vshift = size elif valign == "middle": vshift = float(size) / 2.0 renderPDF.draw(d, self.canv, x - hshift, y - vshift)
def addDemandsForGDPPage(canvas_para): """ 函数功能:三大需求对GDP的贡献 :param canvas_para: :return: """ c = canvas_para gdp_for = ts.get_gdp_for() end_for = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='end_for', timeAxis='year') asset_for = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='asset_for', timeAxis='year') goods_for = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='goods_for', timeAxis='year') gdp_for_drawing = genLPDrawing([tuple(end_for), tuple(asset_for), tuple(goods_for)], ['最终消费支出贡献率', '资本形成总额贡献率', '货物和服务净出口贡献率'], timeAxis='year') renderPDF.draw(drawing=gdp_for_drawing, canvas=c, x=10, y=letter[1] * 0.6) for_rate = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='for_rate', timeAxis='year') asset_rate = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='asset_rate', timeAxis='year') goods_rate = ExtractPointFromDf_DateX(df_origin=gdp_for, date_col='year', y_col='goods_rate', timeAxis='year') gdp_for_drawing = genLPDrawing([tuple(for_rate), tuple(asset_rate), tuple(goods_rate)], ['最终消费支出拉动(百分点)', '资本形成总额拉动(百分点)', '货物和服务净出口拉动(百分点)'], timeAxis='year') renderPDF.draw(drawing=gdp_for_drawing, canvas=c, x=10, y=letter[1] * 0.2) c.showPage() return c
def addGDPPullPage(canvas_para): """ 函数功能:展示三个产业对GDP的拉动情况 :param canvas_para: :return: """ c = canvas_para gdp_pull = ts.get_gdp_pull() gdp_yoy = ExtractPointFromDf_DateX(df_origin=gdp_pull, date_col='year', y_col='gdp_yoy', timeAxis='year') pi = ExtractPointFromDf_DateX(df_origin=gdp_pull, date_col='year', y_col='pi', timeAxis='year') si = ExtractPointFromDf_DateX(df_origin=gdp_pull, date_col='year', y_col='si', timeAxis='year') industry = ExtractPointFromDf_DateX(df_origin=gdp_pull, date_col='year', y_col='industry', timeAxis='year') ti = ExtractPointFromDf_DateX(df_origin=gdp_pull, date_col='year', y_col='ti', timeAxis='year') gdp_pull_drawing = genLPDrawing([tuple(gdp_yoy),tuple(pi),tuple(si),tuple(industry),tuple(ti)], data_note=['GDP同比增长率','第一产业拉动率','第二产业拉动率','工业拉动率','第三产业拉动率'], timeAxis='year') renderPDF.draw(drawing=gdp_pull_drawing, canvas=c, x=10, y=letter[1] * 0.6) c.showPage() return c
def create_header(self): headerCanvas = Drawing() headerRect = Rect(0, 0, width=self.width, height=50) headerRect.fillColor = HexColor("#607D8B") headerRect.strokeColor = HexColor("#607D8B") headerCanvas.add(headerRect) renderPDF.draw(headerCanvas, self.c, 0, self.height - 50) _header_styles = ParagraphStyle( "Header", parent=self.styles["Heading1"], textColor=white, fontName='Helvetica' ) p = Paragraph("Kit Trading Fund Report", style = _header_styles) p.wrapOn(self.c, self.width, self.height - 50) p.drawOn(self.c, *self.coord(75, 10, mm)) _sub_header_styles = ParagraphStyle( "SubHeader", parent=self.styles["Heading4"], textColor=white, fontName='Helvetica' ) p = Paragraph("Monthly Report: January 2016", style = _sub_header_styles) p.wrapOn(self.c, self.width, self.height - 50) p.drawOn(self.c, *self.coord(85, 16, mm))
def print_barcode_page(request, page_id): bcp = get_object_or_404(BarcodePage, id=page_id) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % slugify(bcp.titre) # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) width, height = A4 p.drawCentredString(width/2, height-50, bcp.titre) produits = bcp.produits.all() for idx, prod in enumerate(produits): row = idx%7 col = idx//7 h = 110 w = 180 v_offset = height-80 h_offset = 60 img_offset = 80 text_offset = 10 d = createBarcodeDrawing("EAN13",value=str(prod.ean)) p.drawString(h_offset+text_offset+col*w, v_offset-row*h, prod.nom) renderPDF.draw(d, p, h_offset+col*w, v_offset-img_offset-row*h) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
def render_diploma(request, response, diploma): design = diploma.design c = canvas.Canvas(response) marginLeft = 2 * cm marginTop = 2 * cm marginBottom = 2.5 * cm cTop = 29.7 * cm - marginTop cLeft = marginLeft cMiddle = 21 * cm / 2 logoHeight = 1.4 * cm pictureHeight = 2.5 * cm text_value_map = { '$grade': str(diploma.grade), } if design.logo: c.drawImage(design.logo.path, cLeft, cTop - logoHeight, height=logoHeight, preserveAspectRatio=True, anchor="nw") c.setFont("Helvetica-Bold", 30) c.setFillColorRGB(0, 0.25, 0.5) c.drawCentredString(10.5 * cm, cTop - 5 * cm, diploma.name) c.setFont("Helvetica", 14) c.setFillColorRGB(0, 0, 0) for i,line in enumerate(text_lines(design.title, text_value_map)): c.drawCentredString(cMiddle, cTop - 7 * cm - (i * 0.8 * cm), line) c.setFont("Helvetica", 10) c.setFillColorRGB(0, 0, 0) for i,line in enumerate(text_lines(design.body, text_value_map)): c.drawString(cLeft, cTop - 10 * cm - (i * 0.6 * cm), line) c.setFont("Helvetica", 12) c.setFillColorRGB(0, 0, 0) c.drawString(cLeft, cTop - 21 * cm, design.date) c.drawString(cLeft, cTop - 23.5 * cm, design.signature_name) c.drawString(cLeft, cTop - 24 * cm, design.signature_title) c.setFont("Helvetica", 7) c.setFillColorRGB(0, 0, 0) for i,line in enumerate(text_lines(design.small_print, text_value_map)): c.drawString(cLeft, marginBottom - (i * 0.3 * cm), line) qr_code = qr.QrCodeWidget(request.build_absolute_uri(diploma.get_absolute_url())) bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing(1200, 1200, transform=[60./width,0,0,60./height,0,0]) d.add(qr_code) renderPDF.draw(d, c, 16.7 * cm, cTop - 24.3 * cm) c.showPage() #c.setAuthor("A+") c.setTitle("Course Diploma") #c.setSubject("") c.save()
def draw_to_canvas(O, canvas): if (reportlab is None): return from reportlab.graphics.shapes import Drawing from reportlab.graphics import renderPDF drawing = Drawing(*O.page_size) drawing.add(O.top_group) renderPDF.draw(drawing=drawing, canvas=canvas, x=0, y=0)
def generate_pdf(device_data, output_filename): print('Generating PDF') ts = datetime.datetime.now().timestamp() qr_gen = generate_qr(label.ingest_api_url, device_data.imsi) # generate qrcode c = canvas.Canvas(output_filename, pagesize=label.size) renderPDF.draw(qr_gen, c, 165, -2) # render qr encoded join url icon = svg2rlg(label.safecility_icon) scaling_factor = 0.16 icon.width = icon.minWidth() * scaling_factor # scale icon to appropriate size icon.height = icon.height * scaling_factor icon.scale(scaling_factor, scaling_factor) renderPDF.draw(icon, c, 64, 22.5) # render safecility logo # Draw info to canvas c.setStrokeColorRGB(0, 0, 0) c.setFillColorRGB(0, 0, 0) c.setFont("Helvetica", 18) c.drawString(1 * mm, 24 * mm, str("Safecility™")) c.setFont("Helvetica", 6) c.drawString(1 * mm, 22 * mm, (str("www.safecility.com"))) c.drawString(1 * mm, 16.5 * mm, (str("IMSI: ") + str(device_data.imsi))) c.drawString(1 * mm, 14.5 * mm, (str("IMEI: ") + str(device_data.imei))) c.drawString(1 * mm, 12.5 * mm, (str("UID: ") + str(device_data.stm_uid))) c.drawString(1 * mm, 10.5 * mm, (str("DFW: ") + str(device_data.dev_fwv))) c.drawString(1 * mm, 8.5 * mm, (str("MFW: ") + str(device_data.modem_fwv))) c.drawString(1 * mm, 6.5 * mm, (str("DT: ") + str(ts))) c.drawString(1 * mm, 0 * mm, (str(label.ingest_api_url) + str(device_data.imsi))) # Render page & save PDF c.showPage() c.save() return c
def write_qr_code(delegate, layout): qr_code = qr.QrCodeWidget( "{} <{}>".format(delegate.name, delegate.email), barLevel="H" ) bounds = qr_code.getBounds() qr_width = bounds[2] - bounds[0] qr_height = bounds[3] - bounds[1] qr_size = 200.0 d = Drawing( qr_size, qr_size, transform=[qr_size / qr_width, 0, 0, qr_size / qr_height, 0, 0], ) d.add(qr_code) renderPDF.draw( d, layout.canvas, (layout.section_width - qr_size) / 2.0, (layout.section_height - qr_size) / 2.0, ) logo_width = 60 logo_height = 60 layout.canvas.drawImage( os.path.join(here, "img", "logo_in_qrcode.png"), (layout.section_width - logo_width) / 2.0, (layout.section_height - logo_height) / 2.0, width=logo_width, height=logo_height, mask="auto", )
def addQuarterGDPPage(canvas_para): """ 函数功能:增加季度GDP页 :param canvas_para: :return: """ c = canvas_para gdp_quarter = ts.get_gdp_quarter() gdp_yoy = ExtractPointFromDf_DateX(df_origin=gdp_quarter, date_col='quarter', y_col='gdp_yoy', timeAxis='quarter') pi_yoy = ExtractPointFromDf_DateX(df_origin=gdp_quarter, date_col='quarter', y_col='pi_yoy', timeAxis='quarter') si_yoy = ExtractPointFromDf_DateX(df_origin=gdp_quarter, date_col='quarter', y_col='si_yoy', timeAxis='quarter') ti_yoy = ExtractPointFromDf_DateX(df_origin=gdp_quarter, date_col='quarter', y_col='ti_yoy', timeAxis='quarter') gdp_pull_drawing = genLPDrawing([tuple(gdp_yoy),tuple(pi_yoy),tuple(si_yoy),tuple(ti_yoy)], data_note=['GDP同比增长率','第一产业增长率','第二产业增长率','第三产业增长率'], timeAxis='quarter') renderPDF.draw(drawing=gdp_pull_drawing, canvas=c, x=10, y=letter[1] * 0.6) c.showPage() return c
def later_pages(canvas, document): canvas.saveState() #вывести внизу QR-code (ФИО, (номера направлений)) qr_code = qr.QrCodeWidget(qr_value) qr_code.barWidth = 70 qr_code.barHeight = 70 qr_code.qrVersion = 1 bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(qr_code) renderPDF.draw(d, canvas, 90 * mm, 7) #вывести атрибуты для подписей canvas.setFont('PTAstraSerifReg', 10) canvas.drawString(40 * mm, 10 * mm, '____________________________') canvas.drawString(115 * mm, 10 * mm, '/{}/____________________________'.format(npf)) canvas.setFont('Symbola', 18) canvas.drawString(195 * mm, 10 * mm, '\u2713') canvas.setFont('PTAstraSerifReg', 8) canvas.drawString(50 * mm, 7 * mm, '(подпись сотрудника)') canvas.drawString(160 * mm, 7 * mm, '(подпись плательщика)') canvas.rotate(90) canvas.setFillColor(HexColor(0x4f4b4b)) canvas.setFont('PTAstraSerifReg', 5.2) canvas.drawString(10 * mm, -12 * mm, '{}'.format(6 * left_size_str)) canvas.restoreState()
def print_barcode_page(request, page_id): bcp = get_object_or_404(BarcodePage, id=page_id) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="%s.pdf"' % slugify( bcp.titre) # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) width, height = A4 p.drawCentredString(width / 2, height - 50, bcp.titre) produits = bcp.produits.all() for idx, prod in enumerate(produits): row = idx % 7 col = idx // 7 h = 110 w = 180 v_offset = height - 80 h_offset = 60 img_offset = 80 text_offset = 10 d = createBarcodeDrawing("EAN13", value=str(prod.ean)) p.drawString(h_offset + text_offset + col * w, v_offset - row * h, prod.nom) renderPDF.draw(d, p, h_offset + col * w, v_offset - img_offset - row * h) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
def make_pdf(data): page_width, page_height = A4 page_margin = 10.0 qr_width, qr_height = 60.0, 60.0 qr_margin = 5.0 # this is a desired margin, not the actual one num_rows = int(math.floor((page_height - 2 * page_margin) / (qr_height + qr_margin))) num_cols = int(math.floor((page_width - 2 * page_margin) / (qr_width + qr_margin))) qr_vertical_margin = ((page_height - 2 * page_margin) - num_rows * qr_height) / num_rows qr_horizontal_margin = ((page_width - 2 * page_margin) - num_cols * qr_width) / num_cols qr = QrCodeWidget(data) output = cStringIO.StringIO() p = canvas.Canvas(output, pagesize=A4) b = qr.getBounds() w, h = b[2]-b[0], b[3]-b[1] d = Drawing(qr_width, qr_height, transform=[qr_width / w, 0, 0, qr_height / h, 0, 0]) d.add(qr) for i in xrange(num_cols): x = page_margin + i * (qr_horizontal_margin + qr_width) for j in xrange(num_rows): y = page_margin + j * (qr_vertical_margin + qr_height) renderPDF.draw(d, p, x, y) p.showPage() p.save() pdf_output = output.getvalue() output.close() return pdf_output
def _DrawTop(self, x1, y1, x2, text): from reportlab.graphics import renderPDF R,G,B = VeriwaveGreen self.canvas.setFillColorRGB(R,G,B) self.canvas.roundRect(x1, y1 - 4*self._UnitHieght, x2, 4*self._UnitHieght, self._UnitHieght, stroke=0, fill=1) self.canvas.setFillColorRGB(0,0,0) _MaxStrLen = x2 - 4.0*self._UnitHieght textString = text if self._stringWidth(str(textString), "Helvetica",9) > _MaxStrLen: while self._stringWidth(str(textString) + "...", "Helvetica",9) > _MaxStrLen: textString = textString[:-1] textString = textString + "..." self.canvas.setFont("Helvetica",9) self.canvas.drawString(x1 + self._UnitHieght , y1 - 2*self._UnitHieght, textString) # Add Port Icon if self.CardMap.has_key(text): (textStr, icon) = self.CardMap[text] self.canvas.setFont("Helvetica", 5) self.canvas.drawCentredString(x1 + x2 - 1.4*self._UnitHieght, y1 - 2.65*self._UnitHieght, textStr) d = Drawing(self._UnitHieght, self._UnitHieght) d.add(icon) renderPDF.draw(d, self.canvas, x1 + x2 - 2.2*self._UnitHieght, y1 - 1.9*self._UnitHieght, showBoundary=False) return self._UnitHieght*3
def hello(c, link): c.translate(ORIGIN_X, ORIGIN_Y) # Draw paragraph stylesheet = getSampleStyleSheet() style = stylesheet['BodyText'] style.fontName = 'LeagueGothic' style.fontSize = 42 style.leading = 44 p = Paragraph('<b>print</b><br/>your<br/><b>badge</b><br/>here', style) qr_left = 30*mm p_w, p_h = p.wrap(qr_left, HEIGHT) p.drawOn(c, 0, 0) # Add QR Code qr_code = qr.QrCodeWidget(link) qr_bounds = qr_code.getBounds() qr_width = qr_bounds[2] - qr_bounds[0] qr_height = qr_bounds[3] - qr_bounds[1] d = Drawing(HEIGHT, HEIGHT, transform=[HEIGHT/qr_width,0,0,HEIGHT/qr_height,0,0]) d.add(qr_code) renderPDF.draw(d, c, qr_left, 0) # Draw thin line between text and QR code c.line(qr_left, 0, qr_left, HEIGHT) c.line(qr_left + HEIGHT, 0, qr_left+HEIGHT, HEIGHT) img_left = qr_left + HEIGHT # Draw images c.drawImage('images/ipv6.jpg', img_left, 0, 20*mm, 1/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c') c.drawImage('images/ffrhein_logo_claim_line_rot.png', img_left, 1/3*HEIGHT, 20*mm, 2/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
def persona(request,id): if 'pdf' in request.GET: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="persona_%s.pdf"'%id p=canvas.Canvas(response) drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4),(14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing,p,100,480) p.showPage() p.save() return response else: return HttpResponse("la informacion de la persona %s" %id)
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def generate(self, output_path): if output_path == None: print("no output path specified") return canvas = Canvas(output_path, pagesize=A4) while self.sheets_needed >= 1: canvas.setFont("Helvetica", 7) for i in range(self.down): for j in range(self.across): if len(self.csv_data) < 1: break data = self.csv_data.pop(0) adjust_x = j * self.horizontal_pitch adjust_y = i * -self.vertical_pitch # border x = self.label_x_start + adjust_x y = self.label_y_start + adjust_y #canvas.rect(x, y, self.label_width, self.label_height, stroke=1, fill=0) renderPDF.draw(self.createBarcode(data), canvas, adjust_x, adjust_y) self.sheets_needed -= 1 canvas.showPage() canvas.save() print(output_path + " saved")
def test_ean13ext5(): tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") # generate a canvas (A4 in this case, size doesn"t really matter) canvas1 = canvas.Canvas(tmpfile, (2.4 * inch, 2 * inch)) canvas1.saveState() # create a barcode object # (is not displayed yet) # barHeight encodes how high the bars will be # barWidth encodes how wide the "narrowest" barcode unit is ean13ext5 = "978158322870851234" barcode1 = barcode.createBarcodeDrawing( "EAN13EXT5", value=str(ean13ext5), validate=True, width=2.4 * inch, height=1.4 * inch, humanReadable=True, fontName="Helvetica", ) renderPDF.draw(barcode1, canvas1, 0, 0) canvas1.restoreState() canvas1.showPage() canvas1.save() tmpfile.close() # print_command_string = string.Template("lpr -P $printer -# $num_copies -o media=Custom.175x120 $filename") # pcs_sub = print_command_string.substitute({'filename':tmpfile.name, 'printer': configuration.get('label_printer_name'), 'num_copies':1}) # result=subprocess.call( ' '.join(pcs_sub.split()), shell=True) tmpfile.unlink(tmpfile.name)
def addReserveBaseRatePage(canvas_para): """ 函数功能:在pdf中增加准备金基率 :param canvas_para: :return: """ c = canvas_para c.setFont("song", 10) c.drawString(10, letter[1] - 20, '存款准备金基率') c.setLineWidth(3) c.line(10, letter[1] - 24, letter[0] - 10, letter[1] - 24) # 画银行准备金基率 df_rbr = ts.get_rrr().replace('--', nan) # df_rbr['date'] = df_rbr.apply(lambda x: stdMonthDate2ISO(x['month']), axis=1) # 提取相关数据 pot_before = ExtractPointFromDf_DateX(df_rbr, 'date', 'before') pot_now = ExtractPointFromDf_DateX(df_rbr, 'date', 'now') pot_changed = ExtractPointFromDf_DateX(df_rbr, 'date', 'changed') data_rbr = [tuple(pot_now)] data_rbr_note = ['准备金基率'] money_drawing = genLPDrawing(data=data_rbr, data_note=data_rbr_note, height=letter[1] * 0.2) renderPDF.draw(drawing=money_drawing, canvas=c, x=10, y=letter[1] * 0.7) c.showPage() return c
def buat_kotak(c, nomor, height, baris, kolom, string): awal = 35 + (130 * (kolom - 1)) + (5 * (kolom - 1)) panjang = awal + 130 brs = height - (60 + (115 * (baris - 1))) brs2 = height - (165 + (115 * (baris - 1))) c.line(awal, brs, panjang, brs) c.line(awal, brs, awal, brs2) c.line(awal, brs2, panjang, brs2) c.line(panjang, brs2, panjang, brs) qrw = QrCodeWidget(string) b = qrw.getBounds() w = b[2] - b[0] h = b[3] - b[1] d = Drawing(100, 100, transform=[100. / w, 0, 0, 100. / h, 0, 0]) d.add(qrw) renderPDF.draw(d, c, awal + 15, brs - 90) c.setFont('Helvetica', 12) c.drawString(awal + 6, brs - 92, string) c.setFont('Helvetica', 6) c.drawString(awal + 2, brs2 + 2, str(nomor))
def __add_graph(self): drawing = Drawing(200, 100) data = list() labels = list() self.c.drawString(370, 730, 'Distribucion en pesos'.encode('utf-8')) for acc in self.accounts: balance = acc.balance if acc.currency == 'USD': balance = balance * self.dolar data.append(balance) labels.append(acc.name) pie = Pie() pie.x = 280 pie.y = 630 pie.height = 100 pie.width = 100 pie.data = data pie.labels = labels pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 legend = Legend() legend.x = 400 legend.y = 680 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'w' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = black legend.deltax = 75 legend.deltay = 10 legend.autoXPadding = 5 legend.yGap = 0 legend.dxTextSpace = 5 legend.alignment = 'right' legend.dividerLines = 1|2|4 legend.dividerOffsY = 4.5 legend.subCols.rpad = 30 n = len(pie.data) self.__setItems(n,pie.slices, 'fillColor',self.pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)] drawing.add(pie) drawing.add(legend) x, y = 0, 0 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def render_to_painter(self, canvas, vector): # Render template layer if self.template: background = svg2rlg(self.template) background.scale(PDFWIDTH / background.width, PDFWIDTH / background.width) renderPDF.draw(background, canvas, 0, 0) # Bitmaps are rendered into the PDF as XObjects, which are # easy to pick out for layers. Vectors will render # everything inline, and so we need to add a 'magic point' # to mark the end of the template layer. if False and vector: #TODO pen = GenericPen(color=Qt.transparent, vector=vector) painter.setPen(pen) painter.drawPoint(800, 85) # The annotation coordinate system is upside down compared to the PDF # coordinate system, so offset the bottom to the top and then flip # vertically along the old bottom / new top to place the annotations # correctly. canvas.translate(0, PDFHEIGHT) canvas.scale(PTPERPX, -PTPERPX) # Render user layers for layer in self.layers: # Bitmaps are rendered into the PDF as XObjects, which are # easy to pick out for layers. Vectors will render # everything inline, and so we need to add a 'magic point' # to mark the beginning of layers. if False and vector: #TODO pen = GenericPen(color=Qt.transparent, vector=vector) painter.setPen(pen) painter.drawPoint(420, 69) layer.render_to_painter(canvas, vector) canvas.showPage()
def draw_qr_global_id(canvas, survey): if survey.global_id is None: raise AssertionError # Only allow ascii value = survey.global_id.encode('ascii') y = survey.defs.paper_height - defs.corner_mark_bottom x = (survey.defs.paper_width - defs.corner_mark_right + defs.corner_mark_left) / 2 qr_code = qr.QrCodeWidget(value, barLevel='H') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] # Squeeze into the space between corner mark and content size = defs.bottom_page_margin - defs.corner_mark_bottom code_y = y code_x = x - size / 2.0 d = Drawing(size*mm, size*mm, transform=[float(size*mm)/width,0,0,-float(size*mm)/height,0,0]) d.add(qr_code) renderPDF.draw(d, canvas, code_x*mm, code_y*mm)
def create_sticker_for_box(sticker_name="sticker.pdf", box_number=1): newY = 0 c = canvas.Canvas(sticker_name) c.setFont("Helvetica", 9) startX = 100 startY = 780 draw_box_number(c, startX, startY + 30, box_number) step = 12 draw_line(c, startX, startY + step) with open('store_order.csv') as packing_information_csv: packing_information = csv.reader(packing_information_csv, delimiter=',') next(packing_information) # skip header row for line in packing_information: if len(line) == 0: continue # probably just an empty line box_number_from_csv = line[4] if box_number != int(box_number_from_csv): continue if line[3] == '0': continue # probably did not have the item sticker_items = OrderedDict({"sku": f'SKU: {line[0]} –– Title: {line[1]} –– quantity: {line[3]}', "fill": "---------------------------------------------------------------------------", }, ) newY = draw_sticker_items(c, sticker_items, startX, startY, step) startY = newY d = Drawing(50, 10) renderPDF.draw(d, c, startX, newY - 4 * step) # Save to file c.save()
def draw_qr_sdaps_info(canvas, survey, page): # The page number is one based here already # The survey_id is a 32bit number, which means we need # 10 decimal digits to encode it, then we need to encode the # the page with at least 3 digits(just in case someone is insane enough # to have a questionnaire with more than 99 pages. # So use 10+4 digits value = "%010d%04d" % (survey.survey_id, page) y = survey.defs.paper_height - defs.corner_mark_bottom x = survey.defs.paper_width - defs.corner_mark_right qr_code = qr.QrCodeWidget(value, barLevel='H') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] # Squeeze into the space between corner mark and content size = defs.bottom_page_margin - defs.corner_mark_bottom code_y = y code_x = x - size d = Drawing(size*mm, size*mm, transform=[float(size*mm)/width,0,0,-float(size*mm)/height,0,0]) d.add(qr_code) renderPDF.draw(d, canvas, code_x*mm, code_y*mm)
def drawLayerProfile(self, x, y, depth, color, pattern, width=15): """ """ ulx = settings['page']['left']*mm + x*mm uly = self.height - (settings['page']['top']*mm + y*mm) # save current state of canvas self.c.saveState() # set clipping region self.clipBox(ulx, uly, width*mm, -depth*mm) self.c.setLineWidth( self.settings['boxStyles']['thin'][0]) if color: self.c.setFillColorRGB(color[0]/255, color[1]/255, color[2]/255) self.c.rect(ulx, uly, width*mm, -depth*mm, fill=1) if pattern and path.isfile(pattern): # Opens the pattern bg = svg2rlg(pattern) # The width and height of the pattern bg_w = bg.width bg_h = bg.height # The width and height of the layer w = width*mm h = depth*mm # Iterate through a grid, to place the background tile for i in range(0, int(w/bg_w)+1): for j in range(0, int(h/bg_h)+2): renderPDF.draw(bg, self.c, ulx + (i*bg_w), uly - (j*bg_h)) # restore original state self.c.restoreState()
def Identificacao(myCanvas, dados, pagina): margin = 2 * cm marginleft = margin margintop = height - 1.1 * margin myCanvas.setStrokeColorRGB(0, 0, 0) myCanvas.setFillColorRGB(0, 0, 0) codigo = dados.codigo + '-' + format(pagina, '02d') # Dados do aluno e da prova myCanvas.setFont('Helvetica-Bold', 12) myCanvas.drawString(marginleft + 1.1 * cm, 25.4 * cm, dados.nome) myCanvas.drawString(marginleft + 0.7 * cm, 24.8 * cm, dados.ra) myCanvas.drawString(marginleft + 4.2 * cm, 24.8 * cm, dados.nomePolo) myCanvas.drawString(marginleft + 12 * cm, 24.8 * cm, dados.data) myCanvas.drawString(marginleft + 1.3 * cm, 24.2 * cm, dados.curso) myCanvas.drawString(marginleft + 9.3 * cm, 24.2 * cm, dados.turma) myCanvas.drawString(marginleft + 13.7 * cm, 24.2 * cm, dados.bimestre) myCanvas.drawString(marginleft + 2 * cm, 23.6 * cm, dados.disciplina + ' - ' + dados.nomeDisciplina) myCanvas.drawString(marginleft + 1.5 * cm, 23 * cm, codigo) # Coloca QR-Code no canto superior direito qrw = QrCodeWidget(codigo) qrsize = 100.0 b = qrw.getBounds() w = b[2] - b[0] h = b[3] - b[1] d = Drawing(qrsize, qrsize, transform=[qrsize/w, 0, 0, qrsize/h, 0, 0]) d.add(qrw) renderPDF.draw(d, myCanvas, 16 * cm, margintop - h + 28) return
def createBarCodes(path, barcode_value): from reportlab.graphics.barcode import eanbc from reportlab.graphics.shapes import Drawing from reportlab.pdfgen import canvas from reportlab.graphics import renderPDF from reportlab.lib.units import cm, mm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus.para import Paragraph # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() barcode_eanbc13.barHeight = 19*mm width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(barcode_eanbc13) c = canvas.Canvas(path, pagesize=(43*mm, 25*mm)) # print width, height text = "%s.%s" % (150, '00') p = Paragraph(text, getSampleStyleSheet()["Normal"]) p.wrapOn(c, 43*mm, 5*mm) p.drawOn(c, 16*mm, 20*mm) renderPDF.draw(d, c, 3*mm, 1*mm) c.save()
def create_pdf(path): c = Canvas() forest = pd.read_csv('reports/') del forest["REGION"] del forest["AREA"] a = list(forest.iloc[0]) y = a[1:11] x = [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020] fig = plt.figure(figsize=(6, 4)) plt.plot(x, y) plt.xticks(np.arange(min(x), max(x) + 1, 1.0)) plt.ylabel('Forest in Sq. km') plt.xlabel('Years') imgdata = BytesIO() fig.savefig(imgdata, format='svg') imgdata.seek(0) # rewind the data drawing = svg2rlg(imgdata) renderPDF.draw(drawing, c, 50, 450) c.showPage() c.save() return path
def drawLetterHeadFooter(self): self.setStrokeColor(themeColor) self.setFillColor(themeColor) self.rect(0, 0, 1500, 70, fill=True) # print dir(self) compNameStyle = styleN.clone('footerCompanyName') compNameStyle.textColor = colors.white p = Paragraph( settingsFields.get(name='companyName').value, compNameStyle) p.wrapOn(self, 50 * mm, 10 * mm) p.drawOn(self, 85 * mm, 18 * mm) p1 = Paragraph( settingsFields.get(name='companyAddress').value, compNameStyle) p1.wrapOn(self, 150 * mm, 10 * mm) p1.drawOn(self, 55 * mm, 10 * mm) p2 = Paragraph( settingsFields.get(name='contactDetails').value, compNameStyle) p2.wrapOn(self, 200 * mm, 10 * mm) p2.drawOn(self, 40 * mm, 4 * mm) from svglib.svglib import svg2rlg drawing = svg2rlg( os.path.join(globalSettings.BASE_DIR, 'static_shared', 'images', 'cioc_icon.svg')) sx = sy = 0.5 drawing.width, drawing.height = drawing.minWidth( ) * sx, drawing.height * sy drawing.scale(sx, sy) #if you want to see the box around the image # drawing._showBoundary = True renderPDF.draw(drawing, self, 10 * mm, self._pagesize[1] - 20 * mm)
def create_diagram(cnarr, segarr, threshold, min_probes, outfname, title=None): """Create the diagram.""" if cnarr and segarr: do_both = True # Draw segments on left, probes on right. cnarr_is_seg = False # Are probes actually the segmented values? else: if cnarr: cnarr_is_seg = False elif segarr: cnarr = segarr cnarr_is_seg = True else: raise ValueError("Must provide argument cnarr or segarr, or both. ") do_both = False gene_labels = _get_gene_labels(cnarr, segarr, cnarr_is_seg, threshold, min_probes) # NB: If multiple segments cover the same gene (gene contains breakpoints), # all those segments are marked as "hits". We'll uniquify them. # TODO - use different logic to only label the gene's signficant segment(s) seen_genes = set() # Consolidate genes & coverage values as chromosome features features = collections.defaultdict(list) strand = 1 if do_both else None # Draw on the chr. right half or full width chrom_sizes = plots.chromosome_sizes(cnarr) if not cnarr_is_seg: cnarr = cnarr.squash_genes() for row in cnarr: if row.start - 1 >= 0 and row.end <= chrom_sizes[row.chromosome]: # Sanity check if row.gene in gene_labels and row.gene not in seen_genes: seen_genes.add(row.gene) feat_name = row.gene if "," in feat_name: # TODO - line-wrap multi-gene labels (reportlab won't do \n) feat_name = feat_name.replace(",", ", ") else: feat_name = None features[row.chromosome].append( (row.start - 1, row.end, strand, feat_name, colors.Color(*plots.cvg2rgb(row.log2, not cnarr_is_seg)))) if do_both: # Draw segments in the left half of each chromosome (strand -1) for chrom, segrows in segarr.by_chromosome(): for srow in segrows: if srow.start - 1 >= 0 and srow.end <= chrom_sizes[chrom]: # Sanity check features[chrom].append( (srow.start - 1, srow.end, -1, None, colors.Color(*plots.cvg2rgb(srow.log2, False)))) # Generate the diagram PDF if not outfname: outfname = cnarr.sample_id + '-diagram.pdf' drawing = build_chrom_diagram(features, chrom_sizes, cnarr.sample_id, title) cvs = canvas.Canvas(outfname, pagesize=PAGE_SIZE) renderPDF.draw(drawing, cvs, 0, 0) cvs.showPage() cvs.save() return outfname
def get_location_qrs(request, start_pk): """Generate the PDF for the small sign that identifies a location.""" start_pk = int(start_pk) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = 'attachment; filename="locs_from_%04d.pdf"' % start_pk # Produce PDF using ReportLab: p = canvas.Canvas(response) pageW = defaultPageSize[0] pageH = defaultPageSize[1] marginX = 1.1 * inch marginY = 1.1 * inch spacingX = 0 * inch spacingY = 0 * inch tagw = 1.0 * inch tagh = 1.3 * inch xCount = 7 yCount = 8 for y in range(yCount): for x in range(xCount): centerX = marginX + x * (tagw + spacingX) centerY = pageH - (marginY + y * (tagh + spacingY)) # p.rect(centerX-tagw/2, centerY-tagh/2, tagw, tagh) l = centerX - tagw / 2 r = l + tagw b = centerY - tagh / 2 t = b + tagh m = 0.05 * inch p.lines([(l, t - m, l, t), (l, t, l + m, t)]) p.lines([(l, b + m, l, b), (l, b, l + m, b)]) p.lines([(r - m, t, r, t), (r, t, r, t - m)]) p.lines([(r - m, b, r, b), (r, b, r, b + m)]) loc_pk = start_pk + xCount * y + x Location.objects.get_or_create(pk=loc_pk) # QR Code: qr = QrCodeWidget('{"loc":%d}' % loc_pk) bounds = qr.getBounds() qrW = bounds[2] - bounds[0] qrH = bounds[3] - bounds[1] xx = 1.1 * tagw yy = 1.1 * tagw drawing = Drawing(xx, yy, transform=[xx / qrW, 0, 0, yy / qrH, 0, 0]) drawing.add(qr) renderPDF.draw(drawing, p, centerX - xx / 2, 0.1 * inch + centerY - yy / 2) p.setFont("Helvetica", 16) p.drawCentredString(centerX, centerY - 0.55 * inch, "L%04d" % loc_pk) p.showPage() p.save() return response
def drawOn(self, canvas, x, y, _sW=0): #There is basic support for drawing Barchart, Linechart for #the same dataset. This could be extended for more chart types #There is also basic support for including Legends in the chart #A list of Legends can be optionally specified. Legend config is #[String, Type,Color]. The last two are optional. #The charts are drawn in the order as specified in the config. #So, if the config is ['Line', 'Bar'], Linechart is drawn first #and then Barchart. Thus some parts of Line gets overdrawn by Bars. #To display both line and bar cleanly, it is suggested that the #config be ['Bar', 'Line']. There is also a minimum support to #split a chart. Separate charts are drawn in the same area for #each set of [y_vals]. self.canvas = canvas self.canvas.saveState() self.drawing = Drawing(self.width, self.height) self.origHeight = origHeight = self.height if len(self.legendList) > 1: #Kludge: We encroach the space needed for legends by bringing down the #y value by 28 below (y -= 28), so, the height is increased by 28 self.origHeight += 28 if (self.splitgraph == True and len(self.y_vals) > 1 and len(self.y_vals) * len(self.x_vals) > 30): origXval = x origYval = y origYvals = copy.deepcopy(self.y_vals) numSets = len(self.y_vals) origLegends = self.legendList[:] heightincr = origHeight/numSets self.numSplits = 0 self.betweenSplitsF = True for i in range(numSets): self.y_vals = [] self.y_vals.append(origYvals[i]) self.height = heightincr y = y + (i * heightincr) self.legendList = [] if len(origLegends) > i: self.legendList.append(origLegends[i]) #Kludge: Bring the graph down by 28 points, as we add 28 points #when we have legends y -= 28 self.generateGraphs(x, y) self.numSplits += 1 self.betweenSplitsF = False self.y_vals = copy.deepcopy(origYvals) self.legendList = origLegends[:] self.height = self.origHeight x = origXval y = origYval else: if len(self.legendList) > 0: #Kludge: Bring the graph down by 28 points, as we add 28 points #when we have legends y -= 28 self.generateGraphs(x, y) renderPDF.draw(self.drawing, self.canvas, x, y) self.canvas.restoreState()
def createBarCodes(): """ Create barcode examples and embed in a PDF """ c = canvas.Canvas("STOKsayim.pdf", pagesize=A4) c.setFont("Helvetica", 12) # code93 also has an Extended and MultiWidth version x = 1 * mm y = 270* mm x1 = 6.4 * mm c.drawImage("./images/bishop.png",x+5,y-15) b="NEN2016 " c.setFont("Helvetica", 30) c.drawString(x+90,y-15,str(b)) c.setFont("Helvetica", 21) c.drawString(x+190,y+35,"SAYIM 31/12/2015") c.setFont("Helvetica", 12) y = y - 20 * mm for code in sonuc: b=code[2] print code[0],code[1],code[2] barcode93 = code93.Extended93(code[0]) barcode94 = code128.Code128('02407m3,47') barcode93.drawOn(c, x, y+10) barcode94.drawOn(c, x+200, y+10) c.drawString(x+90,y+15,str(code[0])+" "+str( code[2])+" "+ str(code[1])) c.rect(x,y+3,200*mm,10*mm, fill=0) y = y - 10 * mm if y<20 : c.showPage() y = 280* mm # draw a QR code qr_code = qr.QrCodeWidget('http://78.188.173.248:8080/masa.php') 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, 50) c.save()
def create_card_download(request): filename = "member_card_%s.pdf" % request.user.username # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename member = request.user.member b64 = member.generate_member_card_str() # Produce PDF using ReportLab: p = canvas.Canvas(response, pagesize=letter) pageW, _ = letter # Business card size is 2" x 3" # Credit card size is 2.2125" x 3.370" card_width = 2.125*inch card_height = 3.370*inch card_corner_r = 3.0*mm refX = pageW/2.0 refY = 7.25*inch # Some text to place near the top of the page. p.setFont("Helvetica", 16) p.drawCentredString(refX, refY+3.00*inch, 'This is your new Xerocraft membership card.') p.drawCentredString(refX, refY+2.75*inch, 'Always bring it with you when you visit Xerocraft.') p.drawCentredString(refX, refY+2.50*inch, 'The rectangle is credit card sized, if you would like to cut it out.') p.drawCentredString(refX, refY+2.25*inch, 'If you have any older cards, they have been deactivated.') # Changing refY allows the following to be moved up/down as a group, w.r.t. the text above. refY -= 0.3*inch # Most of the wallet size card: p.roundRect(refX-card_width/2, refY-1.34*inch, card_width, card_height, card_corner_r) p.setFont("Helvetica", 21) p.drawCentredString(refX, refY-0.3*inch, 'XEROCRAFT') p.setFontSize(16) p.drawCentredString(refX, refY-0.65*inch, member.first_name) p.drawCentredString(refX, refY-0.85*inch, member.last_name) p.setFontSize(12) p.drawCentredString(refX, refY-1.2 *inch, date.today().isoformat()) # QR Code: qr = QrCodeWidget(b64) qrSide = 2.3*inch # REVIEW: This isn't actually 2.3 inches. What is it? bounds = qr.getBounds() qrW = bounds[2] - bounds[0] qrH = bounds[3] - bounds[1] drawing = Drawing(1000, 1000, transform=[qrSide/qrW, 0, 0, qrSide/qrH, 0, 0]) drawing.add(qr) renderPDF.draw(drawing, p, refX-qrSide/2, refY-0.19*inch) p.showPage() p.save() return response
def draw(self, canvas): from reportlab.graphics import renderPDF canvas.saveState() (atx,aty) = self.origin (width, height) = self.dimensions logo = RL_CorpLogo() logo.width, logo.height = width, height renderPDF.draw(logo.demo(),canvas,atx,aty,0) canvas.restoreState()
def create_diagram(cnarr, segarr, threshold, min_probes, outfname, male_reference): """Create the diagram.""" if cnarr and segarr: do_both = True # Draw segments on left, probes on right. cnarr_is_seg = False # Are probes actually the segmented values? else: if cnarr: cnarr_is_seg = False elif segarr: cnarr = segarr cnarr_is_seg = True else: raise ValueError("Must specify a filename as an argument or with " "the '-s' option, or both. You did neither.") do_both = False # Label genes where copy ratio value exceeds threshold cnarr = cnarr.shift_xx(male_reference) if cnarr_is_seg: gainloss = [] elif segarr: segarr = segarr.shift_xx(male_reference) gainloss = reports.gainloss_by_segment(cnarr, segarr, threshold) else: gainloss = reports.gainloss_by_gene(cnarr, threshold) gene_labels = [gl_row[0] for gl_row in gainloss if gl_row[5] >= min_probes] # Consolidate genes & coverage values as chromosome features features = collections.defaultdict(list) strand = 1 if do_both else None # Draw on the chr. right half or full width chrom_sizes = plots.chromosome_sizes(cnarr) if not cnarr_is_seg: cnarr = cnarr.squash_genes() for row in cnarr: if row.start - 1 >= 0 and row.end <= chrom_sizes[row.chromosome]: # Sanity check feat_name = row.gene if row.gene in gene_labels else None features[row.chromosome].append( (row.start - 1, row.end, strand, feat_name, colors.Color(*plots.cvg2rgb(row.log2, not cnarr_is_seg)))) if do_both: # Draw segments in the left half of each chromosome (strand -1) for chrom, segrows in segarr.by_chromosome(): for srow in segrows: if srow.start - 1 >= 0 and srow.end <= chrom_sizes[chrom]: # Sanity check features[chrom].append( (srow.start - 1, srow.end, -1, None, colors.Color(*plots.cvg2rgb(srow.log2, False)))) # Generate the diagram PDF if not outfname: outfname = cnarr.sample_id + '-diagram.pdf' drawing = build_chrom_diagram(features, chrom_sizes, cnarr.sample_id) cvs = canvas.Canvas(outfname, pagesize=PAGE_SIZE) renderPDF.draw(drawing, cvs, 0, 0) cvs.showPage() cvs.save() return outfname
def createBarCodes(): """ Create barcode examples and embed in a PDF """ c = canvas.Canvas("STOKMUTFAK.pdf", pagesize=A4) c.setFont("Helvetica", 12) # code93 also has an Extended and MultiWidth version x = 1 * mm y = 270* mm x1 = 6.4 * mm c.drawImage("./images/bishop.png",x+5,y-15) b=sonuc[0][2] c.setFont("Helvetica", 30) c.drawString(x+90,y-15,str(b)) c.setFont("Helvetica", 21) c.drawString(x+190,y+35,"SAYIM MUTFAK 31/03/2016") c.setFont("Helvetica", 12) y = y - 20 * mm for code in sonuc: b=code[2] print code[0],code[1] barcode93 = code93.Standard93(code[0]) barcode93.drawOn(c, x, y+10) c.drawString(x+90,y+15,str(code[0]+" "+ code[1])) c.rect(x,y+3,200*mm,10*mm, fill=0) y = y - 10 * mm if y<20 : c.showPage() y = 280* mm # draw a QR code qr_code = qr.QrCodeWidget('http://nen.duckdns.org:8080/masa.php') 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, 50) c.save()
def drawOn(self, canvas, x, y, _sW=0): """ drawOn is the method of a flowable called when the pdf is printed """ self.canvas = canvas self.canvas.saveState() self.drawing = Drawing(self.width, self.height) self._drawGraphs(x, y) renderPDF.draw(self.drawing, self.canvas, x, y) self.canvas.restoreState()
def draw_qr(c, text, x0, y0, w, h): """Draws a single QR code. """ q = QrCodeWidget(text) b = q.getBounds() d = Drawing(w, h, transform=[ w / (b[2] - b[0]), 0, 0, h / (b[3] - b[1]), 0, 0 ]) d.add(q) renderPDF.draw(d, c, x0, y0)
def draw(self): # here standard and documented QrCodeWidget usage on # Flowable canva qr_code = QrCodeWidget(self.qr_value) bounds = qr_code.getBounds() qr_width = (bounds[2] - bounds[0]) qr_height = (bounds[3] - bounds[1]) w = float(self.width) d = Drawing(w, w, transform=[w/qr_width, 0, 0, w/qr_height, 0, 0]) d.add(qr_code) renderPDF.draw(d, self.canv, 0, 0)
def draw_labels(self, canv): for pos in range( 0, self.ACROSS * self.DOWN ): x, y = self.LabelPosition( pos ) #canv.rect( x, y, self.WIDTH, self.HEIGHT ) canv.drawImage(self.image_path, x, y + self.HEIGHT * 0.30, self.WIDTH , self.HEIGHT * 0.70, preserveAspectRatio=True) tx = canv.beginText( x + self.WIDTH * 0.01, y+self.HEIGHT * 0.24) tx.setFont( 'Helvetica', 8, 8 ) tx.textLines( self.text ) canv.drawText( tx ) renderPDF.draw(self.qr_draw, canv, x + self.WIDTH * 0.75, y -3 ) #+ HEIGHT ) renderPDF.draw(self.ean_draw, canv, x + 4, y) # + HEIGHT)