print bar chart to pdf

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
alisiahaan
Posts: 5
Joined: Mon May 18, 2015 1:41 pm
antibot: No, of course not.

print bar chart to pdf

Post by alisiahaan » Sun May 24, 2015 6:28 pm

hi i want to ask something. I want to call the "save chart to pdf" method, but i got problem on argument list of createchart method.I try dataset but it goes wrong. please someone help me to solve this. Thank you,

This is my code :

Code: Select all

public class MetricCharts extends ApplicationFrame {


    public MetricCharts(final String title) throws Exception {

        super(title);

        final CategoryDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(500, 270));
        setContentPane(chartPanel);

    }

 
    /**
     * Returns a sample dataset.
     * 
     * @return The dataset.
     * @throws ParserConfigurationException 
     * @throws IOException 
     * @throws SAXException 
     */
    public static CategoryDataset createDataset() throws Exception {
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         Document document = db.parse(new File("C:/Users/Napitupulu/AppData/Local/Temp/pti_php_depend/summary.xml"));
         NodeList nodeList = document.getElementsByTagName("metrics");
         
         for(int x=nodeList.getLength()-1;x>=0;x--){
            String m = nodeList.item(x).getAttributes().getNamedItem("ahh").getNodeName();
        	 //System.out.println(m);
         }
         
        		 
         for(int x=nodeList.getLength()-1;x>=0;x--){
        	 Double a = Double.parseDouble(nodeList.item(x).getAttributes().getNamedItem("ahh").getNodeValue());
        	 Double b = Double.parseDouble(nodeList.item(x).getAttributes().getNamedItem("cloc").getNodeValue());
        	 double c = b/a;
             dataset.addValue(a,nodeList.item(x).getAttributes().getNamedItem("ahh").getNodeName(),nodeList.item(x).getAttributes().getNamedItem("ahh").getNodeName());
             dataset.addValue(c,nodeList.item(x).getAttributes().getNamedItem("cloc").getNodeName(),nodeList.item(x).getAttributes().getNamedItem("cloc").getNodeName());
         }
         
         
         

        return dataset;
        }
    

    /**
     * Creates a sample chart.
     * 
     * @param dataset  the dataset.
     * 
     * @return The chart.
     */
    public static JFreeChart createChart(final CategoryDataset dataset) {

        // create the chart...
        final JFreeChart chart = ChartFactory.createBarChart(
            "Bar Chart Demo",         // chart title
            "Metrics",               // domain axis label
            "Value",                  // range axis label
            dataset,                  // data
            PlotOrientation.VERTICAL, // orientation
            true,                     // include legend
            true,                     // tooltips?
            false                             // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
);
        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        final CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());

        // disable bar outlines...
        final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(true);

        // set up gradient paints for series...
        final GradientPaint gp0 = new GradientPaint(
            0.0f, 0.0f, Color.blue, 
            0.0f, 0.0f, Color.lightGray
        );
        //final GradientPaint gp1 = new GradientPaint(
          //  0.0f, 0.0f, Color.green, 
            //0.0f, 0.0f, Color.lightGray
        //);
        //final GradientPaint gp2 = new GradientPaint(
          //  0.0f, 0.0f, Color.red, 
            //0.0f, 0.0f, Color.lightGray
        //);
        renderer.setSeriesPaint(0, gp0);
        //renderer.setSeriesPaint(1, gp1);
        //renderer.setSeriesPaint(2, gp2);

        
   final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(
       CategoryLabelPositions.STANDARD
    );

        
   return chart;

    
    }


    public static void main(final String[] args) throws Exception {

        final MetricCharts demo = new MetricCharts("Barchart");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);
        MetricChartsPDF charts;
        charts = new MetricChartsPDF();
        charts.saveChartToPDF(createChart(dataset), 500, 400, "C://barchart.pdf");
        
    }

}

paradoxoff
Posts: 1634
Joined: Sat Feb 17, 2007 1:51 pm

Re: print bar chart to pdf

Post by paradoxoff » Tue May 26, 2015 12:03 pm

Exporting charts to PDF can be achieved as follows:
Solution using iText:

Code: Select all

    public void exportChart(OutputStream out, JFreeChart chart, int width, int height) throws IOException {
        com.lowagie.text.Rectangle rect = new com.lowagie.text.Rectangle((float) width, (float) height);
        com.lowagie.text.Document document = new com.lowagie.text.Document(rect);
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, out);
        } catch (DocumentException e) {
            throw new IOException("Root cause " + e.getClass().getName() + ", " + e.getMessage());
        }
        document.open();
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("C:\\WINNT\\Fonts");
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, mapper);
        tp.setWidth(width);
        tp.setHeight(height);
        chart.draw(g2d, new Rectangle(width, height));
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
    }
Solution using freehep:

Code: Select all

    public void exportChart(OutputStream out, JFreeChart chart, int width, int height) throws IOException {
        PDFGraphics2D g2d = new PDFGraphics2D(out, new Dimension(width, height));
        g2d.startExport();
        g2d.openPage(new Dimension(width, height), "chart");
        chart.draw((Graphics2D) g2d.create(), new Rectangle(width, height));
        g2d.closePage();
        g2d.endExport();
        g2d.closeStream();
    }

Locked