def __init__(self, filename, entity, options): self.color = (0, 0, 0) self.factor = 1 self.background_color = (0, 0, 0) self.analyse_options(options) self.surface = cairo.SVGSurface(filename, 10, 10) self.context = cairo.Context(self.surface) self.factor = 1 self.height = self.compute_height(entity) self.width = self.compute_width(entity) self.line_length = default_line_length self.surface = cairo.PDFSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) self.context = cairo.Context(self.surface) self.compute_wire_length(entity) if options.format.lower() == "svg": self.factor = 1 self.surface = cairo.SVGSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "pdf": self.factor = 1 self.surface = cairo.PDFSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "ps": self.factor = 1 self.surface = cairo.PSSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "png": self.factor = float( options.width / (self.width + self.factor * self.line_length * 2 + self.factor * bbox_w_margin * 2)) stride = cairo.ImageSurface.format_stride_for_width( cairo.FORMAT_ARGB32, 10000) data = bytearray(stride * 10000) # stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, int(self.width)+1) # data = bytearray(stride * int(self.height)) self.surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, int(self.factor * self.width + self.factor * self.line_length * 2 + self.factor * bbox_w_margin * 2), int(self.factor * self.height + self.factor * bbox_h_margin * 2), data, stride) self.context = cairo.Context(self.surface) self.draw_background(self.context) self.draw_entity(entity) self.surface.write_to_png(options.filename)
def test_pdf(): filename = 'tests/output/glyph_item.pdf' pt_per_mm = 72 / 25.4 width, height = 210 * pt_per_mm, 297 * pt_per_mm # A4 portrait surface = cairocffi.PDFSurface(filename, width, height) ctx = cairocffi.Context(surface) ctx.translate(width / 4, 100) layout = pangocairocffi.create_layout(ctx) layout.set_width(pangocffi.units_from_double(width / 2)) layout.set_alignment(pangocffi.Alignment.CENTER) layout.set_markup( '<span font="italic 30">Hi from Παν語</span>\n' '<span font="sans-serif">The text layout engine library for ' 'displaying <span font-weight="bold">multi-language</span> text!\n' 'Arabic: السَّلام عليكُم\n' 'Hebrew: שלום\n' 'Hindi नमस्ते, नमस्कार।\n' 'Russian: Здравствуйте!\n' 'Japanese: こんにちは, コンニチハ</span>' ) y_diff = 200 pangocairocffi.show_layout(ctx, layout) ctx.translate(0, y_diff) render_run_glyph_items(ctx, layout) ctx.translate(0, y_diff) render_cluster_glyph_items(ctx, layout) surface.finish()
def __init__(self, path: Path, surface_type: str, width: float, height: float, scale: float = 1): self.width = width self.height = height self.scale = scale self.path_as_posix = path.as_posix() if surface_type == 'pdf': surface = cairo.PDFSurface(self.path_as_posix, width, height) elif surface_type == 'svg': surface = cairo.SVGSurface(self.path_as_posix, width, height) elif surface_type == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height)) else: raise Exception('Unexpected Format: %s' % surface_type) context = cairo.Context(surface) self.surface = surface self.context = context if isinstance(self.surface, cairo.ImageSurface): self.context.scale( CanvasUnit.from_pt(1).px * self.scale, CanvasUnit.from_pt(1).px * self.scale)
def create_new_surface(file_format, target=None, width=1024, height=768): """ Create a new surface of the specified `file_format`: "png" for :class:`ImageSurface` "svg" for :class:`SVGSurface` "pdf" for :class:`PDFSurface` "ps" for :class:`PSSurface` The surface will be written to the `target` parameter , which can be a path to save the surface to, or file-like object with a `write()` method. You can also optionally specify the `width` and `height` of the generated surface if you know what it is; otherwise a default size of 1024 by 768 is used. """ file_format = file_format.lower() if file_format == 'png': surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, int(width), int(height)) elif file_format == 'svg': surface = cairo.SVGSurface(target, width, height) elif file_format == 'pdf': surface = cairo.PDFSurface(target, width, height) elif file_format == 'ps': surface = cairo.PSSurface(target, width, height) else: raise ValueError( 'Invalid value "{0}" for type parameter; valid values are "png", "svg", "pdf", and "ps".'.format(type)) return surface
def generate_award_pdf_svg(output, data, template_prefix, dpi=96): svgs = [] surface = cairocffi.PDFSurface(output, 1, 1) context = cairocffi.Context(surface) for d in data: t = d['template'] if len(t) < 1: continue text_template_filename = os.path.join(template_prefix, t + '.svg') with open(text_template_filename, 'r') as f: svg = etree.parse(f) svg = _data_into_svg(svg, d) svg_str = etree.tostring(svg) tree = Tree(bytestring=svg_str) svgs.append(svg_str) image_surface = PDFSurface(tree, None, dpi) surface.set_size(image_surface.width, image_surface.height) context.set_source_surface(image_surface.cairo, 0, 0) context.paint() surface.show_page() # with open(text_template_filename, 'r') as f: # svgs.append(_data_into_svg(etree.parse(f), d)) # svgs += b'</svg>' surface.finish() with open(output + '.svg', 'wb') as f: f.write(b"\n".join(svgs))
def SavePdf(self, filename, image): imageSize = [int(i) for i in image.GetSize()] surface = cairo.PDFSurface(filename, imageSize[0] + image.GetMargin() * 2, imageSize[1] + image.GetMargin() * 2) self._Render(image, surface)
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], 'unknown format: .{}'.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 __init__(self, hinting, font_size, style): self.dummy_context = ( cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)) if hinting else cairo.Context(cairo.PDFSurface(None, 1, 1))) self.layout = ffi.gc( pangocairo.pango_cairo_create_layout(ffi.cast( 'cairo_t *', self.dummy_context._pointer)), gobject.g_object_unref) self.font = font = ffi.gc( pango.pango_font_description_new(), pango.pango_font_description_free) assert not isinstance(style.font_family, basestring), ( 'font_family should be a list') family_p, family = unicode_to_char_p(','.join(style.font_family)) pango.pango_font_description_set_family(font, family_p) pango.pango_font_description_set_variant( font, PANGO_VARIANT[style.font_variant]) pango.pango_font_description_set_style( font, PANGO_STYLE[style.font_style]) pango.pango_font_description_set_stretch( font, PANGO_STRETCH[style.font_stretch]) pango.pango_font_description_set_weight(font, style.font_weight) pango.pango_font_description_set_absolute_size( font, units_from_double(font_size)) pango.pango_layout_set_font_description(self.layout, font)
def test_pdf(): filename = 'tests/output/error_underline.pdf' pt_per_mm = 72 / 25.4 width, height = 45 * pt_per_mm, 10 * pt_per_mm # A4 portrait surface = cairocffi.PDFSurface(filename, width, height) ctx = cairocffi.Context(surface) layout = pangocairocffi.create_layout(ctx) layout.set_width(pangocffi.units_from_double(width)) layout.set_alignment(pangocffi.Alignment.CENTER) layout.set_markup('Hi from Παν語') layout_logical_extent = layout.get_extents()[1] layout_baseline = pangocffi.units_to_double(layout.get_baseline()) layout_logical_extent_pixels = _convert_rectangle_to_pixels( layout_logical_extent) pangocairocffi.show_layout(ctx, layout) ctx.set_source_rgb(0.8, 0, 0) pangocairocffi.show_error_underline(ctx, layout_logical_extent_pixels[0], layout_baseline, layout_logical_extent_pixels[2], 2) surface.finish()
def __enter__(self): surface = cairo.PDFSurface(self.filename, self.width * self.PT_PER_MM, self.height * self.PT_PER_MM) self.ctx = cairo.Context(surface) # Make the base unit mm. self.ctx.scale(self.PT_PER_MM, self.PT_PER_MM) return self.ctx
def __init__(self, args: Namespace, chapters: List[Chapter]): global debug debug = args.debug print("Alustetaan...") self.params = Parameters(args) self.param_stack = [] self.page_direction = args.page_dir self.surf = cairo.PDFSurface(args.outfile, *self._fixXY(args.width, args.height)) self.context = cairo.Context(self.surf) #font_options = cairo.FontOptions() #font_options.set_antialias(cairo.ANTIALIAS_NONE) #self.context.set_font_options(font_options) self.context.rectangle(0, 0, *self._fixXY(args.width, args.height)) self.context.set_source_rgb(1, 1, 1) self.context.fill() self.context.set_source_rgb(0, 0, 0) self.page = 1 self.last_title = defaultdict(lambda: 0) for i, chapter in enumerate(chapters): print(f"Piirretään kappale {i+1}...") self.drawChapter(chapter) self.surf.finish()
def kernel_connector(png_list): pt_per_mm = 72 / 25.4 width, height = 210 * pt_per_mm, 297 * pt_per_mm upper_lim = height * 0.1 lateral_lim = width * 0.1 x_interval = width * 0.8 / 9.0 nodew = width * 0.005 nodeh = 0.0015 * height out_dir = os.path.split(png_list[0])[0] + "/kernels.pdf" ims1 = cairo.PDFSurface(out_dir, width, height) cr = cairo.Context(ims1) #cr.scale(pt_per_mm,pt_per_mm) coordinates = {} im = Image.open(png_list[0]) xwidth = int(width * 0.8 / 10.0) + 5 ywidth = int(im.size[1] * xwidth / float(im.size[0])) print xwidth, ywidth for k, i in enumerate(png_list): im = Image.open(i) im = im.resize([xwidth, ywidth], Image.LANCZOS) _buffer = StringIO.StringIO() im.save(_buffer, format="PNG") #,compress_level=0, dpi=(xwidth, ywidth)) _buffer.seek(0) png_image = cairo.ImageSurface.create_from_png(_buffer) cr.save() #cr.scale(0.5, 0.5) cr.set_source_surface(png_image, lateral_lim + (xwidth - 5) * (k % 10), upper_lim + ywidth * ((k / 10))) cr.paint() cr.show_page()
def convertList(urls, writeTo, dpi=72): #see https://github.com/Kozea/CairoSVG/issues/200 import cairocffi from cairosvg.parser import Tree from cairosvg.surface import PDFSurface class RecordingPDFSurface(PDFSurface): surface_class = cairocffi.RecordingSurface def _create_surface(self, width, height): cairo_surface = cairocffi.RecordingSurface( cairocffi.CONTENT_COLOR_ALPHA, (0, 0, width, height)) return cairo_surface, width, height surface = cairocffi.PDFSurface(writeTo, 1, 1) context = cairocffi.Context(surface) for url in urls: if os.name == 'nt': url = url.replace('\\', '/') url = 'file:///{}'.format(url) image_surface = RecordingPDFSurface(Tree(url=url), None, dpi) surface.set_size(image_surface.width, image_surface.height) context.set_source_surface(image_surface.cairo, 0, 0) context.paint() surface.show_page() surface.finish()
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() return filename
def _make_vector_surface(self, output_path, image_format, image_width, crop_margin): """ Make a vector surface in the appropriate format and with the appropriate size depending on whether or not there is a crop margin. In a vector image, 1 screen pixel is scaled to a certain number of points, such that the figure as a whole will conform to a certain physical size. """ if crop_margin is None: scale = image_width / self.screen_width image_height = self.screen_height * scale else: crop_margin = _mm_to_pts(crop_margin) if crop_margin > image_width / 3: raise ValueError( "The crop margin set on this image is too large for the image width. Increase the image width or decrease the crop margin." ) scale = (image_width - crop_margin * 2) / ( self._block_extents[2] - self._block_extents[0] ) image_height = ( self._block_extents[3] - self._block_extents[1] ) * scale + crop_margin * 2 if image_format == "PDF": surface = _cairo.PDFSurface(output_path, image_width, image_height) surface.set_metadata(_cairo.PDF_METADATA_CREATOR, f"eyekit {__version__}") elif image_format == "EPS": surface = _cairo.PSSurface(output_path, image_width, image_height) surface.set_eps(True) elif image_format == "SVG": surface = _cairo.SVGSurface(output_path, image_width, image_height) surface.set_device_scale(scale, scale) return surface, scale, crop_margin
def drawShapesToFile(filename): surface = cairo.PDFSurface((filename + '.pdf'), edger.width, edger.height) cr = cairo.Context(surface) for key, value in shapes.iteritems(): drawShape(value)
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 = getattr(image, 'tobytes', image.tostring)("raw", "BGRA") except SystemError: r, g, b, a = image.split() mrg = Image.merge("RGBA", (b, g, r, a)) imgd = getattr(mrg, 'tobytes', mrg.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 hasattr(cairo, "PDFSurface") and imageType == "pdf": surface = cairo.PDFSurface(fileName, size[0], size[1]) elif hasattr(cairo, "SVGSurface") and imageType == "svg": surface = cairo.SVGSurface(fileName, size[0], size[1]) elif hasattr(cairo, "PSSurface") 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 write_sticker_list(elements, filename, pcb): """output bom as stickers for each type of component in pdf format""" elements_grouped = get_value_list(elements) mm_to_pt = 2.835 file_pointer = filename and open(filename, 'wb') or sys.stdout pdf = cairo.PDFSurface(file_pointer, PAGE_WIDTH * mm_to_pt, PAGE_HEIGHT * mm_to_pt) gfx = cairo.Context(pdf) # Scale user units to millimetres gfx.scale(1 / 0.3528, 1 / 0.3528) labels = sheet_positions(gfx, LABEL_WIDTH, LABEL_HEIGHT, LABELS_X, LABELS_Y, MARGIN_TOP, MARGIN_LEFT, SPACING_X, SPACING_Y) bom = [] for line in elements_grouped: if not ("DO_NOT_PLACE" in line and line['DO_NOT_PLACE'] == "yes"): bom_line = Line(line['NAME'], line['VALUE'], line['PACKAGE'], "", "", line['__SIDE']) bom.append(bom_line) log.debug("number of labels: " + str(len(bom))) for line, label in _izip(bom, labels): line.render(gfx, (label[0] + 1, label[1]), LABEL_WIDTH - 2, 14) pcb.render(gfx, (label[0] + 1, label[1] + 14), LABEL_WIDTH - 2, LABEL_HEIGHT - 14, line.side, line.refs) log.debug("adding label at " + str(label) + " for " + str(line.refs)) log.debug("finishing page") gfx.show_page()
def draw_background_image(context, layer, image_rendering): # Background image if layer.image is None: return painting_x, painting_y, painting_width, painting_height = ( layer.painting_area) positioning_x, positioning_y, positioning_width, positioning_height = ( layer.positioning_area) position_x, position_y = layer.position repeat_x, repeat_y = layer.repeat image_width, image_height = layer.size if repeat_x == 'no-repeat': repeat_width = painting_width * 2 elif repeat_x in ('repeat', 'round'): repeat_width = image_width else: assert repeat_x == 'space' n_repeats = math.floor(positioning_width / image_width) if n_repeats >= 2: repeat_width = (positioning_width - image_width) / (n_repeats - 1) position_x = 0 # Ignore background-position for this dimension else: repeat_width = image_width if repeat_y == 'no-repeat': repeat_height = painting_height * 2 elif repeat_y in ('repeat', 'round'): repeat_height = image_height else: assert repeat_y == 'space' n_repeats = math.floor(positioning_height / image_height) if n_repeats >= 2: repeat_height = ( positioning_height - image_height) / (n_repeats - 1) position_y = 0 # Ignore background-position for this dimension else: repeat_height = image_height sub_surface = cairo.PDFSurface(None, repeat_width, repeat_height) sub_context = cairo.Context(sub_surface) sub_context.rectangle(0, 0, image_width, image_height) sub_context.clip() layer.image.draw(sub_context, image_width, image_height, image_rendering) pattern = cairo.SurfacePattern(sub_surface) pattern.set_extend(cairo.EXTEND_REPEAT) with stacked(context): if not layer.unbounded: context.rectangle(painting_x, painting_y, painting_width, painting_height) context.clip() # else: unrestricted, whole page box context.translate(positioning_x + position_x, positioning_y + position_y) context.set_source(pattern) context.paint()
def write_pdf(self, target=None, zoom=1, attachments=None): """Paint the pages in a PDF file, with meta-data. PDF files written directly by cairo do not have meta-data such as bookmarks/outlines and hyperlinks. :param target: A filename, file-like object, or :obj:`None`. :type zoom: float :param zoom: The zoom factor in PDF units per CSS units. **Warning**: All CSS units are affected, including physical units like ``cm`` and named sizes like ``A4``. For values other than 1, the physical CSS units will thus be “wrong”. :param attachments: A list of additional file attachments for the generated PDF document or :obj:`None`. The list's elements are :class:`Attachment` objects, filenames, URLs, or file-like objects. :returns: The PDF as byte string if :obj:`target` is :obj:`None`, otherwise :obj:`None` (the PDF is written to :obj:`target`). """ # 0.75 = 72 PDF point (cairo units) per inch / 96 CSS pixel per inch scale = zoom * 0.75 # Use an in-memory buffer. We will need to seek for metadata # TODO: avoid this if target can seek? Benchmark first. file_obj = io.BytesIO() # (1, 1) is overridden by .set_size() below. surface = cairo.PDFSurface(file_obj, 1, 1) context = cairo.Context(surface) LOGGER.info('Step 6 - Drawing') for page in self.pages: surface.set_size( math.floor( scale * (page.width + page.bleed['left'] + page.bleed['right'])), math.floor( scale * (page.height + page.bleed['top'] + page.bleed['bottom']))) with stacked(context): context.translate(page.bleed['left'] * scale, page.bleed['top'] * scale) page.paint(context, scale=scale) surface.show_page() surface.finish() LOGGER.info('Step 7 - Adding PDF metadata') write_pdf_metadata(self, file_obj, scale, self.metadata, attachments, self.url_fetcher) if target is None: return file_obj.getvalue() else: file_obj.seek(0) if hasattr(target, 'write'): shutil.copyfileobj(file_obj, target) else: with open(target, 'wb') as fd: shutil.copyfileobj(file_obj, fd)
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, six.string_types): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: warnings.warn("unknown format: %s" % fmt) return # 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) # 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 self.figure.draw(renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fo.close()
def draw_page(bot_clip, top_clip, ds, ms_values, scale, formations, legend=None, filename=None, current_data=None, annotation=None): global last_glc_height, log_settings last_glc_height = None height = top_clip - bot_clip top_margin = 24 bot_margin = 5 total_height_pt = scale * height + top_margin + bot_margin if filename is None: filename = 'output/ffq%04d' % bot_clip if log_settings.pdf_output: surface = cairo.PDFSurface(filename + '.pdf', mm_to_pt(160), total_height_pt) else: surface = cairo.SVGSurface(filename + '.svg', mm_to_pt(160), total_height_pt) ctx = cairo.Context(surface) ctx.select_font_face(log_settings.font_name) if annotation is not None: draw_annotation(ctx, 20, annotation[0], annotation[1]) draw_magsus(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip, ms_values) for i in range(0, len(ds)): if i > 0: above = ds[i - 1] else: above = None d = ds[i] if d.bot >= bot_clip and d.bot + d.thick <= top_clip: ds[i].draw(height + top_margin / scale, ctx, scale, above, bot_clip) draw_axis(height + top_margin / scale, ctx, 0., height, 100., scale, bot_clip) draw_header(ctx, top_margin - 10) if log_settings.decs_incs_list is not None: draw_decsincs_graph(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip) for (name, bot, top) in formations: draw_formation(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip, name, bot, top) if current_data is not None: page, currents = current_data draw_currents(ctx, 400, page, currents) if legend is not None: draw_legend(ctx, *legend) surface.finish()
def initpicture(self,imagedim,backcolor): self.mimagedim = imagedim self.msurface = cairo.PDFSurface(self.mfilename, imagedim.width(), imagedim.height()) self.mctx = cairo.Context(self.msurface) # set background self.mctx.rectangle(0.0, 0.0, imagedim.width(), imagedim.height()) self.mctx.set_source_rgb(backcolor.r(), backcolor.g(), backcolor.b()) self.mctx.fill()
def Surface(NAME, TYPE, Size): # NAME: Song Name (with page#?) # TYPE: {PDF, SVG} # Size: {A3, A4, B4, B3} if TYPE == 'PDF': return cairo.Context(cairo.PDFSurface(NAME + '.pdf', Size[0], Size[1])) elif TYPE == 'SVG': return cairo.Context(cairo.SVGSurface(NAME + '.svg', Size[0], Size[1]))
def render(self, content, out_filename): pdf_surface = cairo.PDFSurface(target=out_filename, width_in_points=self.media_width, height_in_points=self.media_height) self.cairo_context = cairo.Context(target=pdf_surface) self.pango_context = pc.PangoCairoFontMap().create_context() self.render_pages(content) self.cairo_context = None self.cairo_context = None
def test_pdf_parser(width, height): fileobj = io.BytesIO() surface = cairocffi.PDFSurface(fileobj, 1, 1) surface.set_size(width, height) surface.show_page() surface.finish() fileobj.seek(0) surface, = [page.MediaBox for page in PdfReader(fileobj).Root.Pages.Kids] assert surface == ['0', '0', str(width), str(height)]
def test_pdf_parser(width, height): fileobj = io.BytesIO() surface = cairocffi.PDFSurface(fileobj, 1, 1) surface.set_size(width, height) surface.show_page() surface.finish() sizes = [page.get_value('MediaBox', '\\[(.+?)\\]').strip() for page in pdf.PDFFile(fileobj).pages] assert sizes == ['0 0 {} {}'.format(width, height).encode('ascii')]
def render_pdf(self, tree, width, height, out_file): image = cairo.PDFSurface(out_file, width, height) d = cairo.Context(image) cache = Cache() root = tree.node(tree.root) hasBranchLengths = self.total_branchlength(tree) self.constructNode(tree, root, 0.0, math.pi * 2, 0.0, 0.0, 0.0, hasBranchLengths, cache) self.drawTree(cache, d, width, height) d.stroke()
def __init__( self, width: int, height: int, filename: str = None, export_format: str = "pdf", viewbox=None, step=1, debug_boxes=False, ): super().__init__(step, debug_boxes) self.width = width self.height = height self.device_width = width * RESOLUTION_SCALE self.device_height = height * RESOLUTION_SCALE self.filename = filename if export_format == "pdf": self.surface = cairo.PDFSurface(self.filename, self.device_width, self.device_height) self.reference_ctx = self.ctx = cairo.Context(self.surface) self.ctx.scale(RESOLUTION_SCALE, RESOLUTION_SCALE) self.cairosvg_dpi = TARGET_DPI elif export_format == "png": self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) self.ctx = cairo.Context(self.surface) self.ctx.set_source_rgba(0, 0, 0, 255) reference_surface = cairo.PDFSurface(None, self.device_width, self.device_height) self.reference_ctx = cairo.Context(reference_surface) self.reference_ctx.scale(RESOLUTION_SCALE, RESOLUTION_SCALE) self.cairosvg_dpi = CAIRO_DPI else: assert False self.line_scaling = 1.0 if viewbox: self.line_scaling = apply_viewbox(self.ctx, width, height, viewbox) self.pctx = pangocairocffi.create_context(self.reference_ctx)
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: warnings.warn("unknown format: %s" % fmt, stacklevel=2) return # 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()