Exemplo n.º 1
0
    def _render_to_pdf(self,
                       save=True,
                       canvas=None,
                       filename=None,
                       dest_box=None):
        """
        """
        from chaco.pdf_graphics_context import PdfPlotGraphicsContext

        if filename:
            if not filename.endswith('.pdf'):
                filename += '.pdf'
                #        if dest_box is None:
                #            dest_box = [0.5, 0.5, 0.5, 0.5]
        gc = PdfPlotGraphicsContext(filename=filename, pdf_canvas=canvas)
        pc = self.plotcontainer

        #pc.do_layout(force=True)
        # pc.use_backbuffer=False
        gc.render_component(pc, valign='center')
        if save:
            gc.save()
            # pc.use_backbuffer=True

        return gc
Exemplo n.º 2
0
    def save(self):
        root = paths.corrections_dir
        base = self.stage_map_name
        p = unique_date_path(root, base, extension='')
        gp = '{}.{}'.format(p, 'pdf')
        gc = PdfPlotGraphicsContext(filename=gp,
                                    pagesize='letter')

        from reportlab.lib.pagesizes import letter
        bounds = self.canvas.bounds
        self.canvas.do_layout(size=letter, force=True)

        gc.render_component(self.canvas, valign='center')
        gc.save(p)
        self.canvas.do_layout(size=bounds, force=True)
        self.canvas.invalidate_and_redraw()

        tp = '{}.{}'.format(p, 'txt')
        with open(tp, 'w') as wfile:
            for r in self.results:
                args = r.nx, r.ny, r.dx, r.dy
                args = map(lambda x: '{:0.5f}'.format(x), args)
                args = [r.hole_id, str(r.corrected)] + args
                line = ','.join(args)
                wfile.write('{}\n'.format(line))
Exemplo n.º 3
0
    def save_file(self, path, force_layout=True):
        _, tail = os.path.splitext(path)
        if tail not in ('.pdf', '.png'):
            path = '{}.pdf'.format(path)

        c = self.component
        '''
            chaco becomes less responsive after saving if 
            use_backbuffer is false and using pdf 
        '''
        c.do_layout(size=letter, force=force_layout)

        _, tail = os.path.splitext(path)
        if tail == '.pdf':
            from chaco.pdf_graphics_context import PdfPlotGraphicsContext

            gc = PdfPlotGraphicsContext(filename=path)
            gc.render_component(c, valign='center')
            gc.save()

        else:
            from chaco.plot_graphics_context import PlotGraphicsContext

            gc = PlotGraphicsContext((int(c.outer_width), int(c.outer_height)))
            gc.render_component(c)
            gc.save(path)

        self.rebuild_graph()
Exemplo n.º 4
0
 def _save_pdf(self):
     from chaco.pdf_graphics_context import PdfPlotGraphicsContext
     gc = PdfPlotGraphicsContext(filename=self.filename,
             pagesize = self.pagesize,
             dest_box = self.dest_box,
             dest_box_units = self.dest_box_units)
     gc.render_component(self.component)
     gc.save()
Exemplo n.º 5
0
    def draw(self):
        if self.component:
            gc = PdfPlotGraphicsContext(pdf_canvas=self.canv)

            #             print self.component.x, self.component.y
            scale = self._scale
            gc.scale_ctm(scale, scale)
            gc.translate_ctm(-self.component.x, -self.component.y)
            self.component.draw(gc)
Exemplo n.º 6
0
def draw_pdf(filename, size=(800, 600)):
    from chaco.pdf_graphics_context import PdfPlotGraphicsContext
    container = create_plot()
    container.bounds = list(size)
    container.do_layout(force=True)
    gc = PdfPlotGraphicsContext(filename=filename,
                                dest_box=(0.5, 0.5, 5.0, 5.0))
    gc.render_component(container)
    gc.save()
Exemplo n.º 7
0
def save(filename="chacoplot.png",
         dpi=72,
         pagesize="letter",
         dest_box=None,
         units="inch"):
    """ Saves the active plot to an file.  Currently supported file types
    are: bmp, png, jpg.
    """
    p = curplot()
    if not p:
        print("Doing nothing because there is no active plot.")
        return

    import os.path
    ext = os.path.splitext(filename)[-1]
    if ext == ".pdf":
        print("Warning: the PDF backend is still a little buggy.")
        from chaco.pdf_graphics_context import PdfPlotGraphicsContext
        # Set some default PDF options if none are provided
        if dest_box is None:
            dest_box = (0.5, 0.5, -0.5, -0.5)
        gc = PdfPlotGraphicsContext(
            filename=filename,
            pagesize=pagesize,
            dest_box=dest_box,
            dest_box_units=units)

        # temporarily turn off the backbuffer for offscreen rendering
        use_backbuffer = p.use_backbuffer
        p.use_backbuffer = False
        gc.render_component(p)
        p.use_backbuffer = use_backbuffer

        gc.save()
        del gc
        print("Saved to", filename)

    elif ext in [".bmp", ".png", ".jpg"]:
        from chaco.api import PlotGraphicsContext
        gc = PlotGraphicsContext(tuple(p.outer_bounds), dpi=dpi)

        # temporarily turn off the backbuffer for offscreen rendering
        use_backbuffer = p.use_backbuffer
        p.use_backbuffer = False
        gc.render_component(p)
        p.use_backbuffer = use_backbuffer

        gc.save(filename)
        del gc
        print("Saved to", filename)
    else:
        print("Format not yet supported:", ext)
        print("Currently supported formats are: bmp, png, jpg.")
    return
Exemplo n.º 8
0
 def save_pdf(self, filename):
     """
     Saves an image of a chaco component (e.g. 'Plot' or 'Container')
     to a .pdf file.
     """
     from chaco.pdf_graphics_context import PdfPlotGraphicsContext
     gc = PdfPlotGraphicsContext(filename=filename)
     #pagesize = self.pagesize,
     #dest_box = self.dest_box,
     #dest_box_units = self.dest_box_units)
     gc.render_component(self)
     gc.save()
Exemplo n.º 9
0
    def render_pdf(self, obj, path):
        from chaco.pdf_graphics_context import PdfPlotGraphicsContext

        if not path.endswith('.pdf'):
            path += '.pdf'
        gc = PdfPlotGraphicsContext(filename=path)
#        opad = obj.padding_bottom
#        obj.padding_bottom = 60
        obj.do_layout(force=True)
        gc.render_component(obj, valign='center')

        gc.gc.drawString(600, 5, 'area:{:0.3f}% low={} high={}'.format(self.area, self.low, self.high))

        gc.save()
Exemplo n.º 10
0
    def do_save(self):
        dlg = FileDialog(action='save as')
        if dlg.open() == OK:
            path = dlg.path

        if not path.endswith('.pdf'):
            path += '.pdf'

        gc = PdfPlotGraphicsContext(filename=path)
        pc = self.highlighter.container

        gc.render_component(pc, valign='center')
        gc.save()

        return gc
Exemplo n.º 11
0
    def save_pdf_figure(self):
        if self.active_editor:

            from chaco.pdf_graphics_context import PdfPlotGraphicsContext

            p = self.save_file_dialog(ext='.pdf')
            if p:
                gc = PdfPlotGraphicsContext(filename=p)
                #pc.do_layout(force=True)
                # pc.use_backbuffer=False
                comp = self.active_editor.component
                if not issubclass(type(comp), Component):
                    comp = comp.plotcontainer
                gc.render_component(comp, valign='center')
                gc.save()
Exemplo n.º 12
0
def draw_pdf(filename, size=(800, 600)):
    from chaco.pdf_graphics_context import PdfPlotGraphicsContext
    container = create_plot()
    container.outer_bounds = list(size)
    container.do_layout(force=True)
    gc = PdfPlotGraphicsContext(filename=filename,
                                dest_box=(0.5, 0.5, 5.0, 5.0))

    for i in range(2):
        # draw the plot
        gc.render_component(container)

        #Start a new page for subsequent draw commands.
        gc.add_page()

    gc.save()
Exemplo n.º 13
0
    def save(self, path=None):
        #        print self.container.bounds

        if path is None:
            dlg = FileDialog(action='save as',
                             default_directory=paths.data_dir)
            if dlg.open() == OK:
                path = dlg.path

        if path is not None:
            _, tail = os.path.splitext(path)
            c = self.container
            if tail == '.pdf':
                from chaco.pdf_graphics_context import PdfPlotGraphicsContext

                gc = PdfPlotGraphicsContext(filename=path, pagesize='letter')

            else:
                if not tail in ('.png', '.jpg', '.tiff'):
                    path = '{}.png'.format(path)

                gc = PlotGraphicsContext(
                    (int(c.outer_width), int(c.outer_height)))
                #            c.use_backbuffer = False

            # for ci in c.components:
            #     try:
            #         ci.x_axis.visible = False
            #         ci.y_axis.visible = False
            #     except Exception:
            #         pass

            # c.use_backbuffer = False

            gc.render_component(c)
            #            c.use_backbuffer = True
            gc.save(path)
            self._name = os.path.basename(path)
Exemplo n.º 14
0
def export_plot_pdf(parent):
    dlg = wx.FileDialog(parent, "Export plot as PDF",
                        parent.config.get_path("PDF"), "",
                        "PDF file" + " (*.pdf)|*.pdf",
                        wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
    if dlg.ShowModal() == wx.ID_OK:
        path = dlg.GetPath().encode("utf-8")
        if not path.endswith(".pdf"):
            path += ".pdf"
        parent.config.set_path(os.path.dirname(path), "PDF")
        container = parent.PlotArea.mainplot.container

        retol = hide_scatter_inspector(container)

        #old_height = container.height
        #old_width = container.width

        #a4_factor = 297/210
        ## Segmentation-faults:
        #from chaco.api import PlotGraphicsContext
        #gc = PlotGraphicsContext((int(container.outer_width), int(container.outer_height)))
        #container.draw(gc, mode="normal")
        #gc.save(path)

        #container.auto_size=True
        #container.auto_center=True

        # get inner_boundary
        (bx, by) = container.outer_bounds

        #(x, y) = (bx, by) = container.outer_bounds
        #x2 = 0,
        #y2 = 0
        #for c in container.components:
        #    x = min(c.x, x)
        #    y = min(c.y, y)
        #    x2 = max(c.x2, x2)
        #    y2 = max(c.y2, y2)
        #container.set_outer_bounds(0, (x2-x))
        #container.set_outer_bounds(1, (y2-y))

        # Correction factor 0.9 wih size of plots yields
        # approximately the right size for all kinds of container
        # shapes.
        container.set_outer_bounds(0, (300) * container.shape[1]**.9)
        container.set_outer_bounds(1, (300) * container.shape[0]**.9)

        # scatter plot classes
        class_sp = (chaco.colormapped_scatterplot.ColormappedScatterPlot,
                    chaco.scatterplot.ScatterPlot)

        for c in container.components:
            for comp in c.components:
                if isinstance(comp, class_sp):
                    comp.marker_size /= 2

        dest_box = (.01, .01, -.01, -.01)
        try:
            gc = PdfPlotGraphicsContext(filename=path,
                                        dest_box=dest_box,
                                        pagesize="landscape_A4")
        except KeyError:
            warnings.warn("'landscape_A4' not defined for pdf "+\
                          "export. Please update `chaco`.")
            gc = PdfPlotGraphicsContext(filename=path,
                                        dest_box=dest_box,
                                        pagesize="A4")
        # draw the plot
        gc.render_component(container, halign="center", valign="top")
        #Start a new page for subsequent draw commands.
        gc.save()
        container.set_outer_bounds(0, bx)
        container.set_outer_bounds(1, by)

        for c in container.components:
            for comp in c.components:
                if isinstance(comp, class_sp):
                    comp.marker_size *= 2

        #container.height = old_height
        #container.width = old_width
        #container.auto_size = True
        #container.auto_size = False

        ## TODO:
        ## Put this into a differnt function in PlotArea
        ## -> call it after each plot?

        ## Solves font Error after saving PDF:
        # /usr/lib/python2.7/dist-packages/kiva/fonttools/font_manag
        # er.py:1303: UserWarning: findfont: Could not match
        # (['Bitstream Vera Sans'], 'normal', None, 'normal', 500,
        # 12.0). Returning /usr/share/fonts/truetype/lato/
        # Lato-Hairline.ttf UserWarning)
        for aplot in container.plot_components:
            for item in aplot.overlays:
                if isinstance(item, chaco.plot_label.PlotLabel):
                    item.font = "modern 12"
                elif isinstance(item, chaco.legend.Legend):
                    item.font = "modern 10"
                elif isinstance(item, chaco.axis.PlotAxis):
                    item.title_font = "modern 12"
                    item.tick_label_font = "modern 10"
                elif isinstance(item, chaco.data_label.DataLabel):
                    item.font = "modern 9"
                else:
                    warnings.warn("Not resetting plot fonts for"+\
                                  "plot component class {}.".format(
                                  item.__class__))

        if retol is not None:
            retol.visible = True
Exemplo n.º 15
0
    def make_strat_canvas_file(self):
        identifiers = [
            '57735', '57742', '57734', '57737', '57736', '57744', '57743',
            '57725', '58627'
        ]
        identifiers = ['57731', '58612', '58620']
        identifiers = ['58616', '57719', '58767']
        db = self.db

        root = os.path.join(paths.dissertation, 'data', 'minnabluff',
                            'strat_sequences')
        seqname = 'seq4'
        p, _ = unique_path(root, seqname, extension='.yaml')

        with db.session_ctx():
            items = []
            for i in identifiers:
                strat = {}
                ln = db.get_labnumber(i)
                sample = ln.sample

                ia = ln.selected_interpreted_age.interpreted_age
                if ia.age_kind != 'Integrated':
                    strat['elevation'] = sample.elevation

                    mat = sample.material.name
                    strat['label'] = '{}({}) {}+/-{} ({})'.format(
                        sample.name, mat, ia.age, ia.age_err, ia.age_kind)
                    strat['age'] = ia.age
                    strat['age_err'] = ia.age_err
                    strat['mswd'] = ia.mswd

                    items.append(strat)

            syd = sorted(items, key=lambda x: x['elevation'])
            for i, yi in enumerate(syd[:-1]):
                # print i, yi['elevation'], yi['age']
                # ee2=2*yi['age_err']*yi['mswd']**0.5
                if not strat_ok(yi, syd[i + 1]):
                    yi['color'] = 'red'

        yd = dict(options={}, items=items)

        import yaml

        with open(p, 'w') as wfile:
            yaml.dump(yd, wfile, default_flow_style=False)

        from pychron.canvas.canvas2D.strat_canvas import StratCanvas

        s = StratCanvas()
        s.load_scene(yd)

        p, _ = unique_path(root, seqname, extension='.pdf')
        from chaco.pdf_graphics_context import PdfPlotGraphicsContext

        g = PdfPlotGraphicsContext(filename=p)

        s.do_layout(size=(500, 700), force=True)

        g.render_component(s)
        g.save()