当前位置: 首页>>代码示例>>Python>>正文


Python cairo.PDFSurface方法代码示例

本文整理汇总了Python中cairo.PDFSurface方法的典型用法代码示例。如果您正苦于以下问题:Python cairo.PDFSurface方法的具体用法?Python cairo.PDFSurface怎么用?Python cairo.PDFSurface使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cairo的用法示例。


在下文中一共展示了cairo.PDFSurface方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: barCoord

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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) 
开发者ID:aguai,项目名称:TMDLang,代码行数:20,代码来源:testCairo.py

示例2: main

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:aguai,项目名称:TMDLang,代码行数:18,代码来源:testCairo2.py

示例3: create_cairo_surface

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
def create_cairo_surface(self, fobj, width_in_points, height_in_points):
        return cairo.PDFSurface(fobj, width_in_points, height_in_points)

#------------------------------------------------------------------------
#
# PsDoc class
#
#------------------------------------------------------------------------ 
开发者ID:GenealogyCollective,项目名称:gprime,代码行数:10,代码来源:cairodoc.py

示例4: start

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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 
开发者ID:gramps-project,项目名称:addons-source,代码行数:16,代码来源:DescendantsLines.py

示例5: draw

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:saezlab,项目名称:pypath,代码行数:14,代码来源:drawing.py

示例6: init_pdf

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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) 
开发者ID:saezlab,项目名称:pypath,代码行数:8,代码来源:plot.py

示例7: __save

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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) 
开发者ID:openpaperwork,项目名称:paperwork-backend,代码行数:34,代码来源:doc.py

示例8: gen_calendar

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:eriknyquist,项目名称:generate_life_calendar,代码行数:31,代码来源:generate_life_calendar.py

示例9: render

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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) 
开发者ID:kevinpt,项目名称:symbolator,代码行数:49,代码来源:cairo_backend.py

示例10: _take_screenshot

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:ntu-dsi-dcn,项目名称:ntu-dsi-dcn,代码行数:45,代码来源:core.py

示例11: _save

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:55,代码来源:backend_cairo.py

示例12: _save

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:56,代码来源:backend_cairo.py

示例13: main

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:adamgreig,项目名称:agg-kicad,代码行数:60,代码来源:stickerbom.py

示例14: remove_all

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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 
开发者ID:jubalh,项目名称:MAT,代码行数:55,代码来源:office.py

示例15: _save

# 需要导入模块: import cairo [as 别名]
# 或者: from cairo import PDFSurface [as 别名]
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() 
开发者ID:alvarobartt,项目名称:twitter-stock-recommendation,代码行数:56,代码来源:backend_cairo.py


注:本文中的cairo.PDFSurface方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。