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

@Override
public void draw(Graphics2D g2, Rectangle2D area) 

Source Link

Document

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

Usage

From source file:edu.fullerton.viewerplugin.PluginSupport.java

public void saveImageAsPdfFile(JFreeChart chart, String filename) throws WebUtilException {
    try {//from   w w w  . j  a v  a2 s  . com
        OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
        Rectangle pagesize = new Rectangle(width, height);
        com.itextpdf.text.Document document;
        document = new com.itextpdf.text.Document(pagesize, 50, 50, 50, 50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            FontMapper mapper = new DefaultFontMapper();
            document.addAuthor("JFreeChart");
            document.addSubject("Demonstration");
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, mapper);
            Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
            chart.draw(g2, r2D);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            throw new WebUtilException("Saving as pdf", de);
        }
        document.close();
    } catch (FileNotFoundException ex) {
        throw new WebUtilException("Saving plot as pdf: ", ex);
    }

}

From source file:SciTK.Plot.java

/**
 * Exports a JFreeChart to a PS file using Adobe XML graphics library.
 * // ww w  . j  a  va2 s. c o m
 * @param chart JFreeChart to export
 * @param bounds the dimensions of the viewport
 * @param psFile the output file.
 * @param mode the file write mode ("ps","eps")
 * @throws IOException if writing the file fails.
 */
protected void exportChartAsPS(JFreeChart chart, Rectangle bounds, File psFile, String mode)
        throws IOException {
    // see http://xmlgraphics.apache.org/commons/postscript.html#creating-eps

    // set up file:
    OutputStream outputStream = new FileOutputStream(psFile);

    AbstractPSDocumentGraphics2D g2d;
    if (mode == "ps")
        g2d = new PSDocumentGraphics2D(false);
    else
        g2d = new EPSDocumentGraphics2D(false);

    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    //Set up the document size
    g2d.setupDocument(outputStream, (int) bounds.getWidth(), (int) bounds.getHeight());
    //out is the OutputStream to write the EPS to

    // draw the chart to g2d:
    chart.draw(g2d, bounds);

    // write and close file:    
    g2d.finish(); //Wrap up and finalize the EPS file
    outputStream.flush();
    outputStream.close();
}

From source file:keel.Algorithms.UnsupervisedLearning.AssociationRules.Visualization.keelassotiationrulesbarchart.ResultsProccessor.java

public void writeToFile(String outName)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    calcMeans();//  ww  w.  ja va2 s .  com
    calcAvgRulesBySeed();

    // Create JFreeChart Dataset
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    HashMap<String, Double> measuresFirst = algorithmMeasures.entrySet().iterator().next().getValue();
    for (Map.Entry<String, Double> measure : measuresFirst.entrySet()) {
        String measureName = measure.getKey();
        //Double measureValue = measure.getValue();
        dataset.clear();

        for (Map.Entry<String, HashMap<String, Double>> entry : algorithmMeasures.entrySet()) {
            String alg = entry.getKey();
            Double measureValue = entry.getValue().get(measureName);

            // Parse algorithm name to show it correctly
            String aName = alg.substring(0, alg.length() - 1);
            int startAlgName = aName.lastIndexOf("/");
            aName = aName.substring(startAlgName + 1);

            dataset.addValue(measureValue, aName, measureName);

            ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
            JFreeChart barChart = ChartFactory.createBarChart("Assotiation Rules Measures", measureName,
                    measureName, dataset, PlotOrientation.VERTICAL, true, true, false);
            StandardChartTheme.createLegacyTheme().apply(barChart);

            CategoryItemRenderer renderer = barChart.getCategoryPlot().getRenderer();

            // Black and White
            int numItems = algorithmMeasures.size();
            for (int i = 0; i < numItems; i++) {
                Color color = Color.DARK_GRAY;
                if (i % 2 == 1) {
                    color = Color.LIGHT_GRAY;
                }
                renderer.setSeriesPaint(i, color);
                renderer.setSeriesOutlinePaint(i, Color.BLACK);
            }

            int width = 640 * 2; /* Width of the image */
            int height = 480 * 2; /* Height of the image */

            // JPEG
            File BarChart = new File(outName + "_" + measureName + "_barchart.jpg");
            ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);

            // SVG
            SVGGraphics2D g2 = new SVGGraphics2D(width, height);
            Rectangle r = new Rectangle(0, 0, width, height);
            barChart.draw(g2, r);
            File BarChartSVG = new File(outName + "_" + measureName + "_barchart.svg");
            SVGUtils.writeToSVG(BarChartSVG, g2.getSVGElement());
        }
    }
    /*
    for (Map.Entry<String, HashMap<String, Double>> entry : algorithmMeasures.entrySet())
    {
    String alg = entry.getKey();
    HashMap<String, Double> measures = entry.getValue();
            
    for (Map.Entry<String, Double> entry1 : measures.entrySet())
    {
        String measureName = entry1.getKey();
        Double measureValue = entry1.getValue();
                
        dataset.addValue(measureValue, alg, measureName);
    }
    }
        */

}

From source file:cs.cirg.cida.CIDAView.java

@Action
public void savePlotEPS() {
    JFreeChart chartToSave = ((ChartPanel) chartPanel).getChart();
    String name = chartToSave.getTitle().getText();
    name = name.trim().replaceAll(" ", "");
    try {/*from  www.jav  a2s. co m*/
        OutputStream out = new FileOutputStream(name + CIDAConstants.EXT_EPS);
        EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
        g2d.setGraphicContext(new GraphicContext());

        g2d.setupDocument(out, CIDAConstants.DEFAULT_CHART_HORIZONTAL_RES,
                CIDAConstants.DEFAULT_CHART_VERTICAL_RES);
        chartToSave.draw(g2d, new Rectangle2D.Double(0, 0, CIDAConstants.DEFAULT_CHART_HORIZONTAL_RES,
                CIDAConstants.DEFAULT_CHART_VERTICAL_RES));

        g2d.finish();
    } catch (IOException ex) {
        CIDAPromptDialog dialog = exceptionController.handleException(this.getFrame(), ex,
                CIDAConstants.DIALOG_NEW_NAME_MSG);
        dialog.displayPrompt();
    }
}

From source file:ec.display.chart.StatisticsChartPaneTab.java

/**
 * This method initializes jButton  //from  w w w . ja va  2 s . com
 *  
 * @return javax.swing.JButton      
 */
private JButton getPrintButton() {
    if (printButton == null) {
        printButton = new JButton();
        printButton.setText("Export to PDF...");
        final JFreeChart chart = chartPane.getChart();
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try

                {
                    int width = chartPane.getWidth();
                    int height = chartPane.getHeight();

                    FileDialog fileDialog = new FileDialog(new Frame(), "Export...", FileDialog.SAVE);
                    fileDialog.setDirectory(System.getProperty("user.dir"));
                    fileDialog.setFile("*.pdf");
                    fileDialog.setVisible(true);
                    String fileName = fileDialog.getFile();
                    if (fileName != null)

                    {
                        if (!fileName.endsWith(".pdf")) {
                            fileName = fileName + ".pdf";
                        }
                        File f = new File(fileDialog.getDirectory(), fileName);
                        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
                        document.addAuthor("ECJ Console");
                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(width, height);
                        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
                        chart.draw(g2, rectangle2D);
                        g2.dispose();
                        cb.addTemplate(tp, 0, 0);
                        document.close();
                    }
                } catch (Exception ex)

                {
                    ex.printStackTrace();
                }
            }
        });
    }
    return printButton;
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Export jfreechart to image format. File must have an extension like jpg,
 * png, pdf, svg, eps. Otherwise export will fail.
 *
 * @param file Destination Filedescriptor
 * @param chart JFreechart//from ww  w.ja va 2s  .  c  om
 * @throws Exception
 */
public boolean export(File file, JFreeChart chart) throws Exception {

    /*Get extension from file - File must have one extension of
     jpg,png,pdf,svg,eps. Otherwise the export will fail.
     */
    String ext = JFUtils.getExtension(file);

    //  TODO - Make x,y variable
    int x, y;
    // Set size for image (jpg)
    x = 550;
    y = 470;

    int found = 0;

    // JPEG
    if (ext.equalsIgnoreCase("jpg")) {
        ChartUtilities.saveChartAsJPEG(file, chart, x, y);
        found++;
    }
    // PNG
    if (ext.equalsIgnoreCase("png")) {
        ChartUtilities.saveChartAsPNG(file, chart, x, y);
        found++;
    }

    // PDF
    if (ext.equalsIgnoreCase("pdf")) {

        //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart);
        // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !)
        Rectangle pagesize = new Rectangle(x, y);

        Document document = new Document(pagesize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(x, y);

        Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());

        // Draw doesn't works with Rectangle argument - use rectangle2D instead !
        //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y));
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y);
        chart.draw(g2, r2d2);

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();

        found++;

    }

    // SVG
    if (ext.equalsIgnoreCase("svg")) {
        // When exporting to SVG don't forget this VERY important line:
        // svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz
        // Get a DOMImplementation
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        //chart.draw(svgGenerator,new Rectangle(x,y));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y));

        boolean useCSS = true; // we want to use CSS style attribute

        Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
        found++;
    }

    if (ext.equalsIgnoreCase("eps")) {

        //Graphics2D g = new EpsGraphics2D();
        FileOutputStream out = new FileOutputStream(file);
        //Writer out=new FileWriter(file);
        Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB);

        chart.draw(g, new Rectangle2D.Double(0, 0, x, y));
        //Writer out=new FileWriter(file);
        out.write(g.toString().getBytes());
        out.close();
        found++;
    }

    if (found == 0) {
        throw new IllegalArgumentException("File format '" + ext + "' not supported!");
    }

    return true;

}

From source file:cis_690_report.DynamicReporter.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed

    // TODO add your handling code here:
    // build a controller
    SwingController controller = new SwingController();

    // Build a SwingViewFactory configured with the controller
    SwingViewBuilder factory = new SwingViewBuilder(controller);

    // Use the factory to build a JPanel that is pre-configured
    //with a complete, active Viewer UI.
    JPanel viewerComponentPanel = factory.buildViewerPanel();

    // add copy keyboard command
    ComponentKeyBinding.install(controller, viewerComponentPanel);

    // add interactive mouse link annotation support via callback
    controller.getDocumentViewController().setAnnotationCallback(
            new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController()));

    // Create a JFrame to display the panel in
    JFrame window = new JFrame("Using the Viewer Component");
    window.getContentPane().add(viewerComponentPanel);
    window.pack();//from w w w .  j a va  2s .  co m
    window.setVisible(true);

    String Path;
    Path = "C:/Users/Shubh Chopra/Documents/reporter.pdf";

    try {
        br1 = new BufferedReader(new FileReader(f));
        BufferedReader b1 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {

    }

    String line = "";

    bull1 = new String[number_of_rows - 1][];
    int k = 0;
    BufferedReader br3 = null;
    try {
        br3 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {
    }
    try {
        while ((line = br3.readLine()) != null) {

            // use comma as separator
            String Bull[] = line.split(",");
            if (k != 0) {
                System.out.println(Bull.length);
                bull1[k - 1] = new String[Bull.length];
                for (int j = 0; j < Bull.length; j++) {

                    bull1[k - 1][j] = Bull[j];

                }
            }
            k++;
        }
    } catch (IOException ex) {
    }
    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
        Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

        //file path

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path));

        //document header attributes
        doc.addAuthor("Shubh Chopra");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("Shubh Chopra");
        doc.addTitle("BES");
        doc.setPageSize(PageSize.LETTER.rotate());

        //open document
        doc.open();
        //create a paragraph
        Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
        paragraph.setFont(bfBold20);
        paragraph.setAlignment(Element.ALIGN_CENTER);

        Image img = Image.getInstance("VETMED.png");

        img.scaleToFit(300f, 150f);
        doc.add(paragraph);
        PdfPTable table1 = new PdfPTable(2);
        table1.setWidthPercentage(100);
        PdfPCell cell = new PdfPCell(img);
        cell.setBorder(PdfPCell.NO_BORDER);
        table1.addCell(cell);

        String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";

        table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
        doc.add(table1);

        //specify column widths
        int temp = dlm2.size();

        float[] columnWidths = new float[temp];
        for (int x = 0; x < columnWidths.length; x++) {
            columnWidths[x] = 2f;
        }

        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(90f);
        DynamicReporter re;
        re = new DynamicReporter();

        for (int i = 0; i < dlm2.size(); i++) {
            String[] parts = dlm2.get(i).toString().split(": ");
            String part2 = parts[1];

            re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
        }

        table.setHeaderRows(1);
        //insert an empty row

        //create section heading by cell merging

        //just some random data to fill 

        for (int x = 0; x < dlm3.size(); x++) {
            String str = dlm3.get(x).toString();

            System.out.println(str);
            String[] parts = str.split(":");

            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            for (int i = 0; i < dlm2.getSize(); i++)
                for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                    String str1 = dlm2.get(i).toString();
                    String[] p1 = str1.split(": ");
                    String p2 = p1[0];
                    if (p2.equals(header[j])) {
                        re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                    }
                }
            // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
        }

        doc.add(table);
        if (jCheckBox2.isSelected()) {
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            for (int i = 0; i < dlm3.size(); i++) {

                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }

            }
            JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                    "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

            if (dlm3.size() > 12) {
                doc.newPage();
            }
            PdfContentByte contentByte = docWriter.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(325, 250);
            PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

            chart.draw(graphics2d, rectangle2d);

            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        }
        if (jCheckBox1.isSelected()) {

            for (int i = 0; i < dlm3.size(); i++) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }
                JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                        "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);

                doc.newPage();
            }
        }

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (doc != null) {
            //close the document
            doc.close();
        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

    }
    controller.openDocument(Path);
}

From source file:cis_690_report.DynamicReporter.java

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed

    // TODO add your handling code here:
    // build a controller
    SwingController controller = new SwingController();

    // Build a SwingViewFactory configured with the controller
    SwingViewBuilder factory = new SwingViewBuilder(controller);

    // Use the factory to build a JPanel that is pre-configured
    //with a complete, active Viewer UI.
    JPanel viewerComponentPanel = factory.buildViewerPanel();

    // add copy keyboard command
    ComponentKeyBinding.install(controller, viewerComponentPanel);

    // add interactive mouse link annotation support via callback
    controller.getDocumentViewController().setAnnotationCallback(
            new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController()));

    // Create a JFrame to display the panel in
    JFrame window = new JFrame("Using the Viewer Component");
    window.getContentPane().add(viewerComponentPanel);
    window.pack();//from w w  w .ja  v  a2 s .  c  o m
    window.setVisible(true);

    String Path;
    Path = "C:/Users/Shubh Chopra/Documents/reporter.pdf";

    try {
        br1 = new BufferedReader(new FileReader(f));
        BufferedReader b1 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {

    }

    String line = "";

    bull1 = new String[number_of_rows - 1][];
    int k = 0;
    BufferedReader br3 = null;
    try {
        br3 = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException ex) {
    }
    try {
        while ((line = br3.readLine()) != null) {

            // use comma as separator
            String Bull[] = line.split(",");
            if (k != 0) {
                System.out.println(Bull.length);
                bull1[k - 1] = new String[Bull.length];
                for (int j = 0; j < Bull.length; j++) {

                    bull1[k - 1][j] = Bull[j];

                }
            }
            k++;
        }
    } catch (IOException ex) {
    }
    Document doc = new Document();
    PdfWriter docWriter = null;

    DecimalFormat df = new DecimalFormat("0.00");

    try {

        //special font sizes
        Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
        Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
        Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

        //file path

        docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path));

        //document header attributes
        doc.addAuthor("Shubh Chopra");
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator("Shubh Chopra");
        doc.addTitle("BES");
        doc.setPageSize(PageSize.LETTER.rotate());

        //open document
        doc.open();
        //create a paragraph
        Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
        paragraph.setFont(bfBold20);
        paragraph.setAlignment(Element.ALIGN_CENTER);

        Image img = Image.getInstance("VETMED.png");

        img.scaleToFit(300f, 150f);
        doc.add(paragraph);
        PdfPTable table1 = new PdfPTable(2);
        table1.setWidthPercentage(100);
        PdfPCell cell = new PdfPCell(img);
        cell.setBorder(PdfPCell.NO_BORDER);
        table1.addCell(cell);

        String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";

        table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
        doc.add(table1);

        //specify column widths
        int temp = dlm2.size();

        float[] columnWidths = new float[temp];
        for (int x = 0; x < columnWidths.length; x++) {
            columnWidths[x] = 2f;
        }

        //create PDF table with the given widths
        PdfPTable table = new PdfPTable(columnWidths);
        // set table width a percentage of the page width
        table.setWidthPercentage(90f);
        DynamicReporter re;
        re = new DynamicReporter();

        for (int i = 0; i < dlm2.size(); i++) {
            String[] parts = dlm2.get(i).toString().split(": ");
            String part2 = parts[1];

            re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
        }

        table.setHeaderRows(1);
        //insert an empty row

        //create section heading by cell merging

        //just some random data to fill 

        for (int x = 0; x < dlm3.size(); x++) {
            String str = dlm3.get(x).toString();

            System.out.println(str);
            String[] parts = str.split(":");

            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            for (int i = 0; i < dlm2.getSize(); i++)
                for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                    String str1 = dlm2.get(i).toString();
                    String[] p1 = str1.split(": ");
                    String p2 = p1[0];
                    if (p2.equals(header[j])) {
                        re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                    }
                }
            // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
        }

        doc.add(table);
        if (jCheckBox2.isSelected()) {
            DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
            for (int i = 0; i < dlm3.size(); i++) {

                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }

            }
            JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                    "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

            if (dlm3.size() > 12) {
                doc.newPage();
            }
            PdfContentByte contentByte = docWriter.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(325, 250);
            PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

            chart.draw(graphics2d, rectangle2d);

            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);
        }
        if (jCheckBox1.isSelected()) {

            for (int i = 0; i < dlm3.size(); i++) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                String str = dlm3.get(i).toString();
                System.out.println(str);
                String[] parts = str.split(":");
                String part1 = parts[0];
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                float total = (float) 0.0;
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                    if (bull1[row][j].equals("")) {
                        continue;
                    } else {
                        total += Integer.parseInt(bull1[row][j]);
                    }

                }
                System.out.println(total);
                for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                    if (!bull1[row][j].equals("")) {

                        String[] Parts = header[j].split("_");
                        String Part2 = Parts[1];
                        dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                    } else {
                        dataSet.setValue(0, "Percent", header[j]);

                    }
                }
                JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                        "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);

                doc.newPage();
            }
        }

    } catch (DocumentException dex) {
        dex.printStackTrace();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (doc != null) {
            //close the document
            doc.close();
        }
        if (docWriter != null) {
            //close the writer
            docWriter.close();
        }

    }
    controller.openDocument(Path);
}

From source file:cis_690_report.DynamicReporter.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed

    JFileChooser chooser = new JFileChooser();
    int option = chooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            File3 = chooser.getSelectedFile().getAbsolutePath();
        }/*from   w  w w . j a v a 2s. c om*/

        try {
            br1 = new BufferedReader(new FileReader(f));
            BufferedReader b1 = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {

        }

        String line = "";

        bull1 = new String[number_of_rows - 1][];
        int k = 0;
        BufferedReader br3 = null;
        try {
            br3 = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException ex) {
        }
        try {
            while ((line = br3.readLine()) != null) {

                // use comma as separator
                String Bull[] = line.split(",");
                if (k != 0) {
                    System.out.println(Bull.length);
                    bull1[k - 1] = new String[Bull.length];
                    for (int j = 0; j < Bull.length; j++) {

                        bull1[k - 1][j] = Bull[j];

                    }
                }
                k++;
            }
        } catch (IOException ex) {
        }
        Document doc = new Document();
        PdfWriter docWriter = null;

        DecimalFormat df = new DecimalFormat("0.00");

        try {

            //special font sizes
            Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0));
            Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6);
            Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            Font bfBold25 = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD);
            //file path

            docWriter = PdfWriter.getInstance(doc, new FileOutputStream(File3));

            //document header attributes
            doc.addAuthor("Shubh Chopra");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Shubh Chopra");
            doc.addTitle("BES");
            doc.setPageSize(PageSize.LETTER.rotate());

            //open document
            doc.open();
            //create a paragraph
            Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n");
            paragraph.setFont(bfBold25);
            paragraph.setAlignment(Element.ALIGN_CENTER);

            Image img = Image.getInstance("VETMED.png");

            img.scaleToFit(300f, 150f);
            doc.add(paragraph);
            PdfPTable table1 = new PdfPTable(2);
            table1.setWidthPercentage(100);
            PdfPCell cell = new PdfPCell(img);
            cell.setBorder(PdfPCell.NO_BORDER);
            table1.addCell(cell);

            String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64]
                    + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: "
                    + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n";

            table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT));
            doc.add(table1);

            //specify column widths
            int temp = dlm2.size();

            float[] columnWidths = new float[temp];
            for (int x = 0; x < columnWidths.length; x++) {
                columnWidths[x] = 2f;
            }

            //create PDF table with the given widths
            PdfPTable table = new PdfPTable(columnWidths);
            // set table width a percentage of the page width
            table.setWidthPercentage(90f);
            DynamicReporter re;
            re = new DynamicReporter();

            for (int i = 0; i < dlm2.size(); i++) {
                String[] parts = dlm2.get(i).toString().split(": ");
                String part2 = parts[1];

                re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12);
            }

            table.setHeaderRows(1);
            //insert an empty row

            //create section heading by cell merging

            //just some random data to fill 
            for (int x = 0; x < dlm3.size(); x++) {
                String str = dlm3.get(x).toString();

                System.out.println(str);
                String[] parts = str.split(":");

                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                for (int i = 0; i < dlm2.getSize(); i++)
                    for (int j = 0; j < header.length && j < bull1[row].length; j++) {
                        String str1 = dlm2.get(i).toString();
                        String[] p1 = str1.split(": ");
                        String p2 = p1[0];
                        if (p2.equals(header[j])) {
                            re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12);
                        }
                    }
                // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12);
            }

            doc.add(table);
            if (jCheckBox2.isSelected()) {
                DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                for (int i = 0; i < dlm3.size(); i++) {

                    String str = dlm3.get(i).toString();
                    System.out.println(str);
                    String[] parts = str.split(":");
                    String part1 = parts[0];
                    String part2 = parts[1];
                    System.out.println(part2);
                    int row = Integer.parseInt(part2) - 1;
                    float total = (float) 0.0;
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                        if (bull1[row][j].equals("")) {
                            continue;
                        } else {
                            total += Integer.parseInt(bull1[row][j]);
                        }

                    }
                    System.out.println(total);
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                        if (!bull1[row][j].equals("")) {

                            String[] Parts = header[j].split("_");
                            String Part2 = Parts[1];
                            dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1);
                        } else {
                            dataSet.setValue(0, "Percent", header[j]);

                        }
                    }

                }
                JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology",
                        "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false);

                if (dlm3.size() > 12) {
                    doc.newPage();
                }
                PdfContentByte contentByte = docWriter.getDirectContent();
                PdfTemplate template = contentByte.createTemplate(325, 250);
                PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                chart.draw(graphics2d, rectangle2d);

                graphics2d.dispose();
                contentByte.addTemplate(template, 0, 0);
            }
            if (jCheckBox1.isSelected()) {

                for (int i = 0; i < dlm3.size(); i++) {
                    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
                    String str = dlm3.get(i).toString();
                    System.out.println(str);
                    String[] parts = str.split(":");
                    String part1 = parts[0];
                    String part2 = parts[1];
                    System.out.println(part2);
                    int row = Integer.parseInt(part2) - 1;
                    float total = (float) 0.0;
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {

                        if (bull1[row][j].equals("")) {
                            continue;
                        } else {
                            total += Integer.parseInt(bull1[row][j]);
                        }

                    }
                    System.out.println(total);
                    for (int j = 77; j < header.length && j < bull1[row].length; j++) {
                        if (!bull1[row][j].equals("")) {

                            String[] Parts = header[j].split("_");
                            String Part2 = Parts[1];
                            dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2);
                        } else {
                            dataSet.setValue(0, "Percent", header[j]);

                        }
                    }
                    JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1,
                            "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false);
                    if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) {
                        doc.newPage();
                    }
                    PdfContentByte contentByte = docWriter.getDirectContent();
                    PdfTemplate template = contentByte.createTemplate(325, 250);
                    PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250);
                    Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250);

                    chart.draw(graphics2d, rectangle2d);

                    graphics2d.dispose();
                    contentByte.addTemplate(template, 0, 0);

                    doc.newPage();
                }
            }

        } catch (DocumentException dex) {
            dex.printStackTrace();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (doc != null) {
                //close the document
                doc.close();
            }
            if (docWriter != null) {
                //close the writer
                docWriter.close();
            }

        }
    }
    // TODO add your handling code here:

}

From source file:Servlet3.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w  w  w .j ava  2 s  .  co  m
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        // To Insert data to UserActivity table for Recent Activities Tab
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);
        // To insert colored Pie Chart into the PDF file using
        // iText now   
        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();

            PieChart.addTitle("Pie-Chart");
            PieChart.addAuthor("MUurugappan");

            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();

            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set response headers to view PDF
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}