com.datamyne.charts.FinallyDemo.java Source code

Java tutorial

Introduction

Here is the source code for com.datamyne.charts.FinallyDemo.java

Source

package com.datamyne.charts;

/**
 * Copyright 2010 Jee Vang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.DefaultFontMapper;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Finally there demo in fixing UglyDemo.
 * 
 * @author Jee Vang
 *
 */
public class FinallyDemo {

    /**
     * Gets a {@link JFreeChart}.
     * @return {@link JFreeChart}.
     */
    public JFreeChart getChart() {
        //create dummy data
        //take from http://www.java2s.com/Code/Java/Chart/JFreeChartPieChartDemo1.htm
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("One", new Double(43.2));
        dataset.setValue("Two", new Double(10.0));
        dataset.setValue("Three", new Double(27.5));
        dataset.setValue("Four", new Double(17.5));
        dataset.setValue("Five", new Double(11.0));
        dataset.setValue("Six", new Double(19.4));

        //use the ChartFactory to create a pie chart
        JFreeChart chart = ChartFactory.createPieChart("Dummy Data", dataset, true, true, false);
        return chart;
    }

    /**
     * Creates PDf file.
     * @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) {
                }
            }
        }
    }

    /**
     * Gets generic lorem ipsum text.
     * @return String.
     */
    public String getText() {
        StringBuffer sb = new StringBuffer();
        sb.append("Lorem ipsum dolor sit amet, consectetur adipisicing ");
        sb.append("elit, sed do eiusmod tempor incididunt ut labore et ");
        sb.append("dolore magna aliqua. Ut enim ad minim veniam, quis nostrud ");
        sb.append("exercitation ullamco laboris nisi ut aliquip ex ");
        sb.append("ea commodo consequat. Duis aute irure dolor in reprehenderit ");
        sb.append("in voluptate velit esse cillum dolore eu fugiat ");
        sb.append("nulla pariatur. Excepteur sint occaecat cupidatat non ");
        sb.append("proident, sunt in culpa qui officia deserunt mollit ");
        sb.append("anim id est laborum.");
        return sb.toString();
    }

    /**
     * Main method.
     * @param args No args required.
     * @throws FileNotFoundException
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {
        (new FinallyDemo()).create(new FileOutputStream(new File("/storage/tradeFiles/finally-there-demo.pdf")));
    }
}