Esempio n. 1
0
    def __init__(self,
                 writing,
                 filename,
                 width=None,
                 height=None,
                 stroke_groups=None,
                 start=0,
                 length=None,
                 n_chars_per_row=None):
        """
        width and height are in points (1 point == 1/72.0 inch).
        """
        self.writing = writing
        self.width = width
        self.height = height
        self.stroke_groups = stroke_groups
        self.start = start
        self.length = length
        self.n_chars_per_row = n_chars_per_row

        self._init()

        self.surface = cairo.PDFSurface(filename, self.width, self.height)
        cr = cairo.Context(self.surface)
        cr.scale(
            float(self.width) / writing.get_width(),
            float(self.height) / writing.get_height())
        WritingStepsCairoRenderer.__init__(self, cr, writing)
Esempio n. 2
0
    def __save(self, target_path, pages):
        pdf_surface = cairo.PDFSurface(target_path, self.__page_format[0],
                                       self.__page_format[1])
        pdf_context = cairo.Context(pdf_surface)

        quality = float(self.__quality) / 100.0

        for page in [self.doc.pages[x] for x in range(pages[0], pages[1])]:
            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)
            new_size = (int(quality * img.size[0]), int(quality * img.size[1]))
            img = img.resize(new_size, Image.ANTIALIAS)

            scale_factor_x = x / img.size[0]
            scale_factor_y = y / img.size[1]
            scale_factor = min(scale_factor_x, scale_factor_y)

            img_surface = image2surface(img)

            pdf_context.identity_matrix()
            pdf_context.scale(scale_factor, scale_factor)
            pdf_context.set_source_surface(img_surface)
            pdf_context.paint()

            pdf_context.show_page()

        return target_path
Esempio n. 3
0
 def new(self):
     if self.format == 'png':
         self.set_point_size(PONT_IMG)
         self.sfc_width = int(self.gi_width * DPMM_IMG)
         self.sfc_height = int(self.gi_height * DPMM_IMG)
         self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                           self.sfc_width, self.sfc_height)
         self.surface.set_device_scale(DPMM_IMG, DPMM_IMG)
         self.surface.set_device_offset(self.gi_origin_x * DPMM_IMG,
                                        self.gi_origin_y * DPMM_IMG)
     elif self.format == 'svg':
         self.sfc_width = int(self.gi_width * DPMM)
         self.sfc_height = int(self.gi_height * DPMM)
         self.surface = cairo.SVGSurface(self.fobj, self.sfc_width,
                                         self.sfc_height)
         self.surface.set_device_scale(DPMM, DPMM)
         self.surface.set_device_offset(self.gi_origin_x * DPMM,
                                        self.gi_origin_y * DPMM)
     else:
         self.sfc_width = A4_WIDTH_POINTS
         self.sfc_height = A4_HEIGHT_POINTS
         self.surface = cairo.PDFSurface(self.fobj, self.sfc_width,
                                         self.sfc_height)
         self.surface.set_device_scale(DPMM, DPMM)
         self.surface.set_device_offset(
             self.gi_origin_x * DPMM + (210 - self.gi_width) * DPMM / 2,
             self.gi_origin_y * DPMM + 20)
     self.context = cairo.Context(self.surface)
     self.set_font('Times-Roman', 12 * POINT)
     self.set_linewidth(10)
Esempio n. 4
0
def save_cairo(evt):
    d = gtk.FileChooserDialog("Save file as svg, png or pdf", None,
                              gtk.FILE_CHOOSER_ACTION_SAVE,
                              (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                               gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))

    if (d.run() == gtk.RESPONSE_ACCEPT):
        filename = d.get_filename()
        cr_s = None
        left, top, width, height = current_toys[0].get_save_size()

        if filename[-4:] == ".pdf":
            cr_s = cairo.PDFSurface(filename, width, height)
        elif filename[-4:] == ".png":
            cr_s = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        else:
            cr_s = cairo.SVGSurface(filename, width, height)
        cr = cairo.Context(cr_s)
        cr = pangocairo.CairoContext(cairo.Context(cr_s))
        cr.translate(-left, -top)
        current_toys[0].draw(cr, (width, height), True)

        cr.show_page()
        del cr
        del cr_s
    d.destroy()
Esempio n. 5
0
def test_pdf_surface():
    fd, fname = tempfile.mkstemp()
    os.close(fd)
    try:
        cairo.PDFSurface(fname, 10, 10).finish()
    finally:
        os.unlink(fname)

    with pytest.raises(TypeError):
        cairo.PDFSurface()

    with pytest.raises((ValueError, TypeError)):
        cairo.PDFSurface("\x00")

    with pytest.raises(TypeError):
        cairo.PDFSurface(object(), 100, 100)
Esempio n. 6
0
def test_surface():
    # TypeError: The Surface type cannot be instantiated
    test.raises(TypeError, "s = cairo.Surface()")

    if cairo.HAS_IMAGE_SURFACE:
        f, w, h = cairo.FORMAT_ARGB32, 100, 100
        s = cairo.ImageSurface(f, w, h)
        assert s.get_format() == f
        assert s.get_width() == w
        assert s.get_height() == h

    if cairo.HAS_PDF_SURFACE:
        f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100
        s = cairo.PDFSurface(f, w, h)

    if cairo.HAS_PS_SURFACE:
        f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100
        s = cairo.PSSurface(f, w, h)

    if cairo.HAS_RECORDING_SURFACE:
        s = cairo.RecordingSurface(cairo.CONTENT_COLOR, None)
        s = cairo.RecordingSurface(cairo.CONTENT_COLOR, (1, 1, 10, 10))

    if cairo.HAS_SVG_SURFACE:
        f, w, h = tfi.TemporaryFile(mode='w+b'), 100, 100
        s = cairo.SVGSurface(f, w, h)
Esempio n. 7
0
def test_show_text_glyphs():
    surface = cairo.PDFSurface(None, 300, 300)
    context = cairo.Context(surface)
    context.scale(300, 300)
    context.select_font_face("Sans", cairo.FONT_SLANT_NORMAL,
                             cairo.FONT_WEIGHT_NORMAL)
    context.set_font_size(0.08)
    context.set_line_width(0.09)
    sf = context.get_scaled_font()
    glyphs, clusters, flags = sf.text_to_glyphs(0.5, 0.5, "foobar")
    context.show_text_glyphs("foobar", glyphs, clusters, flags)

    glyphs, clusters, flags = sf.text_to_glyphs(0.5, 0.5, "")
    context.show_text_glyphs("", glyphs, clusters, flags)

    with pytest.raises(TypeError):
        context.show_text_glyphs(object(), glyphs, clusters, flags)

    with pytest.raises(TypeError):
        context.show_text_glyphs("", [object()], clusters, flags)

    with pytest.raises(TypeError):
        context.show_text_glyphs("", object(), clusters, flags)

    with pytest.raises(TypeError):
        context.show_text_glyphs("", glyphs, [object()], flags)

    with pytest.raises(TypeError):
        context.show_text_glyphs("", glyphs, object(), flags)
Esempio n. 8
0
    def __init__(
            self,
            image=None,  # PIL image
            size=None,
            ctx=None,
            imageType=None,  # determines file type
            fileName=None,  # if set determines output file name
    ):
        """
    Canvas can be used in four modes:
    1) using the supplied PIL image
    2) using the supplied cairo context ctx
    3) writing to a file fileName with image type imageType
    4) creating a cairo surface and context within the constructor
    """
        self.image = None
        self.imageType = imageType
        if image is not None:
            try:
                imgd = image.tostring("raw", "BGRA")
            except SystemError:
                r, g, b, a = image.split()
                imgd = Image.merge("RGBA",
                                   (b, g, r, a)).tostring("raw", "RGBA")

            a = array.array('B', imgd)
            stride = image.size[0] * 4
            surface = cairo.ImageSurface.create_for_data(
                a, cairo.FORMAT_ARGB32, image.size[0], image.size[1], stride)
            ctx = cairo.Context(surface)
            size = image.size[0], image.size[1]
            self.image = image
        elif ctx is None and size is not None:
            if cairo.HAS_PDF_SURFACE and imageType == "pdf":
                surface = cairo.PDFSurface(fileName, size[0], size[1])
            elif cairo.HAS_SVG_SURFACE and imageType == "svg":
                surface = cairo.SVGSurface(fileName, size[0], size[1])
            elif cairo.HAS_PS_SURFACE and imageType == "ps":
                surface = cairo.PSSurface(fileName, size[0], size[1])
            elif imageType == "png":
                surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0],
                                             size[1])
            else:
                raise ValueError(
                    "Unrecognized file type. Valid choices are pdf, svg, ps, and png"
                )
            ctx = cairo.Context(surface)
            ctx.set_source_rgb(1, 1, 1)
            ctx.paint()
        else:
            surface = ctx.get_target()
            if size is None:
                try:
                    size = surface.get_width(), surface.get_height()
                except AttributeError:
                    size = None
        self.ctx = ctx
        self.size = size
        self.surface = surface
        self.fileName = fileName
Esempio n. 9
0
def render(
    pdf_filename: str,
    page_width: float,
    page_height: float,
    page_margin: float,
    picture_locations: List[List[PictureLocation]],
) -> None:
    """
    Render a packed set of pictures into a PDF.

    Picture locations and sizes should be given in millimeters with (0, 0)
    being the coordinate of the top-left of the page within the page margin.
    """

    with cairo.PDFSurface(
        pdf_filename, mm_to_pt(page_width), mm_to_pt(page_height)
    ) as surface:
        for page_number, page in enumerate(picture_locations):
            if page_number != 0:
                surface.show_page()

            for picture_location in page:
                ctx = cairo.Context(surface)
                ctx.scale(mm_to_pt(1), mm_to_pt(1))  # Use mm as unit
                ctx.translate(page_margin, page_margin)

                # Translate and rotate according to packing outcome
                ctx.translate(picture_location.x, picture_location.y)
                if picture_location.rotated:
                    ctx.rotate(math.pi / 2.0)
                    ctx.translate(0, -picture_location.picture.height)

                render_picture(ctx, picture_location.picture)
Esempio n. 10
0
def test_surface_file_obj_error():
    class Fail(object):
        def write(*args):
            raise IOError

    cairo.PDFSurface(Fail(), 100, 100)
    cairo.PSSurface(Fail(), 100, 100)
Esempio n. 11
0
 def get_dummy_surface(self):
     if not self.dummy_surface:
         self.dummy_surface = cairo.PDFSurface(
             None,
             16, 16,
         )
     return self.dummy_surface
Esempio n. 12
0
    def __init__(self, width, height, outputName):
        self.width = width
        self.height = height
        self.outputName = outputName

        self.ps = cairo.PDFSurface(self.outputName, self.width, self.height)
        self.cr = cairo.Context(self.ps)
        self.cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL,
                                 cairo.FONT_WEIGHT_NORMAL)
        self.cr.set_font_size(12)

        self.pgcr = pangocairo.CairoContext(self.cr)
        self.pgcr.set_antialias(cairo.ANTIALIAS_SUBPIXEL)

        self.layout = self.pgcr.create_layout()
        self.fontname = "Times New Roman"
        self.font = pango.FontDescription(self.fontname + " 8")
        self.layout.set_font_description(self.font)

        self.vOffset = 30
        self.LOffset = 30
        self.axesTop = 0.0
        self.axesBot = 0.0
        self.axesTick = 1.0
        self.axesOriginNormalised = 0.0
Esempio n. 13
0
 def export_pdf(self, filename):
     """
     Renders map as a PDF, exporting to file given.
     """
     import cairo
     surface = cairo.PDFSurface(filename, self.width, self.height)
     render(self, surface)
Esempio n. 14
0
def render(writer, trace, app_options, filename):
    handlers = {
        "png": (lambda w, h: cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h), \
                lambda sfc: sfc.write_to_png(filename)),
        "pdf": (lambda w, h: cairo.PDFSurface(filename, w, h), lambda sfc: 0),
        "svg": (lambda w, h: cairo.SVGSurface(filename, w, h), lambda sfc: 0)
    }

    if app_options.format is None:
        fmt = filename.rsplit('.', 1)[1]
    else:
        fmt = app_options.format

    if not (fmt in handlers):
        writer.error("Unknown format '%s'." % fmt)
        return 10

    make_surface, write_surface = handlers[fmt]
    options = RenderOptions(app_options)
    (w, h) = draw.extents(options, 1.0, trace)
    w = max(w, draw.MIN_IMG_W)
    surface = make_surface(w, h)
    ctx = cairo.Context(surface)
    draw.render(ctx, options, 1.0, trace)
    write_surface(surface)
    writer.status("bootchart written to '%s'" % filename)
def gen_calendar(start_date, title, filename):
    # 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()
    print('Created %s' % filename)
Esempio n. 16
0
 def _InitCairo(self):
     self.surface = cairo.PDFSurface(
         self.options['output_pdf'],
         self.width * self.POINTS_TO_MILLIMETERS_RATIO,
         self.height * self.POINTS_TO_MILLIMETERS_RATIO)
     self.fonts = dict()
     for slant in self.FONT_SLANTS:
         self.fonts[slant] = dict()
         for weight in self.FONT_WEIGHTS:
             self.fonts[slant][weight] = \
                 cairo.ToyFontFace("Monospace", slant, weight)
     self.context = cairo.Context(self.surface)
     self.context.scale(self.POINTS_TO_MILLIMETERS_RATIO,
                        self.POINTS_TO_MILLIMETERS_RATIO)
     self.context.set_font_face(
         self.fonts[cairo.FONT_SLANT_NORMAL][cairo.FONT_WEIGHT_NORMAL])
     self.context.set_font_size(1)
     self.font_ascent, self.font_descent, self.font_height, \
         self.font_max_x_advance, self.font_max_y_advance = \
             self.context.font_extents()
     font_scale_factor = \
         self.column_width / (self.font_max_x_advance * self.characters_in_a_row)
     self.context.set_font_size(font_scale_factor)
     self.font_ascent, self.font_descent, self.font_height, \
         self.font_max_x_advance, self.font_max_y_advance = \
             self.context.font_extents()
     self.context.set_line_width(0.05)
Esempio n. 17
0
def notebook_to_pdf(fil, t0=None):
    z = zipfile.ZipFile(fil, "r")

    size = 4963, 6278
    res = 1 / 10.
    surface = cairo.PDFSurface("{}.pdf".format(fil), *(i * res for i in size))
    ctx = cairo.Context(surface)
    ctx.scale(res, res)

    files = sorted(z.namelist())
    pages = [n for n in files if re.match(r"^data/.*/.*/.*.stf$", n)]
    papers = [n for n in files if re.match(r"^userdata/lsac_data/.*\.png$", n)]

    papers = [cairo.ImageSurface.create_from_png(z.open(p)) for p in papers]

    for i, name in enumerate(pages):
        paper = papers[i % 2]
        scale = size[0] / paper.get_width()
        f = z.open(name)
        ctx.save()
        ctx.scale(scale, scale)
        ctx.set_source_surface(paper, 0, 0)
        ctx.paint()
        ctx.restore()
        n = "{} - {}/{}".format(fil, i + 1, len(pages))
        Parser(f).parse(ctx, t0=t0, name=n)
        ctx.show_page()
Esempio n. 18
0
    def item_size(self, tasks_list, plot_param, ctx=None):

        dummy_width = 500

        plot_width = dummy_width + plot_param["margin_left"]

        # start draw
        if not ctx:
            buffered = BytesIO()
            report_surface = cairo.PDFSurface(buffered,
                                              plot_param["timeline_width"],
                                              plot_param["plot_height"])
            ctx = cairo.Context(report_surface)
            # svg = cairo.SVGSurface(buffered, dummy_width + plot_param["timeline_width"],  plot_param["plot_height"])
            # ctx = cairo.Context(svg)

        # border
        self.rectangle_draw(ctx, plot_param["line_width"],
                            plot_param["margin_left"],
                            plot_param["margin_top"], plot_width,
                            plot_param["plot_height"])

        item_width = self.item_draw(ctx,
                                    tasks_list,
                                    plot_param,
                                    calc_width=True)

        return item_width
    def write_to_pdf(self, target_path, dpi=300):
        """
		Write our Surface to a PDF file.

		Keyword arguments:
			target_path (str) -- the filepath of the PDF file to save to.
			dpi (float) -- the DPI of the image (default 300).
		"""
        # Calculate the scale of resolution between our Surface and our PDF
        points_per_inch = 72.0
        pdf_scale = points_per_inch / dpi

        # Create the PDFSurface object at the proper dimensions
        pdf_surface = cairo.PDFSurface(target_path,
                                       self.surface.get_width() * pdf_scale,
                                       self.surface.get_height() * pdf_scale)
        pdf_context = cairo.Context(pdf_surface)

        # Paint our Surface onto the PDFSurface
        pdf_context.save()
        try:
            pdf_context.identity_matrix()
            pdf_context.scale(pdf_scale, pdf_scale)
            pdf_context.set_source_surface(self.surface)
            pdf_context.paint()
        finally:
            pdf_context.restore()

        # Save the PDF file
        pdf_context.show_page()
Esempio n. 20
0
def gen_calendar(birthdate, 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 = birthdate
    while date.weekday() != 0:
        date -= datetime.timedelta(days=1)

    # Draw 52x90 grid of squares
    draw_grid(ctx, date, birthdate)
    ctx.show_page()
Esempio n. 21
0
def create_from_images(file_out, images, width=1189, height=1682, margin=0):
    temp_pdf = create_temp_file()
    pdfsurface = cairo.PDFSurface(temp_pdf, width, height)
    context = cairo.Context(pdfsurface)
    for image in images:
        basename, extension = os.path.splitext(image)
        if mimetypes.guess_type(image)[0] in MIMETYPES_PNG:
            imagesurface = cairo.ImageSurface.create_from_png(image)
        else:
            imagesurface = create_image_surface_from_file(image)
        imagesurface_width = imagesurface.get_width()
        imagesurface_height = imagesurface.get_height()
        scale_x = (imagesurface_width / MMTOPIXEL) / width
        scale_y = (imagesurface_height / MMTOPIXEL) / height
        if scale_x > scale_y:
            scale = scale_x
        else:
            scale = scale_y
        if margin == 1:
            scale = scale * 1.05
        elif margin == 2:
            scale = scale * 1.15
        x = (width - imagesurface_width / MMTOPIXEL / scale) / 2
        y = (height - imagesurface_height / MMTOPIXEL / scale) / 2
        context.save()
        context.translate(x, y)
        context.scale(1.0 / MMTOPIXEL / scale, 1.0 / MMTOPIXEL / scale)
        context.set_source_surface(imagesurface)
        context.paint()
        context.restore()
        context.show_page()
    pdfsurface.flush()
    pdfsurface.finish()
    shutil.copy(temp_pdf, file_out)
    os.remove(temp_pdf)
Esempio n. 22
0
    def capture_screenshot(self, widget):

        img_width = 512
        img_height = 512
        filename = "spiral"

        raster = True
        svg = True
        pdf = False
        if raster:
            img = cairo.ImageSurface(cairo.FORMAT_ARGB32, img_width,
                                     img_height)
            width, height = img.get_width(), img.get_height()
            c = cairo.Context(img)
            self.draw(c, width, height)
            img.write_to_png(filename + ".png")
        if pdf:
            surf = cairo.PDFSurface(filename + ".pdf", img_width, img_height)
            cr = cairo.Context(surf)
            self.draw(cr, img_width, img_height)
            cr.show_page()
        if svg:
            surf = cairo.SVGSurface(filename + ".svg", img_width, img_height)
            cr = cairo.Context(surf)
            self.draw(cr, img_width, img_height)
            cr.show_page()
Esempio n. 23
0
    def __remove_all_lightweight(self) -> bool:
        """
            Load the document into Poppler, render pages on a new PDFSurface.
        """
        document = Poppler.Document.new_from_file(self.uri, None)
        pages_count = document.get_n_pages()

        tmp_path = tempfile.mkstemp()[1]
        pdf_surface = cairo.PDFSurface(tmp_path, 10, 10)  # resized later anyway
        pdf_context = cairo.Context(pdf_surface)  # context draws on the surface

        for pagenum in range(pages_count):
            logging.info("Rendering page %d/%d", pagenum + 1, pages_count)
            page = document.get_page(pagenum)
            page_width, page_height = page.get_size()
            pdf_surface.set_size(page_width, page_height)
            pdf_context.save()
            page.render_for_printing(pdf_context)
            pdf_context.restore()
            pdf_context.show_page()  # draw pdf_context on pdf_surface
        pdf_surface.finish()

        self.__remove_superficial_meta(tmp_path, self.output_filename)
        os.remove(tmp_path)

        return True
Esempio n. 24
0
    def __init__(self, width, height, surfaceType=SurfaceType.SVG):
        self.width = width
        self.height = height
        self.surfaceType = surfaceType
        self.fileName = 'drawing'

        # Create Surface
        if self.surfaceType == SurfaceType.PDF:
            self.surface = cairo.PDFSurface(self.fileName + '.pdf', self.width,
                                            self.height)
        elif self.surfaceType == SurfaceType.PS:
            self.surface = cairo.PSSurface(self.fileName + '.ps', self.width,
                                           self.height)
        elif self.surfaceType == SurfaceType.SVG:
            self.surface = cairo.SVGSurface(self.fileName + '.svg', self.width,
                                            self.height)
        else:
            self.surface = None

        # Create Context
        self.context = cairo.Context(self.surface)

        self.context.scale(self.width, self.height)

        self._color = (0, 0, 0, 1)
        self._stroke = 1 / self.width
        self.origin = Point(0, 0)
        self._textSize = 12 / self.width
Esempio n. 25
0
def test_surface_from_stream_closed_before_finished():
    for Kind in [cairo.PDFSurface, cairo.PSSurface, cairo.SVGSurface]:
        fileobj = io.BytesIO()
        surface = cairo.PDFSurface(fileobj, 128, 128)
        fileobj.close()
        with pytest.raises(IOError):
            surface.finish()
        def pdf_cb(*args):
            dlg = gtk.FileChooserDialog(
                title="Save As...",
                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK))
            filter = gtk.FileFilter()
            filter.set_name("PDF")
            filter.add_pattern("*.pdf")
            dlg.add_filter(filter)
            resp = dlg.run()
            filename = dlg.get_filename()
            dlg.destroy()

            if resp != gtk.RESPONSE_OK:
                return

            fd, tmpfile = tempfile.mkstemp()
            self.pen.get_guid(tmpfile, self.guid, 0)
            z = zipfile.ZipFile(tmpfile, "r")
            name = self.ls[path][3]
            f = z.open(name)
            p = Parser(f)
            surface = cairo.PDFSurface(filename, 4963, 6278)
            ctx = cairo.Context(surface)
            ctx.set_source_rgb(255, 255, 255)
            ctx.paint()
            ctx.set_source_rgb(0, 0, 0)
            try:
                p.parse(ctx)
            except Exception, e:
                print "Parse error"
                print e
Esempio n. 27
0
def drawGraph(graph,graphName):
  import cairo
  import pangocairo
  b = Borg()
  tmpDir = b.tmpDir
  outputDir = os.environ['OUTPUT_DIR']
  tmpFile = tmpDir + '/' + graphName + '.pdf'
#Make the surface a bit bigger to account for graphviz positioning the image too far left
  s = cairo.PDFSurface(tmpFile,graph.width + 5,graph.height + 5)
  c1 = cairo.Context(s)
  c2 = pangocairo.CairoContext(c1)
  c2.set_line_cap(cairo.LINE_CAP_BUTT)
  c2.set_line_join(cairo.LINE_JOIN_MITER)
  graph.zoom_ratio = 1
#Reposition the co-ordinates to start a bit more to the right
  c2.translate(3,3)
  graph.draw(c2)
  s.finish()
  svgFile = tmpDir + '/' + graphName + '.svg'
  s = cairo.SVGSurface(svgFile,graph.width,graph.height)
  c1 = cairo.Context(s)
  c2 = pangocairo.CairoContext(c1)
  c2.set_line_cap(cairo.LINE_CAP_BUTT)
  c2.set_line_join(cairo.LINE_JOIN_MITER)
  graph.zoom_ratio = 1
  graph.draw(c2)
  s.finish()

  ppmFile = tmpDir + '/' + graphName + '.ppm'
  jpgFile = outputDir + '/' + graphName
  cmd1 = 'pdftoppm ' + tmpFile + ' > ' + ppmFile
  cmd2 = 'ppmtojpeg ' + ppmFile + ' > ' + jpgFile
  os.system(cmd1)
  os.system(cmd2)
Esempio n. 28
0
def renderToPdf(envLL, filename, sizex, sizey):
    """Renders the specified Box2d and zoom level as a PDF"""
    basefilename = os.path.splitext(filename)[0]
    mergedpdf = None
    for mapname in MAPNIK_LAYERS:
        print 'Rendering', mapname
        # Render layer PDF.
        localfilename = basefilename + '_' + mapname + '.pdf'
        file = open(localfilename, 'wb')
        surface = cairo.PDFSurface(file.name, sizex, sizey)
        envMerc = LLToMerc(envLL)
        map = mapnik.Map(sizex, sizey)
        mapnik.load_map(map, mapname + ".xml")
        map.zoom_to_box(envMerc)
        mapnik.render(map, surface)
        surface.finish()
        file.close()
        # Merge with master.
        if not mergedpdf:
            mergedpdf = PdfFileWriter()
            localpdf = PdfFileReader(open(localfilename, "rb"))
            page = localpdf.getPage(0)
            mergedpdf.addPage(page)
        else:
            localpdf = PdfFileReader(open(localfilename, "rb"))
            page.mergePage(localpdf.getPage(0))
    output = open(filename, 'wb')
    mergedpdf.write(output)
    output.close()
Esempio n. 29
0
    def save_pdf(self, filename, canvas):

        self.logger.info('Exporting to PDF')
        self.logger.debug('PDF path is %s' % filename)

        view = View(canvas)

        self.update_painters(view)

        # Update bounding boxes with a temporaly CairoContext
        # (used for stuff like calculating font metrics)
        tmpsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
        tmpcr = cairo.Context(tmpsurface)
        view.update_bounding_box(tmpcr)
        tmpcr.show_page()
        tmpsurface.flush()

        w, h = view.bounding_box.width, view.bounding_box.height
        surface = cairo.PDFSurface(filename, w, h)
        cr = cairo.Context(surface)
        view.matrix.translate(-view.bounding_box.x, -view.bounding_box.y)
        view.paint(cr)
        cr.show_page()
        surface.flush()
        surface.finish()
Esempio n. 30
0
def fileformat(filename, width, height):
    ''' figure out the output image format
    
    Args:
        filename: output filename, which will raise an error if it does not end
            in one of '.pdf', '.png', '.ps', or '.svg'
        width: width of the output image, in pixels
        height: height of the output image, in pixels
    
    Returns:
        tuple of cairo.Surface and filetype string e.g. 'pdf' or 'png'
    '''
    
    if filename is not None:
        _, ext = os.path.splitext(filename)
        if not ext:
            ext = '.png'
        ext = ext[1:].lower()
    else:
        ext = None
    
    assert ext in ['png', 'pdf', 'ps', 'svg', None], f'unknown format: .{ext}'
    
    if ext == 'pdf':
        surface = cairo.PDFSurface(filename, width, height)
    elif ext == 'svg':
        surface = cairo.SVGSurface(filename, width, height)
    elif ext == 'ps':
        surface = cairo.PSSurface(filename, width, height)
    else:
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width,  height)
    
    return ext, surface