Example usage for org.jfree.chart JFreeChart draw

List of usage examples for org.jfree.chart JFreeChart draw

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart draw.

Prototype

public void draw(Graphics2D g2, Rectangle2D area, ChartRenderingInfo info) 

Source Link

Document

Draws the chart on a Java 2D graphics device (such as the screen or a printer).

Usage

From source file:de.atomfrede.tools.evalutation.tools.plot.util.PlotUtil.java

public static void saveChartAsSVG(File file, JFreeChart chart, int width, int height) throws Exception {
    Writer out = null;/*from  ww w.  ja  v  a 2 s  .  com*/
    try {
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

        String svgNS = "http://www.w3.org/2000/svg";
        org.w3c.dom.Document document = domImpl.createDocument(svgNS, "svg", null);

        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        svgGenerator.getGeneratorContext().setPrecision(6);

        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);

        boolean useCSS = true;
        out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);

    } catch (UnsupportedEncodingException enc) {
        log.error(enc);
    } catch (FileNotFoundException fnf) {
        log.error(fnf);
    } catch (SVGGraphics2DIOException e) {
        log.error(e);
    } catch (DOMException dome) {
        log.error(dome);
    } finally {
        if (out != null)
            out.close();
    }

}

From source file:net.bioclipse.model.ImageWriter.java

/**
 * Save image to svg format//from   w  w w.j  a  v  a2s.  com
 * @param path the path including filename where the image is to be stored
 * @param chart TODO
 */
public static void saveImageSVG(String path, JFreeChart chart) {
    //First check that we have a valid chart
    if (chart != null) {
        //Create DOM objects
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument(null, "svg", null);

        //Create an instance of the SVG generator
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

        //Setting the precision apparently avoids a NullPointerException in Batik 1.5
        svgGenerator.getGeneratorContext().setPrecision(6);

        //Render chart into SVG Graphics2D impl.
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, 400, 300), null);

        //Write to file
        boolean useCSS = true;
        try {
            Writer out = new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8");
            svgGenerator.stream(out, useCSS);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SVGGraphics2DIOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.encog.workbench.util.graph.DocumentSVG.java

public static void saveSVG(File filename, JFreeChart chart, int width, int height) {
    try {// w ww. j a  va2  s  . c o  m
        // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION...
        // Get a DOMImplementation
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
        // Create an instance of org.w3c.dom.Document
        Document document = domImpl.createDocument(null, "svg", null);
        // Create an instance of the SVG Generator
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        // set the precision to avoid a null pointer exception in Batik 1.5
        svgGenerator.getGeneratorContext().setPrecision(6);
        // Ask the chart to render into the SVG Graphics2D implementation
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);
        // Finally, stream out SVG to a file using UTF-8 character to
        // byte encoding
        boolean useCSS = true;
        Writer out = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8");
        svgGenerator.stream(out, useCSS);
    } catch (IOException ex) {
        throw new WorkBenchError(ex);
    }
}

From source file:de.laures.cewolf.util.Renderer.java

/**
 * Handles rendering a chart as a SVG. Currently this method is synchronized
 * because of concurrency issues with JFreeChart.
 *
 * @param  baos//w  w w .ja  va2  s. com
 * @param  chart
 * @param  width
 * @param  height
 * @throws IOException
 */
private static synchronized void handleSVG(ByteArrayOutputStream baos, JFreeChart chart, int width, int height)
        throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument("cewolf-svg", "svg", null);
    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
    ctx.setComment("Generated by Cewolf using JFreeChart and Apache Batik SVG Generator");
    SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, false);
    svgGenerator.setSVGCanvasSize(new Dimension(width, height));
    chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);
    svgGenerator.stream(writer, false);
    writer.close();
}

From source file:net.sf.jasperreports.charts.util.ChartUtil.java

/**
 * /*from w  w w . j  a v  a  2  s .c o m*/
 */
public static List<JRPrintImageAreaHyperlink> getImageAreaHyperlinks(JFreeChart chart,
        ChartHyperlinkProvider chartHyperlinkProvider, Graphics2D grx, Rectangle2D renderingArea)// throws JRException
{
    List<JRPrintImageAreaHyperlink> areaHyperlinks = null;

    if (chartHyperlinkProvider != null && chartHyperlinkProvider.hasHyperlinks()) {
        ChartRenderingInfo renderingInfo = new ChartRenderingInfo();

        if (grx == null) {
            chart.createBufferedImage((int) renderingArea.getWidth(), (int) renderingArea.getHeight(),
                    renderingInfo);
        } else {
            chart.draw(grx, renderingArea, renderingInfo);
        }

        EntityCollection entityCollection = renderingInfo.getEntityCollection();
        if (entityCollection != null && entityCollection.getEntityCount() > 0) {
            areaHyperlinks = new ArrayList<JRPrintImageAreaHyperlink>(entityCollection.getEntityCount());

            for (@SuppressWarnings("unchecked")
            Iterator<ChartEntity> it = entityCollection.iterator(); it.hasNext();) {
                ChartEntity entity = it.next();
                JRPrintHyperlink printHyperlink = chartHyperlinkProvider.getEntityHyperlink(entity);
                if (printHyperlink != null) {
                    JRPrintImageArea area = getImageArea(entity);

                    JRPrintImageAreaHyperlink areaHyperlink = new JRPrintImageAreaHyperlink();
                    areaHyperlink.setArea(area);
                    areaHyperlink.setHyperlink(printHyperlink);
                    areaHyperlinks.add(areaHyperlink);
                }
            }
        }
    }

    return areaHyperlinks;
}

From source file:net.sf.mzmine.chartbasics.graphicsexport.ChartExportUtil.java

/**
 * Paints a chart with scaling options/*from  w w  w. ja  v a 2  s  . c o m*/
 * 
 * @param chart
 * @param info
 * @param out
 * @param width
 * @param height
 * @param resolution
 * @return BufferedImage of a given chart with scaling to resolution
 * @throws IOException
 */
private static BufferedImage paintScaledChartToBufferedImage(JFreeChart chart, ChartRenderingInfo info,
        OutputStream out, int width, int height, int resolution, int bufferedIType) throws IOException {
    Args.nullNotPermitted(out, "out");
    Args.nullNotPermitted(chart, "chart");

    double scaleX = resolution / 72.0;
    double scaleY = resolution / 72.0;

    double desiredWidth = width * scaleX;
    double desiredHeight = height * scaleY;
    double defaultWidth = width;
    double defaultHeight = height;
    boolean scale = false;

    // get desired width and height from somewhere then...
    if ((scaleX != 1) || (scaleY != 1)) {
        scale = true;
    }

    BufferedImage image = new BufferedImage((int) desiredWidth, (int) desiredHeight, bufferedIType);
    Graphics2D g2 = image.createGraphics();

    if (scale) {
        AffineTransform saved = g2.getTransform();
        g2.transform(AffineTransform.getScaleInstance(scaleX, scaleY));
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
        g2.setTransform(saved);
        g2.dispose();
    } else {
        chart.draw(g2, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight), info);
    }
    return image;
}

From source file:eu.planets_project.tb.impl.chart.ExperimentChartServlet.java

public static void writeChartAsSVG(OutputStream outstream, JFreeChart chart, int width, int height)
        throws UnsupportedEncodingException, SVGGraphics2DIOException {

    Writer out = new OutputStreamWriter(outstream, "UTF-8");

    // THE FOLLOWING CODE BASED ON THE EXAMPLE IN THE BATIK DOCUMENTATION...
    // Get a DOMImplementation
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document
    Document document = domImpl.createDocument(null, "svg", null);

    // Create an instance of the SVG Generator
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    // set the precision to avoid a null pointer exception in Batik 1.5
    svgGenerator.getGeneratorContext().setPrecision(3);

    // Other opts:
    svgGenerator.getGeneratorContext().setEmbeddedFontsOn(true);
    //        svgGenerator.setFont( new Font("SansSerif", Font.PLAIN, 8) );

    // Ask the chart to render into the SVG Graphics2D implementation
    chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height), null);

    // Finally, stream out SVG to a file using UTF-8 character to
    // byte encoding
    boolean useCSS = true;

    svgGenerator.stream(out, useCSS);//from  ww  w .  j  a  v  a 2  s  .co m

}

From source file:ca.sqlpower.wabit.report.ChartRenderer.java

public boolean renderReportContent(Graphics2D g, double width, double height, double scaleFactor, int pageIndex,
        boolean printing, SPVariableResolver variablesContext) {

    if (printing) {
        // If we're printing a streaming query, we have to
        // print whatever's displayed.
        if (this.chartCache == null || (this.chartCache != null && !this.chartCache.getQuery().isStreaming())) {
            refresh(false);/* w  ww .j  a  va2 s .c  o m*/
        }
    } else if (needsRefresh || this.chartCache == null) {
        // No chart loaded. Doing a refresh will trigger a new 
        // redraw later on.
        refresh();
        return false;
    }

    JFreeChart jFreeChart = null;
    try {
        jFreeChart = ChartSwingUtil.createChartFromQuery(chartCache);
        if (jFreeChart == null) {
            g.drawString("Loading...", 0, g.getFontMetrics().getHeight());
            return false;
        }

        Rectangle2D area = new Rectangle2D.Double(0, 0, width, height);

        // first pass establishes rendering info but draws nothing
        ChartRenderingInfo info = new ChartRenderingInfo();
        Graphics2D dummyGraphics = (Graphics2D) g.create(0, 0, 0, 0);
        jFreeChart.draw(dummyGraphics, area, info);
        dummyGraphics.dispose();

        // now for real
        Rectangle2D plotArea = info.getPlotInfo().getDataArea();
        ChartGradientPainter.paintChartGradient(g, area, (int) plotArea.getMaxY());
        jFreeChart.draw(g, area);

    } catch (Exception e) {
        logger.error("Error while rendering chart", e);
        g.drawString("Could not render chart: " + e.getMessage(), 0, g.getFontMetrics().getHeight());
    }
    return false;
}

From source file:com.datamyne.charts.AlmostThereDemo.java

/**
 * Creates PDf file.//from w  w  w  .  j  av a 2 s  .c o m
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this
        //add the PdfTemplate to the PdfContentByte
        contentByte.addTemplate(template, 0, 300);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.FinallyDemo.java

/**
 * Creates PDf file.//ww  w . java2s  .co m
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //get dummy text
        String text = getText();
        //create text font
        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFamily.TIMES_ROMAN, 10.0f);

        //add text before
        document.add(new Paragraph(new Chunk(text, font)));

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this

        //create Image from PdfTemplate
        Image image = Image.getInstance(template);
        document.add(image);

        //add text after
        document.add(new Paragraph(new Chunk(text, font)));

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}