PDFGraph.java [src/java/reports] Revision: default  Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reports;

import java.io.File;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 * Create a graph that later can be linked into the HTML template which then will get inserted in
 * the PDF.
 *
 * @author Yuanyuan.Ji
 */
public class PDFGraph {

  /**
   * generate JPEG graph image by data for X axis and data for Y axis.
   *
   * @param Xdata : data for X axis.
   * @param Ydata : data for Y axis.
   * @param imagePath : the output image generated by this function.
   * @param title : the title of the graph.
   * @throws IOException error writing image to file
   */
  public static void generateJPEGByXY(double[] Xdata, double[] Ydata, String imagePath, String title) throws IOException {
    // create dataset
    XYSeries series1 = new XYSeries(title);

    for (int i = 0; i < Xdata.length && i < Ydata.length; i++) {
      series1.add(Xdata[i], Ydata[i]);
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series1);

    // create the chart
    JFreeChart chart = ChartFactory.createXYLineChart(
            title, // chart title
            "Distance(ft)", // x axis label
            title, // y axis label
            dataset, // data
            PlotOrientation.VERTICAL,
            true, // include legend
            true, // tooltips
            false // urls
    );

    int width = 400;
    /* Width of the image */  // If we want zoom in (curent unit/2), we can increase width to 500. But increase width to 400 will not zoom in.
    int height = 300;
    /* Height of the image */
    File lineChart = new File(imagePath);
    ChartUtils.saveChartAsJPEG(lineChart, chart, width, height);
  }
}