def newDrawing(self, zoom, d, text): w, h = int(zoom * d.width + 0.5), int(zoom * d.height + 0.5) if zoom != 1.0: from reportlab.graphics.shapes import Drawing d = Drawing(w, h, d, transform=(zoom, 0, 0, zoom, 0, 0)) dim = d.width, d.height ds = renderPM.drawToString(d, fmt='gif') ndim = d.width, d.height if ndim != dim: print('size changed dim=%r ndim=%r' % (dim, ndim)) w, h = int(d.width + 0.5), int(d.height + 0.5) ds = renderPM.drawToString(d, fmt='gif') self._image = tkinter.PhotoImage(data=base64.encodestring(ds), width=w, height=h, format='gif') if hasattr(self, '_label'): self._label.grid_forget() frame = self.interior() self._label = tkinter.Label(frame, width=w, height=h, image=self._image) self._label.grid(row=0, column=0, sticky='news') self['label_text'] = text frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) self.reposition()
def convert_svg_to_png(self, svg): return_val = None rlg = svg2rlg( BytesIO(bytes(self.convert_svg_textpath(svg), encoding="utf-8"))) if GWASMiner.theme() == "light": return_val = renderPM.drawToString(rlg, fmt="PNG") else: return_val = renderPM.drawToString(rlg, fmt="PNG", bg=0x19232D) return return_val
def get_image(value): barcode = get_barcode(value=value, width=600) data = b64encode(renderPM.drawToString(barcode, fmt='PNG')) #print '<img src="data:image/png;base64,{0}">'.format(data) #return '<img src="data:image/png;base64,{0}">'.format(data) return 'data:image/png;base64,{0}'.format(data)
def asString(self, format, verbose=None, preview=0, **kw): """Converts to an 8 bit string in given format.""" assert format in ('pdf','ps','eps','gif','png','jpg','jpeg','bmp','ppm','tiff','tif','py','pict','pct','tiffp','tiffl','tiff1'), 'Unknown file format "%s"' % format from reportlab import rl_config #verbose = verbose is not None and (verbose,) or (getattr(self,'verbose',verbose),)[0] if format == 'pdf': from reportlab.graphics import renderPDF return renderPDF.drawToString(self) elif format in ('gif','png','tif','tiff','jpg','pct','pict','bmp','ppm','tiffp','tiffl','tiff1'): from reportlab.graphics import renderPM return renderPM.drawToString(self, fmt=format,showBoundary=getattr(self,'showBorder', rl_config.showBoundary),**_extraKW(self,'_renderPM_',**kw)) elif format == 'eps': try: from rlextra.graphics import renderPS_SEP as renderPS except ImportError: from reportlab.graphics import renderPS return renderPS.drawToString(self, preview = preview, showBoundary=getattr(self,'showBorder',rl_config.showBoundary)) elif format == 'ps': from reportlab.graphics import renderPS return renderPS.drawToString(self, showBoundary=getattr(self,'showBorder',rl_config.showBoundary)) elif format == 'py': return self._renderPy()
def svgToPng(svg_code): t0 = int(round(time.time() * 1000)) tmp_path = r'C:\Users\j20687\Desktop\%d.svg' % t0 b = bytes(svg_code, encoding="utf8") with open(tmp_path, 'wb') as f: f.write(b) drawing = svg2rlg(tmp_path) png_value = renderPM.drawToString(drawing, fmt="PNG") return png_value
async def get_file_from_svg_url(self, url, exclude=[], fmt="PNG"): res = await (await self.session.get(url)).content.read() for i in exclude: res = res.replace( i, b"" ) # removes everything that needs to be excluded (eg. the uncentered A+) drawing = svg2rlg(BytesIO(res)) file = BytesIO(renderPM.drawToString(drawing, fmt=fmt)) return file
def barcode(value): "generate a barcode for the provided value" barcode = createBarcodeDrawing("Code128", value=str(value)) scale = 30 / barcode.height drawing = Drawing(barcode.width * scale, 30) drawing.scale(scale, scale) drawing.add(barcode, name='barcode') data = b64encode(renderPM.drawToString(drawing, fmt='PNG')) return mark_safe('<img src="data:image/png;base64,{}">'.format(data))
def preview_string(self, page, format="png", dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page as a string. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported. dpi: positive real The dots-per-inch to use when rendering. background_colour: Hex colour specification What color background to use. Notes ----- If you are creating this sheet for a preview only, you can pass the pages_to_draw parameter to the constructor to avoid the drawing function being called for all the labels on pages you'll never look at. If you preview a page you did not tell the sheet to draw, you will get a blank image. Raises ------ ValueError: If the page number is not valid. """ # Check the page number. if page < 1 or page > self.page_count: raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) # Shade any remaining missing labels if desired. self._shade_remaining_missing() # Rendering to an image (as opposed to a PDF) requires any background # to have an integer width and height if it is a ReportLab Image # object. Drawing objects are exempt from this. oldw, oldh = None, None if isinstance(self._bgimage, Image): oldw, oldh = self._bgimage.width, self._bgimage.height self._bgimage.width = int(oldw) + 1 self._bgimage.height = int(oldh) + 1 # Let ReportLab do the heavy lifting. s = renderPM.drawToString(self._pages[page - 1], format, dpi, background_colour) # Restore the size of the background image if we changed it. if oldw: self._bgimage.width = oldw self._bgimage.height = oldh # Done. return s
def render_to_svg(water_actions, mountain_actions, country_actions): mountains = set( tuple(json.loads(a.data)["location"]) for a in mountain_actions) with tempfile.NamedTemporaryFile(suffix=".svg") as svg_file: svg_file.write(b"<svg viewBox='0 0 3500 2000'>") water_points = set() for water in water_actions: coords = json.loads(water.data)["coords"] water_points.update( tuple(c) for c in json.loads(water.data)["contains"]) coord_strings = [] for x, y in coords: coord_strings.append(f'{x} {y}') water_color = '#42e9f5' if coord_strings: path = f'<path fill="{water_color}" stroke="black" strokeWidth="5px" d="M {coord_strings[0]} {" L ".join(coord_strings[1:])}"/>'.encode( ) svg_file.write(path) for row in range(rows): for column in range(columns): x = grid_to_board_x(column, row) y = grid_to_board_y(column, row) if (column, row) not in water_points: if (column, row) in mountains: svg_file.write( f'<path fill="black" d="M {x} {y - mountainSize} L {x + mountainSize} {y + mountainSize} L {x - mountainSize} {y + mountainSize}"/>' .encode()) else: svg_file.write( f"<circle cx='{x}' cy='{y}' r='{circleRadius}' fill='black'/>" .encode()) for country in country_actions: coords = json.loads(country.data)["cells"] color = json.loads(country.data)["color"] for x, y in coords: board_x = grid_to_board_x(x, y) board_y = grid_to_board_y(x, y) cell = f'<rect ' \ f'x="{board_x - spaceBetween / 2}" ' \ f'y="{board_y - spaceBetween / 2}" ' \ f'width="{spaceBetween}" height="{spaceBetween}" ' \ f'style="fill:{color};fill-opacity:0.35"/>'.encode() svg_file.write(cell) svg_file.write(b"</svg>") svg_file.seek(0) drawing = svg2rlg(svg_file.name) return renderPM.drawToString(drawing, fmt="jpg")
def preview_string(self, page, format='png', dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page as a string. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported. dpi: positive real The dots-per-inch to use when rendering. background_colour: Hex colour specification What color background to use. Notes ----- If you are creating this sheet for a preview only, you can pass the pages_to_draw parameter to the constructor to avoid the drawing function being called for all the labels on pages you'll never look at. If you preview a page you did not tell the sheet to draw, you will get a blank image. Raises ------ ValueError: If the page number is not valid. """ # Check the page number. if page < 1 or page > self.page_count: raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) # Shade any remaining missing labels if desired. self._shade_remaining_missing() # Rendering to an image (as opposed to a PDF) requires any background # to have an integer width and height if it is a ReportLab Image # object. Drawing objects are exempt from this. oldw, oldh = None, None if isinstance(self._bgimage, Image): oldw, oldh = self._bgimage.width, self._bgimage.height self._bgimage.width = int(oldw) + 1 self._bgimage.height = int(oldh) + 1 # Let ReportLab do the heavy lifting. s = renderPM.drawToString(self._pages[page-1], format, dpi, background_colour) # Restore the size of the background image if we changed it. if oldw: self._bgimage.width = oldw self._bgimage.height = oldh # Done. return s
def create_qrcode(value, size=50): d = Drawing(size, size) qr = QrCodeWidget(value=value, barWidth=size, barHeight=size) d.add(qr) return Image( value=renderPM.drawToString(d, fmt="png"), format='png', width=size, height=size, )
def asString(self, format, verbose=None, preview=0, **kw): """Converts to an 8 bit string in given format.""" assert format in ( "pdf", "ps", "eps", "gif", "png", "jpg", "jpeg", "bmp", "ppm", "tiff", "tif", "py", "pict", "pct", "tiffp", "tiffl", "tiff1", ), ('Unknown file format "%s"' % format) from reportlab import rl_config # verbose = verbose is not None and (verbose,) or (getattr(self,'verbose',verbose),)[0] if format == "pdf": from reportlab.graphics import renderPDF return renderPDF.drawToString(self) elif format in ("gif", "png", "tif", "tiff", "jpg", "pct", "pict", "bmp", "ppm", "tiffp", "tiffl", "tiff1"): from reportlab.graphics import renderPM return renderPM.drawToString( self, fmt=format, showBoundary=getattr(self, "showBorder", rl_config.showBoundary), **_extraKW(self, "_renderPM_", **kw) ) elif format == "eps": try: from rlextra.graphics import renderPS_SEP as renderPS except ImportError: from reportlab.graphics import renderPS return renderPS.drawToString( self, preview=preview, showBoundary=getattr(self, "showBorder", rl_config.showBoundary) ) elif format == "ps": from reportlab.graphics import renderPS return renderPS.drawToString(self, showBoundary=getattr(self, "showBorder", rl_config.showBoundary)) elif format == "py": return self._renderPy()
def get_barcode(self, value, width, barWidth = 0.05 * units.inch, fontSize = 12, humanReadable = True): # El valor por default de fontSize=60 barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize, humanReadable = humanReadable) drawing_width = width barcode_scale = drawing_width / barcode.width drawing_height = barcode.height * barcode_scale drawing = Drawing(drawing_width, drawing_height) drawing.scale(barcode_scale, barcode_scale) drawing.add(barcode, name='barcode') barcode_encode = b64encode(renderPM.drawToString(drawing, fmt = 'PNG')) barcode_str = '<img style="width:320px;height:80px;" src="data:image/png;base64,{0} : ">'.format(barcode_encode) return barcode_str
def render_png(self, width=800, height=800): # svglib expects an lxml structure internally parser = etree.XMLParser(remove_comments=True, recover=True) svg = etree.fromstring(self.get_xml().encode("utf-8"), parser=parser) # render the SVG to a PNG renderer = SvgRenderer(None) drawing = renderer.render(svg) scale_x = width / drawing.width scale_y = height / drawing.height drawing.width = width drawing.height = height drawing.scale(scale_x, scale_y) return renderPM.drawToString(drawing, fmt="PNG")
def get_gs1_128_barcode_image(self, value, width, barWidth=0.05 * units.inch, fontSize=30, humanReadable=True): barcode = createBarcodeDrawing('Code128', value=value, barWidth=barWidth, fontSize=fontSize, humanReadable=humanReadable) drawing_width = width barcode_scale = drawing_width / barcode.width drawing_height = barcode.height * barcode_scale drawing = Drawing(drawing_width, drawing_height) drawing.scale(barcode_scale, barcode_scale) drawing.add(barcode, name='barcode') data = b64encode(renderPM.drawToString(drawing, fmt='PNG')) return data
def preview_string(self, page, format='png', dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page as a string. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] format: string The image format to use for the preview. ReportLab uses the Python Imaging Library (PIL) internally, so any PIL format should be supported. dpi: positive real The dots-per-inch to use when rendering. background_colour: Hex colour specification What color background to use. Notes ----- If you are creating this sheet for a preview only, you can pass the pages_to_draw parameter to the constructor to avoid the drawing function being called for all the labels on pages you'll never look at. If you preview a page you did not tell the sheet to draw, you will get a blank image. Raises ------ ValueError: If the page number is not valid. """ # Check the page number. if page < 1 or page > self.page_count: raise ValueError("Invalid page number; should be between 1 and {0:d}.".format(self.page_count)) # Shade any remaining missing labels if desired. self._shade_remaining_missing() # Let ReportLab do the heavy lifting. return renderPM.drawToString(self._pages[page-1], format, dpi, background_colour)
def get_code128_barcode(self, value, width, barWidth=(0.05 * units.inch) / 2, fontSize=12, humanReadable=True): # El valor por default de fontSize=60 barcode = createBarcodeDrawing('Code128', value=value, barWidth=barWidth, fontSize=fontSize, humanReadable=humanReadable) drawing_width = width barcode_scale = drawing_width / barcode.width drawing_height = barcode.height * barcode_scale drawing = Drawing(drawing_width, drawing_height) drawing.scale(barcode_scale, barcode_scale) drawing.add(barcode, name='barcode') barcode_encode = b64encode(renderPM.drawToString(drawing, fmt='PNG')) barcode_str = '<img style="width:320px;height:80px;" src="data:image/png;base64,{0} : ">'.format( barcode_encode) return barcode_str
def get_image(request, code): response = HttpResponse(content_type="image/png") barcode = Barcode.get_barcode(value=code, width=250) data = renderPM.drawToString(barcode, fmt='PNG') response.write(data) return response
def get_image(self): data = b64encode(renderPM.drawToString(self, fmt = 'PNG')) return "<img src='data:image/png;base64,{0}'>".format(data)
def get(self, request): code = request.data['barcode'] barcode = get_barcode(value=code, width=600) databar = b64encode(renderPM.drawToString(barcode, fmt='JPEG')) return Response({'barfile': databar})
def get_image(cod): barcode = get_barcode(value=cod, width=600) data = b64encode(renderPM.drawToString(barcode, fmt='PNG')) return format(data)