def _render_one(self, config, tmpdir, renderer_cls, output_format, output_filename, osm_date, file_prefix): LOG.info('Rendering to %s format...' % output_format.upper()) factory = None dpi = layoutlib.commons.PT_PER_INCH if output_format == 'png': try: dpi = int(self._parser.get('rendering', 'png_dpi')) except ConfigParser.NoOptionError: dpi = OCitySMap.DEFAULT_RENDERING_PNG_DPI # As strange as it may seem, we HAVE to use a vector # device here and not a raster device such as # ImageSurface. Because, for some reason, with # ImageSurface, the font metrics would NOT match those # pre-computed by renderer_cls.__init__() and used to # layout the whole page def factory(w, h): w_px = int(layoutlib.commons.convert_pt_to_dots(w, dpi)) h_px = int(layoutlib.commons.convert_pt_to_dots(h, dpi)) LOG.debug("Rendering PNG into %dpx x %dpx area at %ddpi ..." % (w_px, h_px, dpi)) return cairo.PDFSurface(None, w_px, h_px) elif output_format == 'svg': factory = lambda w, h: cairo.SVGSurface(output_filename, w, h) elif output_format == 'svgz': factory = lambda w, h: cairo.SVGSurface( gzip.GzipFile(output_filename, 'wb'), w, h) elif output_format == 'pdf': factory = lambda w, h: cairo.PDFSurface(output_filename, w, h) elif output_format == 'ps': factory = lambda w, h: cairo.PSSurface(output_filename, w, h) elif output_format == 'ps.gz': factory = lambda w, h: cairo.PSSurface( gzip.GzipFile(output_filename, 'wb'), w, h) elif output_format == 'csv': # We don't render maps into CSV. return else: raise ValueError, \ 'Unsupported output format: %s!' % output_format.upper() renderer = renderer_cls(self._db, config, tmpdir, dpi, file_prefix) surface = factory(renderer.paper_width_pt, renderer.paper_height_pt) renderer.render(surface, dpi, osm_date) LOG.debug('Writing %s...' % output_filename) if output_format == 'png': surface.write_to_png(output_filename) surface.finish()
def start( self, fn, w, h, ): return cairo.PSSurface(fn, w, h)
def fileformat(filename, width, height): ''' figure out the output image format Args: filename: output filename, which will raise an error if it does not end in one of '.pdf', '.png', '.ps', or '.svg' width: width of the output image, in pixels height: height of the output image, in pixels Returns: tuple of cairo.Surface and filetype string e.g. 'pdf' or 'png' ''' if filename is not None: _, ext = os.path.splitext(filename) if not ext: ext = '.png' ext = ext[1:].lower() else: ext = None assert ext in ['png', 'pdf', 'ps', 'svg', None], f'unknown format: .{ext}' if ext == 'pdf': surface = cairo.PDFSurface(filename, width, height) elif ext == 'svg': surface = cairo.SVGSurface(filename, width, height) elif ext == 'ps': surface = cairo.PSSurface(filename, width, height) else: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) return ext, surface
def test_surface_file_obj_error(): class Fail(object): def write(*args): raise IOError cairo.PDFSurface(Fail(), 100, 100) cairo.PSSurface(Fail(), 100, 100)
def export_to(self, fname): area = self.allocation WIDTH, HEIGHT = area.width, area.height if '.ps' in fname: surface = cairo.PSSurface(fname, WIDTH, HEIGHT) cr = pangocairo.CairoContext(cairo.Context(surface)) self.__cairo_draw(cr) surface.flush() elif '.pdf' in fname: surface = cairo.PDFSurface(fname, WIDTH, HEIGHT) cr = pangocairo.CairoContext(cairo.Context(surface)) self.__cairo_draw(cr) surface.flush() else: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) cr = pangocairo.CairoContext(cairo.Context(surface)) self.__cairo_draw(cr) surface.write_to_png(fname)
def test_ps_get_eps(): surface = cairo.PSSurface(None, 10, 10) assert isinstance(surface.get_eps(), bool) surface.set_eps(True) assert surface.get_eps() with pytest.raises(TypeError): surface.set_eps(object())
def Draw(self, fname, *args): pnttoum = .002834646 f = open(fname, 'w') surface = cairo.PSSurface(f, 10000, 10000) surface.set_device_offset(4000, 4000) ctx = cairo.Context(surface) ctx.scale(pnttoum, pnttoum) ctx.set_source_rgb(0, 0, 0) for layer in [self] + list(args): for branch in layer.branches: if branch.blocks[0].placed: blocks = branch.blocks else: blocks = branch.blocks[1:] for block in blocks: for prim in block.children: if prim.neg: ctx.set_source_rgb(255, 255, 255) else: ctx.set_source_rgb(0, 0, 0) ctx.move_to(*prim.GetVertexCoords(False)[0][0:2]) for pnt in prim.GetVertexCoords(False): ctx.line_to(*pnt[0:2]) ctx.close_path() ctx.fill() ctx.set_line_width(.01) ctx.stroke() surface.flush() surface.finish() f.close()
def __init__(self, width, height, surfaceType=SurfaceType.SVG): self.width = width self.height = height self.surfaceType = surfaceType self.fileName = 'drawing' # Create Surface if self.surfaceType == SurfaceType.PDF: self.surface = cairo.PDFSurface(self.fileName + '.pdf', self.width, self.height) elif self.surfaceType == SurfaceType.PS: self.surface = cairo.PSSurface(self.fileName + '.ps', self.width, self.height) elif self.surfaceType == SurfaceType.SVG: self.surface = cairo.SVGSurface(self.fileName + '.svg', self.width, self.height) else: self.surface = None # Create Context self.context = cairo.Context(self.surface) self.context.scale(self.width, self.height) self._color = (0, 0, 0, 1) self._stroke = 1 / self.width self.origin = Point(0, 0) self._textSize = 12 / self.width
def __init__( self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imageType 4) creating a cairo surface and context within the constructor """ self.image = None self.imageType = imageType if image is not None: try: imgd = image.tostring("raw", "BGRA") except SystemError: r, g, b, a = image.split() imgd = Image.merge("RGBA", (b, g, r, a)).tostring("raw", "RGBA") a = array.array('B', imgd) stride = image.size[0] * 4 surface = cairo.ImageSurface.create_for_data( a, cairo.FORMAT_ARGB32, image.size[0], image.size[1], stride) ctx = cairo.Context(surface) size = image.size[0], image.size[1] self.image = image elif ctx is None and size is not None: if cairo.HAS_PDF_SURFACE and imageType == "pdf": surface = cairo.PDFSurface(fileName, size[0], size[1]) elif cairo.HAS_SVG_SURFACE and imageType == "svg": surface = cairo.SVGSurface(fileName, size[0], size[1]) elif cairo.HAS_PS_SURFACE and imageType == "ps": surface = cairo.PSSurface(fileName, size[0], size[1]) elif imageType == "png": surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1]) else: raise ValueError( "Unrecognized file type. Valid choices are pdf, svg, ps, and png" ) ctx = cairo.Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() else: surface = ctx.get_target() if size is None: try: size = surface.get_width(), surface.get_height() except AttributeError: size = None self.ctx = ctx self.size = size self.surface = surface self.fileName = fileName
def output_file(ctx): root, extension = os.path.splitext(target) if file_number: filename = '%s_%04d%s' % (root, file_number, extension) else: filename = target extension = extension.lower() if extension == '.png': surface = ctx.get_target() surface.write_to_png(target) elif extension == '.pdf': target_ctx = cairo.Context( cairo.PDFSurface(filename, *self.size_or_default())) target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint() elif extension in ('.ps', '.eps'): target_ctx = cairo.Context( cairo.PSSurface(filename, *self.size_or_default())) if extension == '.eps': target_ctx.set_eps(extension='.eps') target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint() elif extension == '.svg': target_ctx = cairo.Context( cairo.SVGSurface(filename, *self.size_or_default())) target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint()
def test_surface(): # TypeError: The Surface type cannot be instantiated test.raises(TypeError, "s = cairo.Surface()") if cairo.HAS_IMAGE_SURFACE: f, w, h = cairo.FORMAT_ARGB32, 100, 100 s = cairo.ImageSurface(f, w, h) assert s.get_format() == f assert s.get_width() == w assert s.get_height() == h if cairo.HAS_PDF_SURFACE: f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100 s = cairo.PDFSurface(f, w, h) if cairo.HAS_PS_SURFACE: f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100 s = cairo.PSSurface(f, w, h) if cairo.HAS_RECORDING_SURFACE: s = cairo.RecordingSurface(cairo.CONTENT_COLOR, None) s = cairo.RecordingSurface(cairo.CONTENT_COLOR, (1, 1, 10, 10)) if cairo.HAS_SVG_SURFACE: f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100 s = cairo.SVGSurface(f, w, h)
def test_ps_surface_dsc_comment(): surface = cairo.PSSurface(None, 10, 10) surface.dsc_comment("%%Title: My excellent document") with pytest.raises(cairo.Error): surface.dsc_comment("") with pytest.raises(TypeError): surface.dsc_comment(object())
def __init__(self, filename, pagedims_in_points, margins, style, smartOrient=True, useEPS=False): w, h = pagedims_in_points landscape = w > h and smartOrient if landscape: surf = cairo.PSSurface(filename, h, w) else: surf = cairo.PSSurface(filename, w, h) if useEPS: # Cairo < 1.8 (?) doesn't support this surf.set_eps(True) self.surf = surf def f(prend): surf.dsc_begin_page_setup() # surf.dsc_comment ('%%IncludeFeature: *PageSize Letter') # FIXME: is there some DSC comment to indicate the page # margins? if landscape: surf.dsc_comment('%%PageOrientation: Landscape') ctxt = cairo.Context(surf) if landscape: ctxt.translate(h / 2, w / 2) ctxt.rotate(-pi / 2) ctxt.translate(-w / 2, -h / 2) ctxt.translate(margins[3], margins[0]) weff = w - (margins[1] + margins[3]) heff = h - (margins[0] + margins[2]) assert weff > 0 assert heff > 0 prend(ctxt, style, weff, heff) ctxt.show_page() self._rfunc = f
def test_ps_surface(): assert isinstance(cairo.PSSurface(None, 10, 10), cairo.PSSurface) fd, fname = tempfile.mkstemp() os.close(fd) try: cairo.PSSurface(fname, 10, 10).finish() finally: os.unlink(fname) with pytest.raises(TypeError): cairo.PSSurface() with pytest.raises((ValueError, TypeError)): cairo.PSSurface("\x00", 100, 100) with pytest.raises(TypeError): cairo.PSSurface(object(), 100, 100)
def writePS(self, outFileName): surface = cairo.PSSurface(outFileName, 595, self.aspect * 595) context = cairo.Context(surface) context.scale(595, 595) self.drawPhylo(context) surface.finish()
def _save_ps_pdf(self, figure, filename, ext, orientation): # Cairo produces PostScript Level 3 # 'ggv' can't read cairo ps files, but 'gv' can dpi = 72 figure.dpi.set(dpi) w_in, h_in = figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = (height_in_points, width_in_points) if ext == 'ps': if not cairo.HAS_PS_SURFACE: raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(filename, width_in_points, height_in_points) else: # pdf if not cairo.HAS_PDF_SURFACE: raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(filename, width_in_points, height_in_points) # surface.set_dpi() can be used renderer = RendererCairo(figure.dpi) renderer.set_width_height(width_in_points, height_in_points) renderer.set_ctx_from_surface(surface) ctx = renderer.ctx if orientation == 'landscape': ctx.rotate(numx.pi / 2) ctx.translate(0, -height_in_points) # cairo/src/cairo_ps_surface.c # '%%Orientation: Portrait' is always written to the file header # '%%Orientation: Landscape' would possibly cause problems # since some printers would rotate again ? # TODO: # add portrait/landscape checkbox to FileChooser figure.draw(renderer) show_fig_border = False # for testing figure orientation and scaling if show_fig_border: ctx.new_path() ctx.rectangle(0, 0, width_in_points, height_in_points) ctx.set_line_width(4.0) ctx.set_source_rgb(1, 0, 0) ctx.stroke() ctx.move_to(30, 30) ctx.select_font_face('sans-serif') ctx.set_font_size(20) ctx.show_text('Origin corner') ctx.show_page()
def new_surface(self, name=None): surface = cairo.PSSurface( name, int( math.ceil(self.image_size()[0] + self.margin()[0] + self.margin()[1])), int( math.ceil(self.image_size()[1] + self.margin()[2] + self.margin()[3]))) surface.set_eps(True) return surface
def _save(self, fo, fmt, **kwargs): # save PDF/PS/SVG orientation = kwargs.get('orientation', 'portrait') dpi = 72 self.figure.dpi = dpi w_in, h_in = self.figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = ( height_in_points, width_in_points) if fmt == 'ps': if not hasattr(cairo, 'PSSurface'): raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(fo, width_in_points, height_in_points) elif fmt == 'pdf': if not hasattr(cairo, 'PDFSurface'): raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(fo, width_in_points, height_in_points) elif fmt in ('svg', 'svgz'): if not hasattr(cairo, 'SVGSurface'): raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if fmt == 'svgz': if isinstance(fo, str): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: raise ValueError("Unknown format: {!r}".format(fmt)) # surface.set_dpi() can be used renderer = RendererCairo(self.figure.dpi) renderer.set_width_height(width_in_points, height_in_points) renderer.set_ctx_from_surface(surface) ctx = renderer.gc.ctx if orientation == 'landscape': ctx.rotate(np.pi / 2) ctx.translate(0, -height_in_points) # Perhaps add an '%%Orientation: Landscape' comment? self.figure.draw(renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fo.close()
def save_frame_eps(self, name=None, num=None, size=None): if name is None: name = self.title if size is None: size = self.window.get_size() if num is None: num = self.saved_frame_counter self.saved_frame_counter += 1 surface = cairo.PSSurface("%s%04d.eps" % (name, num), size[0], size[1]) surface.set_eps(True) cr = cairo.Context(surface) self.draw(cr, *size) surface.write_to_png("%s%04d.png" % (name, num))
def test(): m = Map(256, 256) s_show = cairo.PSSurface(show_fn, 256, 256) s_no_show = cairo.PSSurface(no_show_fn, 256, 256) print "Saving", show_fn render(m, s_show, True) print "Saving", no_show_fn render(m, s_no_show, False) # The second render should not have called # show_page(), if we draw something now on this # map it appears still on the first page; on # s_show it should appear on the second page. for s in [s_show, s_no_show]: ctx = cairo.Context(s) ctx.set_source_rgba(0, 0, 0, 1) ctx.set_line_width(3.0) ctx.move_to(128, 128) ctx.rel_line_to(256, 0) ctx.stroke() # Make sure it is written to file. s.finish() p_show = read_pages(show_fn) p_no_show = read_pages(no_show_fn) success = (p_show == 2 and p_no_show == 1) for f in [show_fn, no_show_fn]: if os.path.exists(f): print "Removing", f os.remove(f) print "=======================================================" print "Status:", if success: print "SUCCESS" else: print "FAILED" print "=======================================================" return success
def create_rcontext(self, size, frame): ''' Called when CairoCanvas needs a cairo context to draw on ''' if self.format == 'pdf': surface = cairo.PDFSurface(self._filename(frame), *size) elif self.format == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size) elif self.format == 'ps': surface = cairo.PSSurface(self._filename(frame), *size) if self.format == 'svg': surface = cairo.SVGSurface(self._filename(frame), *size) return cairo.Context(surface)
def run(self): combo = self.wTree.get_object('saveAsComboBox') combo.set_active(0) cols = self.pM.dataTreeView.get_columns() mapType = cols[0].get_title() if mapType == 'Phamily': treeSelection = self.pM.dataTreeView.get_selection() (model, pathlist) = treeSelection.get_selected_rows() phamsToSave = [] for path in pathlist: iter = model.get_iter(path) phamName = str(model.get_value(iter, 0)) phamsToSave.append(phamName) else: print 'Phamily not selected' response = self.chooser.run() if response == gtk.RESPONSE_OK: dirname, ext = self.get_chooser_filename(self.chooser) if not ext: ext = 'pdf' for phamName in phamsToSave: filename = 'pham' + phamName + '.' + ext self.pM.draw_phamCircle_canvas(phamName=phamName) self.pM.phamCircleCanvas.props.automatic_bounds = True x1, y1, x2, y2 = self.pM.phamCircleCanvas.get_bounds() x, y = int(x2 - x1) + 240, int(y2 - y1) + 240 #self.pM.phamCircleCanvas.set_bounds(0,0, 10000, 10000) filename = os.path.join(dirname, filename) if ext == 'svg': surface = cairo.SVGSurface(filename, x, y) elif ext == 'pdf': surface = cairo.PDFSurface(filename, x, y) elif ext == 'ps': surface = cairo.PSSurface(filename, x, y) elif ext == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, x, y) cr = cairo.Context(surface) # center in the page (9x10) cr.translate(36, 130) self.pM.phamCircleCanvas.render(cr, None, 0.1) cr.show_page() if ext == 'png': surface.write_to_png(filename) elif response == gtk.RESPONSE_CANCEL: pass self.chooser.destroy()
def create_surface(self, width, height): self._validate_image_format() if self.fout or self.surface: raise CairoUtilError('tried to reuse a surface') self.fout = StringIO() if self.image_format in ('svg', 'png'): self.surface = cairo.SVGSurface(self.fout, width, height) elif self.image_format == 'ps': self.surface = cairo.PSSurface(self.fout, width, height) elif self.image_format == 'pdf': self.surface = cairo.PDFSurface(self.fout, width, height) else: raise CairoUtilError('internal image format error') return self.surface
def event_menuFileExport(self, *args): response, filename = self.getFilenameSave() if response == gtk.RESPONSE_OK: self.pwd = os.path.dirname(filename) if filename.endswith(".ps"): csurf = cairo.PSSurface(filename, self.width, self.height) if filename.endswith(".eps"): csurf = cairo.PSSurface(filename, self.width, self.height) try: csurf.set_eps(True) except: print "Could not enable eps." elif filename.endswith(".svg"): csurf = cairo.SVGSurface(filename, self.width, self.height) elif filename.endswith(".pdf"): csurf = cairo.PDFSurface(filename, self.width, self.height) self.cairo_context = cairo.Context(csurf) self.cairo_context.rectangle(0, 0, self.width, self.height) self.cairo_context.clip() self.render_cairo = True self.gfx_render() self.render_cairo = False csurf.finish() return True
def render(self, canvas, transparent=False): x0, y0, x1, y1 = canvas.bbox('all') self.markers = canvas.markers W = int((x1 - x0 + 2 * self.padding) * self.scale) H = int((y1 - y0 + 2 * self.padding) * self.scale) ext = os.path.splitext(self.fname)[1].lower() if ext == '.svg': surf = cairo.SVGSurface(self.fname, W, H) elif ext == '.pdf': surf = cairo.PDFSurface(self.fname, W, H) elif ext in ('.ps', '.eps'): surf = cairo.PSSurface(self.fname, W, H) if ext == '.eps': surf.set_eps(True) else: # Bitmap surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H) self.ctx = cairo.Context(surf) ctx = self.ctx if not transparent: # Fill background ctx.rectangle(0, 0, W, H) ctx.set_source_rgba(1.0, 1.0, 1.0) ctx.fill() ctx.scale(self.scale, self.scale) ctx.translate(-x0 + self.padding, -y0 + self.padding) if self.draw_bbox: last = len(canvas.shapes) for s in canvas.shapes[:last]: bbox = s.bbox r = canvas.create_rectangle(*bbox, line_color=(255, 0, 0, 127), fill=(0, 255, 0, 90)) for s in canvas.shapes: self.draw_shape(s) if ext in ('.svg', '.pdf', '.ps', '.eps'): surf.show_page() else: surf.write_to_png(self.fname)
def export_as_ps(self): """ Export the content shown in the drawing area as PS. """ # check if a path is defined if self._path != None: # read width and height width = self._drawing_area.get_allocation()[2] height = self._drawing_area.get_allocation()[3] # get GraphicsContext ctx = self._drawing_area.window.cairo_create() # create surface and export the created surface drawable_surface = ctx.get_target() surface = cairo.PSSurface(self._path, width, height) cairo_ctx = cairo.Context(surface) cairo_ctx.set_source_surface(drawable_surface, 0, 0) cairo_ctx.paint() cairo_ctx.show_page()
def render(canvas, fobj, width=None, height=None, scale=None): """Render the Encapsulated Postscript representation of a canvas. Because the canvas dimensions are explicitly specified when it's created, they map directly to real-world units in the output EPS image. Use one of `width`, `height`, or `scale` to override this behavior. Parameters ---------- canvas: :class:`toyplot.canvas.Canvas` Canvas to be rendered. fobj: file-like object or string The file to write. Use a string filepath to write data directly to disk. width: number, string, or (number, string) tuple, optional Specify the width of the output image with optional units. If the units aren't specified, defaults to points. See :ref:`units` for details on unit conversion in Toyplot. height: number, string, or (number, string) tuple, optional Specify the height of the output image with optional units. If the units aren't specified, defaults to points. See :ref:`units` for details on unit conversion in Toyplot. scale: number, optional Scales the output `canvas` by the given ratio. Examples -------- >>> toyplot.eps.render(canvas, "figure-1.eps", width=(4.5, "inches")) Notes ----- When you specify `width` or `height` the output EPS file may have a smaller bounding-box than expected. This is because `width` and `height` specify the desired dimensions of the *canvas*, while the output EPS file bounding box tightly bounds only the visible parts of the graphic. A Toyplot canvas is transparent by default, and thus wouldn't be included in the EPS bounding box, unless explicitly made visible with the "background-color" style. """ svg = toyplot.svg.render(canvas) scale = canvas._point_scale(width=width, height=height, scale=scale) surface = cairo.PSSurface(fobj, scale * canvas._width, scale * canvas._height) surface.set_eps(True) context = cairo.Context(surface) context.scale(scale, scale) toyplot.cairo.render(svg, context) surface.flush() surface.finish()
def __render( self, outputtype="png", width=None, height=None, ): output = ContentFile("", name="%s.%s" % ( self.cf.name, outputtype, )) width, height, = self.set_dimensions(width, height) if outputtype == "pdf": self.surface = cairo.PDFSurface( output, width, height, ) elif outputtype == "ps": self.surface = cairo.PSSurface( output, width, height, ) elif outputtype == "png": self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) else: raise Exception, "Must set the 'outputtype'." cr = cairo.Context(self.surface) wscale = float(width) / self.svg.props.width hscale = float(height) / self.svg.props.height cr.scale(wscale, hscale) # create cairo self.svg.render_cairo(cr) if outputtype == "png": self.surface.write_to_png(output) return output
def __init__(self, out_path=None, width=1980, height=1224, bg_color=(1, 1, 1)): """ During the initilization, define surface format, dimensions and background color (manifested by a rectangle of the surface size) """ # input handling if (out_path is None): raise NameError("There must be out_path specified!") else: self.out_path = out_path path = path_features(out_path)["path"] if not os.path.exists(path): os.makedirs(path) # creating cairo surface for drawing path_feature = path_features(out_path) if path_feature["extension"] == "pdf": self.surface = cairo.PDFSurface(out_path, width, height) elif path_feature["extension"] == "svg": self.surface = cairo.SVGSurface(out_path, width, height) elif path_feature["extension"] == "ps": self.surface = cairo.PSSurface(out_path, width, height) # different syntax for ImageSurface, out_path provided before finish elif path_feature["extension"] == "png": self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) else: raise NameError( "Unsupported graphics format.. Try to use .svg, .pdf, .png or .ps extension." ) # creating background rectangle to avoid transparent background in the final result self.ctx = cairo.Context(self.surface) self.ctx.set_source_rgb(bg_color[0], bg_color[1], bg_color[2]) self.ctx.rectangle(0, 0, width, height) self.ctx.fill()
def Save2D(self, fname): pnttoum = 1 / .002834646 f = open(fname, 'w') surface = cairo.PSSurface(f, 1000, 1000) ctx = cairo.Context(surface) ctx.scale(pnttoum, pnttoum) ctx.set_source_rgb(0, 0, 0) for path in self.GroupPaths(self.MidSlice()): ctx.move_to(*((self.hedra.get_vertex(path[0])))[0:2]) for pnt in path[1:]: ctx.line_to(*(10 * (self.hedra.get_vertex(pnt)))[0:2]) ctx.fill() ctx.set_line_width(.01) ctx.stroke() surface.flush() surface.finish() f.close()