Python cairo.PDFSurface() Examples

The following are 28 code examples of cairo.PDFSurface(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cairo , or try the search function .
Example #1
Source File: testCairo2.py    From TMDLang with GNU General Public License v3.0 6 votes vote down vote up
def main():

    ps = cairo.PDFSurface("pdffile.pdf", 504, 648)
    cr = cairo.Context(ps)

    cr.set_source_rgb(0, 0, 0)
    cr.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
                        cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(40)
    cr.move_to(10, 50)
    cr.show_text(chr(119046) +'1 2 3 4 5' + chr(119047) )
    cr.set_line_width(11)
    cr.move_to(100, 100)
    cr.line_to(20, 300)

    cr.show_page() 
Example #2
Source File: cairodoc.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def create_cairo_surface(self, fobj, width_in_points, height_in_points):
        return cairo.PDFSurface(fobj, width_in_points, height_in_points)

#------------------------------------------------------------------------
#
# PsDoc class
#
#------------------------------------------------------------------------ 
Example #3
Source File: DescendantsLines.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def start(self, fn, w, h,):
        self.fn = fn
        if OUTPUT_FMT == 'PNG' or not fn:
            self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                              int(w + 1), int(h + 1))
        elif OUTPUT_FMT == 'SVG':
            self.surface = cairo.SVGSurface(self.fn, int(w + 1), int(h + 1))
        elif OUTPUT_FMT == 'PDF':
            self.surface = cairo.PDFSurface(self.fn, int(w + 1), int(h + 1))
        elif OUTPUT_FMT == 'PS':
            self.surface = cairo.PSSurface(self.fn, int(w + 1), int(h + 1))
        else:
            raise AttributeError("no such output format: '%s'" % OUTPUT_FMT)
        return self.surface 
Example #4
Source File: testCairo.py    From TMDLang with GNU General Public License v3.0 5 votes vote down vote up
def barCoord(n):
    '''
    returns ((x-left-top, y-left-top),
            (x-left-buttom, y-right-buttom),
            (x-right-top, y-right-top),
            (x-right-buttom, y-right-buttom))
            coordinate of a bar area   
    '''
    return ((100 + (n % 6) * 380, 430 + (n // 6) * 331),                # left x-axis 100pt for margin blank    
            (100 + (n % 6) * 380, 430 + (n // 6) * 331 + 252),          # top  y-axis 430pt for title
            (100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331),          # 252 is 1.5em for chord 1em * 3 for melody 56pt per em
            (100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331 + 252))


# ctx = cairo.Context(cairo.PDFSurface("haha.pdf", 2480.0, 3508.0))
# ctx.set_font_size(30)
# ctx.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
#                     cairo.FONT_WEIGHT_NORMAL) 
Example #5
Source File: doc.py    From paperwork-backend with GNU General Public License v3.0 5 votes vote down vote up
def __save(self, target_path, pages, progress_cb=dummy_export_progress_cb):
        # XXX(Jflesch): This is a problem. It will fails if someone tries
        # to export to a non-local directory. We should use
        # cairo_pdf_surface_create_for_stream()
        target_path = self.doc.fs.unsafe(target_path)

        pdf_surface = cairo.PDFSurface(target_path,
                                       self.__page_format[0],
                                       self.__page_format[1])
        pdf_context = cairo.Context(pdf_surface)

        pages = [self.doc.pages[x] for x in range(pages[0], pages[1])]
        for page_idx, page in enumerate(pages):
            progress_cb(page_idx, len(pages))
            img = page.img
            if (img.size[0] < img.size[1]):
                (x, y) = (min(self.__page_format[0], self.__page_format[1]),
                          max(self.__page_format[0], self.__page_format[1]))
            else:
                (x, y) = (max(self.__page_format[0], self.__page_format[1]),
                          min(self.__page_format[0], self.__page_format[1]))
            pdf_surface.set_size(x, y)

            logger.info("Adding text to PDF page {} ...".format(page))
            self.__paint_txt(pdf_surface, (x, y), pdf_context, page)
            logger.info("Adding image to PDF page {} ...".format(page))
            self.__paint_img(pdf_surface, (x, y), pdf_context, page)
            pdf_context.show_page()
            logger.info("Page {} ready".format(page))

        progress_cb(len(pages), len(pages))
        return self.doc.fs.safe(target_path) 
Example #6
Source File: drawing.py    From pypath with GNU General Public License v3.0 5 votes vote down vote up
def draw(self):
        '''
        main function of this class
        '''
        self.srf = cairo.PDFSurface(self.outf, self.width, self.height)
        self.ctx = cairo.Context(self.srf)
        self.draw_table()
        self.colnames()
        self.rownames()
        self.draw_circles()
        self.srf.finish()
        self.srf.flush() 
Example #7
Source File: plot.py    From pypath with GNU General Public License v3.0 5 votes vote down vote up
def init_pdf(self):
        import cairo
        self.surface = cairo.PDFSurface(self.fname, self.width, self.height)
        self.bbox = igraph.drawing.utils.BoundingBox(self.margin, self.margin,
                                                     self.width - self.margin,
                                                     self.height - self.margin) 
Example #8
Source File: backend_cairo.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
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)
            # Perhaps add an '%%Orientation: Landscape' comment?

        self.figure.draw(renderer)

        ctx.show_page()
        surface.finish()
        if fmt == 'svgz':
            fo.close() 
Example #9
Source File: cairo_backend.py    From symbolator with MIT License 4 votes vote down vote up
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) 
Example #10
Source File: backend_cairo.py    From CogAlg with MIT License 4 votes vote down vote up
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() 
Example #11
Source File: office.py    From MAT with GNU General Public License v2.0 4 votes vote down vote up
def remove_all(self):
        """ Opening the PDF with poppler, then doing a render
            on a cairo pdfsurface for each pages.

            http://cairographics.org/documentation/pycairo/2/

            The use of an intermediate tempfile is necessary because
            python-cairo segfaults on unicode.
            See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=699457
        """
        document = Poppler.Document.new_from_file(self.uri, self.password)
        try:
            output = tempfile.mkstemp()[1]

            # Size doesn't matter (pun intended),
            # since the surface will be resized before
            # being rendered
            surface = cairo.PDFSurface(output, 10, 10)
            context = cairo.Context(surface)  # context draws on the surface

            logging.debug('PDF rendering of %s' % self.filename)
            for pagenum in range(document.get_n_pages()):
                page = document.get_page(pagenum)
                page_width, page_height = page.get_size()
                surface.set_size(page_width, page_height)
                context.save()
                if self.pdf_quality:  # this may reduce the produced PDF size
                    page.render(context)
                else:
                    page.render_for_printing(context)
                context.restore()
                context.show_page()  # draw context on surface
            surface.finish()
            shutil.move(output, self.output)
        except:
            logging.error('Something went wrong when cleaning %s.' % self.filename)
            return False

        try:
            import pdfrw  # For now, poppler cannot write meta, so we must use pdfrw

            logging.debug('Removing %s\'s superficial metadata' % self.filename)
            trailer = pdfrw.PdfReader(self.output)
            trailer.Info.Producer = None
            trailer.Info.Creator = None
            writer = pdfrw.PdfWriter()
            writer.trailer = trailer
            writer.write(self.output)
            self.do_backup()
        except:
            logging.error('Unable to remove all metadata from %s, please install pdfrw' % self.output)
            return False
        return True 
Example #12
Source File: backend_cairo.py    From coffeegrindsize with MIT License 4 votes vote down vote up
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() 
Example #13
Source File: core.py    From Tocino with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #14
Source File: core.py    From ns3-802.11ad with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #15
Source File: core.py    From ns3-ecn-sharp with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #16
Source File: generate_life_calendar.py    From generate_life_calendar with Apache License 2.0 4 votes vote down vote up
def gen_calendar(start_date, title, filename):
    if len(title) > MAX_TITLE_SIZE:
        raise ValueError("Title can't be longer than %d characters"
            % MAX_TITLE_SIZE)

    # Fill background with white
    surface = cairo.PDFSurface (filename, DOC_WIDTH, DOC_HEIGHT)
    ctx = cairo.Context(surface)

    ctx.set_source_rgb(1, 1, 1)
    ctx.rectangle(0, 0, DOC_WIDTH, DOC_HEIGHT)
    ctx.fill()

    ctx.select_font_face(FONT, cairo.FONT_SLANT_NORMAL,
        cairo.FONT_WEIGHT_BOLD)
    ctx.set_source_rgb(0, 0, 0)
    ctx.set_font_size(BIGFONT_SIZE)
    w, h = text_size(ctx, title)
    ctx.move_to((DOC_WIDTH / 2) - (w / 2), (Y_MARGIN / 2) - (h / 2))
    ctx.show_text(title)

    # Back up to the last monday
    date = start_date
    while date.weekday() != 0:
        date -= datetime.timedelta(days=1)

    # Draw 52x90 grid of squares
    draw_grid(ctx, date)
    ctx.show_page() 
Example #17
Source File: core.py    From CRE-NS3 with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #18
Source File: stickerbom.py    From agg-kicad with MIT License 4 votes vote down vote up
def main():
    args = get_args()

    bom = BOM(args.xmlpath, include=args.include, exclude=args.exclude)

    with open(args.xmlpath[:-3] + "kicad_pcb") as f:
        pcb = PCB(sexp.parse(f.read()))

    mm_to_pt = 2.835
    ps = cairo.PDFSurface(args.pdfpath,
                          args.page_width*mm_to_pt,
                          args.page_height*mm_to_pt)
    cr = cairo.Context(ps)

    # Scale user units to millimetres
    cr.scale(mm_to_pt, mm_to_pt)

    labels = sheet_positions(cr,
                             args.label_width, args.label_height,
                             args.labels_x, args.labels_y,
                             args.margin_top, args.margin_left,
                             args.spacing_x, args.spacing_y)

    suppliers = [name.strip() for name in args.suppliers.split(",")]

    for line in bom.lines:
        if line.supplier not in suppliers:
            continue
        if not line.footprint and not args.include_parts_without_footprint:
            continue
        label = next(labels)
        line.render(cr,
                    (label[0]+1, label[1]),
                    args.label_width-2, 14)
        sides = pcb.get_mod_sides(line.refs)

        if "F.Cu" in sides and "B.Cu" in sides:
            # if both sides present, split area and draw both
            pcb.render(cr, (label[0]+1, label[1]+14),
                       (args.label_width-4)/2.0, args.label_height-14,
                       ["F.Fab"], ["F.Cu", "*.Cu", "F.SilkS"], sides["F.Cu"])

            pcb.render(cr, (label[0]+3+(args.label_width-3)/2.0, label[1]+14),
                       (args.label_width-4)/2.0, args.label_height-14,
                       ["B.Fab"], ["B.Cu", "*.Cu", "B.SilkS"], sides["B.Cu"],
                       args.flip_vert)

        elif "F.Cu" in sides:
            pcb.render(cr, (label[0]+1, label[1]+14),
                       args.label_width-2, args.label_height-14,
                       ["F.Fab"], ["F.Cu", "*.Cu", "F.SilkS"], sides["F.Cu"])
        elif "B.Cu" in sides:
            pcb.render(cr, (label[0]+1, label[1]+14),
                       args.label_width-2, args.label_height-14,
                       ["B.Fab"], ["B.Cu", "*.Cu", "B.SilkS"], sides["B.Cu"],
                       args.flip_vert)

    cr.show_page() 
Example #19
Source File: core.py    From ns-3-dev-git with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #20
Source File: core.py    From royal-chaos with MIT License 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #21
Source File: backend_cairo.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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() 
Example #22
Source File: backend_cairo.py    From GraphicDesignPatternByPython with MIT License 4 votes vote down vote up
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() 
Example #23
Source File: core.py    From ns3-rdma with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #24
Source File: core.py    From 802.11ah-ns3 with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #25
Source File: core.py    From ns3-load-balance with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #26
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 4 votes vote down vote up
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() 
Example #27
Source File: core.py    From IEEE-802.11ah-ns-3 with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish() 
Example #28
Source File: core.py    From ntu-dsi-dcn with GNU General Public License v2.0 4 votes vote down vote up
def _take_screenshot(self, dummy_button):
        #print "Cheese!"
        file_name = self._get_export_file_name()
        if file_name is None:
            return

        # figure out the correct bounding box for what is visible on screen
        x1 = self._scrolled_window.get_hadjustment().value
        y1 = self._scrolled_window.get_vadjustment().value
        x2 = x1 + self._scrolled_window.get_hadjustment().page_size
        y2 = y1 + self._scrolled_window.get_vadjustment().page_size
        bounds = goocanvas.Bounds()
        bounds.x1, bounds.y1 = self.canvas.convert_from_pixels(x1, y1)
        bounds.x2, bounds.y2 = self.canvas.convert_from_pixels(x2, y2)
        dest_width = bounds.x2 - bounds.x1
        dest_height = bounds.y2 - bounds.y1
        #print bounds.x1, bounds.y1, " -> ", bounds.x2, bounds.y2

        dummy, extension = os.path.splitext(file_name)
        extension = extension.lower()
        if extension == '.eps':
            surface = cairo.PSSurface(file_name, dest_width, dest_height)
        elif extension == '.pdf':
            surface = cairo.PDFSurface(file_name, dest_width, dest_height)
        elif extension == '.svg':
            surface = cairo.SVGSurface(file_name, dest_width, dest_height)
        else:
            dialog = gtk.MessageDialog(parent  = self.canvas.get_toplevel(),
                		       flags   = gtk.DIALOG_DESTROY_WITH_PARENT,
                		       type    = gtk.MESSAGE_ERROR,
                		       buttons = gtk.BUTTONS_OK,
                		       message_format = "Unknown extension '%s' (valid extensions are '.eps', '.svg', and '.pdf')"
                                                          % (extension,))
            dialog.run()
            dialog.destroy()
            return

        # draw the canvas to a printing context
        cr = cairo.Context(surface)
        cr.translate(-bounds.x1, -bounds.y1)
        self.canvas.render(cr, bounds, self.zoom.value)
        cr.show_page()
        surface.finish()