Example usage for com.itextpdf.text.pdf PdfContentByte createTemplate

List of usage examples for com.itextpdf.text.pdf PdfContentByte createTemplate

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte createTemplate.

Prototype

public PdfTemplate createTemplate(final float width, final float height) 

Source Link

Document

Creates a new template.

Usage

From source file:com.vectorprint.report.jfree.ItextChartHelper.java

License:Open Source License

/**
 *
 * @param chart the chart tp plot/*from   w w w.ja v  a2  s  .c o m*/
 * @param contentByte the canvas to plot to
 * @param width the width of the chart will be fit to
 * @param height the height of the chart will be fit to
 * @return
 * @throws BadElementException
 */
public static Image getChartImage(JFreeChart chart, PdfContentByte contentByte, float width, float height,
        float opacity) throws BadElementException {

    // create PdfTemplate from PdfContentByte
    PdfTemplate template = contentByte.createTemplate(width, height);
    template.saveState();
    PdfGState pgs = new PdfGState();
    pgs.setFillOpacity(opacity);
    pgs.setStrokeOpacity(opacity);
    template.setGState(pgs);

    // create Graphics2D from PdfTemplate
    Graphics2D g2 = new PdfGraphics2D(template, width, height);

    // 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);
    g2.dispose(); // always dispose this

    template.restoreState();

    // create Image from PdfTemplate
    return Image.getInstance(template);
}

From source file:com.vectorprint.report.svg.BatikHelper.java

License:Open Source License

/**
 *
 * @param svg the svg document//www  .  j  a v  a 2s. co  m
 * @param contentByte the canvas to plot to
 * @param width the width in pt of the svg will be fit to
 * @param height the height in pt of the svg will be fit to
 * @return
 * @throws BadElementException
 */
public static PdfTemplate getSVGTemplate(Reader svg, PdfContentByte contentByte, float width, float height,
        float opacity) throws BadElementException, IOException {

    // create PdfTemplate from PdfContentByte
    PdfTemplate template = contentByte.createTemplate(width, height);

    // create Graphics2D from PdfTemplate
    Graphics2D g2 = new PdfGraphics2D(template, width, height);

    SVGDocument svgd = factory.createSVGDocument(null, svg);
    svgd.getRootElement().setAttribute("opacity", String.valueOf(opacity));

    GraphicsNode build = new GVTBuilder().build(ctx, svgd);
    build.paint(g2);

    g2.dispose(); // always dispose this
    return template;
}

From source file:de.bfs.radon.omsimulation.gui.data.OMExports.java

License:Open Source License

/**
 * //from  w ww . j a va2s  .c  om
 * Method to export charts as PDF files using the defined path.
 * 
 * @param path
 *          The filename and absolute path.
 * @param chart
 *          The JFreeChart object.
 * @param width
 *          The width of the PDF file.
 * @param height
 *          The height of the PDF file.
 * @param mapper
 *          The font mapper for the PDF file.
 * @param title
 *          The title of the PDF file.
 * @throws IOException
 *           If writing a PDF file fails.
 */
@SuppressWarnings("deprecation")
public static void exportPdf(String path, JFreeChart chart, int width, int height, FontMapper mapper,
        String title) throws IOException {
    File file = new File(path);
    FileOutputStream pdfStream = new FileOutputStream(file);
    BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream);
    Rectangle pagesize = new Rectangle(width, height);
    Document document = new Document();
    document.setPageSize(pagesize);
    document.setMargins(50, 50, 50, 50);
    document.addAuthor("OMSimulationTool");
    document.addSubject(title);
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput);
        document.open();
        PdfContentByte contentByte = pdfWriter.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D g2D = template.createGraphics(width, height, mapper);
        Double r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2D, r2D);
        g2D.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, "Failed to write PDF document.\n" + de.getMessage(), "Failed",
                JOptionPane.ERROR_MESSAGE);
        de.printStackTrace();
    }
    document.close();
}

From source file:de.fau.amos.ChartToPDF.java

License:Open Source License

/**
 * Converts Chart into PDF//w ww . ja  v  a 2 s.c o m
 * 
 * @param chart JFreeChart from CharRenderer that will be displayed in the PDF file
 * @param fileName Name of created PDF-file
 */
public void convertChart(JFreeChart chart, String fileName) {
    if (chart != null) {

        //set page size
        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight();

        //creating a new pdf document
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(new File(System.getProperty("userdir.location"), fileName + ".pdf")));
        } catch (DocumentException e) {
            e.printStackTrace();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        document.addAuthor("Green Energy Cockpit");
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        //sets the pdf page
        Graphics2D g2D = new PdfGraphics2D(tp, width, height);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);

        //draws the passed JFreeChart into the PDF file
        chart.draw(g2D, r2D);

        g2D.dispose();
        cb.addTemplate(tp, 0, 0);

        document.close();

        writer.flush();
        writer.close();
    }
}

From source file:direccion.Reportes.java

public Reportes() {

    String titulo = "Reportes";
    jFrame = new JFrame(titulo);
    jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    jFrame.setSize(800, 600);/*w w  w .  j a va 2 s .  com*/

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width / 2) - (jFrame.getSize().width / 2);
    int y = (screenSize.height / 2) - (jFrame.getSize().height / 2);
    jFrame.setLocation(x, y);

    JLabel etiqueta = new JLabel("Reportes");
    etiqueta.setBounds(300, 25, 200, 50);
    etiqueta.setFont(new Font("Verdana", Font.BOLD, 30));
    etiqueta.setForeground(Color.BLACK);

    JMenuBar jMenuBar = new JMenuBar();

    JMenu acceso = new JMenu("Acceso a");
    JMenu ayuda = new JMenu("Ayuda");

    JMenuItem rec_hum = new JMenuItem("Recursos Humanos");
    JMenuItem conta = new JMenuItem("Contabilidad");
    JMenuItem ventas = new JMenuItem("Ventas");
    JMenuItem compras = new JMenuItem("Compras");
    JMenuItem inventario = new JMenuItem("Inventario");

    JMenuItem acerca_de = new JMenuItem("Acerca de");
    acerca_de.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Ayuda", "Ayuda", 3);
        }
    });

    acceso.add(rec_hum);
    acceso.add(conta);
    acceso.add(ventas);
    acceso.add(compras);
    acceso.add(inventario);

    ayuda.add(acerca_de);

    jMenuBar.add(acceso);
    jMenuBar.add(ayuda);

    JCalendar cal1 = new JCalendar();
    cal1.setBounds(250, 150, 400, 300);
    JCalendarCombo cal2 = new JCalendarCombo();
    cal2.setBounds(250, 150, 400, 300);

    String reportes[] = { "Mantenimiento", "Compras", "Ventas", "Inventario", "Contabilidad",
            "Recursos Humanos" };
    JComboBox combobox = new JComboBox(reportes);
    combobox.setBounds(300, 100, 150, 30);

    JLabel calendario = new JLabel("Fecha de Operacin:");
    calendario.setBounds(60, 150, 150, 30);

    JButton aceptar = new JButton("Aceptar");
    aceptar.setBounds(50, 200, 150, 30);
    aceptar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (combobox.getSelectedIndex() == 0) {

                datos_mantenimiento.setValue("Recursos Humanos", d_mant_rh);
                datos_mantenimiento.setValue("Contabilidad", d_mant_cont);
                datos_mantenimiento.setValue("Ventas", d_mant_vent);
                datos_mantenimiento.setValue("Compras", d_mant_comp);
                datos_mantenimiento.setValue("Inventario", d_mant_inv);
                datos_mantenimiento.setValue("Mantenimiento", d_mant_mant);

                Grafica = ChartFactory.createPieChart3D("Mantenimiento", datos_mantenimiento, true, true, true);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Mantenimiento.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(450, 450);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Mantenimiento");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Mantenimiento.xls");
                        Cell celda;

                        String[] titulos = { "Recursos Humanos", "Contabilidad", "Ventas", "Compras",
                                "Inventario", "Mantenimiento" };
                        Double[] datos = { d_mant_rh, d_mant_cont, d_mant_vent, d_mant_comp, d_mant_inv,
                                d_mant_mant };

                        int i;
                        for (i = 0; i < titulos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(titulos[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < datos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(datos[i]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            if (combobox.getSelectedIndex() == 1) {

                datos_compras.setValue("Nomina", d_comp_nom);
                datos_compras.setValue("Compras", d_comp_comp);
                datos_compras.setValue("Gastos Fijos", d_comp_gf);
                datos_compras.setValue("Gastos Variables", d_comp_gv);
                datos_compras.setValue("Gastos Otros", d_comp_go);

                Grafica = ChartFactory.createPieChart3D("Compras", datos_compras, true, true, true);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Compras.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        menu.setVisible(false);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(850, 850);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Compras");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Compras.xls");
                        Cell celda;

                        String[] titulos = { "Nomina", "Compras", "Gastos Fijos", "Gastos Variables",
                                "Gastos Otros" };
                        Double[] datos = { d_comp_nom, d_comp_comp, d_comp_gf, d_comp_gv, d_comp_go };

                        int i;
                        for (i = 0; i < titulos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(titulos[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < datos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(datos[i]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            if (combobox.getSelectedIndex() == 2) {

                datos_ventas.addValue(d_vent_s1_lu, "Semana 1", "Lunes");
                datos_ventas.addValue(d_vent_s1_ma, "Semana 1", "Martes");
                datos_ventas.addValue(d_vent_s1_mi, "Semana 1", "Mircoles");
                datos_ventas.addValue(d_vent_s1_ju, "Semana 1", "Jueves");
                datos_ventas.addValue(d_vent_s1_vi, "Semana 1", "Viernes");
                datos_ventas.addValue(d_vent_s1_sa, "Semana 1", "Sbado");
                datos_ventas.addValue(d_vent_s1_do, "Semana 1", "Domingo");

                datos_ventas.addValue(d_vent_s2_lu, "Semana 2", "Lunes");
                datos_ventas.addValue(d_vent_s2_ma, "Semana 2", "Martes");
                datos_ventas.addValue(d_vent_s2_mi, "Semana 2", "Mircoles");
                datos_ventas.addValue(d_vent_s2_ju, "Semana 2", "Jueves");
                datos_ventas.addValue(d_vent_s2_vi, "Semana 2", "Viernes");
                datos_ventas.addValue(d_vent_s2_sa, "Semana 2", "Sbado");
                datos_ventas.addValue(d_vent_s2_do, "Semana 2", "Domingo");

                Grafica = ChartFactory.createLineChart3D("Ventas", "Das", "Ingresos", datos_ventas,
                        PlotOrientation.VERTICAL, true, true, false);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Ventas.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(450, 450);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Ventas");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Ventas.xls");
                        Cell celda;

                        String[] titulos1 = { "S1 lunes", "S1 martes", "S1 miercoles", "S1 jueves",
                                "S1 viernes", "S1 sabado", "S1 domingo" };
                        String[] titulos2 = { "S2 lunes", "S2 martes", "S2 miercoles", "S2 jueves",
                                "S2 viernes", "S2 sabado", "S2 domingo" };
                        Double[] datos1 = { d_vent_s1_lu, d_vent_s1_ma, d_vent_s1_mi, d_vent_s1_ju,
                                d_vent_s1_vi, d_vent_s1_sa, d_vent_s1_do };
                        Double[] datos2 = { d_vent_s2_lu, d_vent_s2_ma, d_vent_s2_mi, d_vent_s2_ju,
                                d_vent_s2_vi, d_vent_s2_sa, d_vent_s2_do };

                        int i, j;
                        for (i = 0; i < titulos1.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(titulos1[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < datos1.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(datos1[i]);
                        }
                        fila = sheet.createRow(3);
                        for (j = 0; j < titulos2.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(titulos2[j]);
                        }
                        fila = sheet.createRow(4);
                        for (j = 0; j < datos2.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(datos2[j]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            if (combobox.getSelectedIndex() == 3) {

                datos_inventario.setValue("Producto 1", d_inv_p1);
                datos_inventario.setValue("Producto 2", d_inv_p2);
                datos_inventario.setValue("Producto 3", d_inv_p3);
                datos_inventario.setValue("Producto 4", d_inv_p4);
                datos_inventario.setValue("Producto 5", d_inv_p5);

                Grafica = ChartFactory.createPieChart3D("Inventario", datos_inventario, true, true, true);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Inventario.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(450, 450);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Inventario");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Inventario.xls");
                        Cell celda;

                        String[] titulos = { "Producto 1", "Producto 2", "Prroducto 3", "Producto 4",
                                "Producto 5" };
                        Double[] datos = { d_inv_p1, d_inv_p2, d_inv_p3, d_inv_p4, d_inv_p5 };

                        int i;
                        for (i = 0; i < titulos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(titulos[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < datos.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(datos[i]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            if (combobox.getSelectedIndex() == 4) {

                datos_contabilidad.addValue(d_cont_e_lu, "Entradas", "Lunes");
                datos_contabilidad.addValue(d_cont_e_ma, "Entradas", "Martes");
                datos_contabilidad.addValue(d_cont_e_mi, "Entradas", "Mircoles");
                datos_contabilidad.addValue(d_cont_e_ju, "Entradas", "Jueves");
                datos_contabilidad.addValue(d_cont_e_vi, "Entradas", "Viernes");
                datos_contabilidad.addValue(d_cont_e_sa, "Entradas", "Sbado");
                datos_contabilidad.addValue(d_cont_e_do, "Entradas", "Domingo");

                datos_contabilidad.addValue(d_cont_s_lu, "Salidas", "Lunes");
                datos_contabilidad.addValue(d_cont_s_ma, "Salidas", "Martes");
                datos_contabilidad.addValue(d_cont_s_mi, "Salidas", "Mircoles");
                datos_contabilidad.addValue(d_cont_s_ju, "Salidas", "Jueves");
                datos_contabilidad.addValue(d_cont_s_vi, "Salidas", "Viernes");
                datos_contabilidad.addValue(d_cont_s_sa, "Salidas", "Sbado");
                datos_contabilidad.addValue(d_cont_s_do, "Salidas", "Domingo");

                datos_contabilidad.addValue(d_cont_u_lu, "Utilidades", "Lunes");
                datos_contabilidad.addValue(d_cont_u_ma, "Utilidades", "Martes");
                datos_contabilidad.addValue(d_cont_u_mi, "Utilidades", "Mircoles");
                datos_contabilidad.addValue(d_cont_u_ju, "Utilidades", "Jueves");
                datos_contabilidad.addValue(d_cont_u_vi, "Utilidades", "Viernes");
                datos_contabilidad.addValue(d_cont_u_sa, "Utilidades", "Sbado");
                datos_contabilidad.addValue(d_cont_u_do, "Utilidades", "Domingo");

                Grafica = ChartFactory.createLineChart3D("Contabilidad", "Das", "Ingresos",
                        datos_contabilidad, PlotOrientation.VERTICAL, true, true, false);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Contabilidad.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(450, 450);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Contabilidad");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Contabilidad.xls");
                        Cell celda;

                        String[] t_ent = { "E lunes", "E martes", "E miercoles", "E jueves", "E viernes",
                                "E sabado", "E domingo" };
                        String[] t_sal = { "S lunes", "S martes", "S miercoles", "S jueves", "S viernes",
                                "S sabado", "S domingo" };
                        String[] t_uti = { "U lunes", "U martes", "U miercoles", "U jueves", "U viernes",
                                "U sabado", "U domingo" };
                        Double[] d_ent = { d_cont_e_lu, d_cont_e_ma, d_cont_e_mi, d_cont_e_ju, d_cont_e_vi,
                                d_cont_e_sa, d_cont_e_do };
                        Double[] d_sal = { d_cont_s_lu, d_cont_s_ma, d_cont_s_mi, d_cont_s_ju, d_cont_s_vi,
                                d_cont_s_sa, d_cont_s_do };
                        Double[] d_uti = { d_cont_u_lu, d_cont_u_ma, d_cont_u_mi, d_cont_u_ju, d_cont_u_vi,
                                d_cont_u_sa, d_cont_u_do };

                        int i, j, k;
                        for (i = 0; i < t_ent.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(t_ent[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < d_ent.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(d_ent[i]);
                        }
                        fila = sheet.createRow(3);
                        for (j = 0; j < t_sal.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(t_sal[j]);
                        }
                        fila = sheet.createRow(4);
                        for (j = 0; j < d_sal.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(d_sal[j]);
                        }
                        fila = sheet.createRow(6);
                        for (k = 0; k < t_uti.length; k++) {
                            celda = fila.createCell(k);
                            celda.setCellValue(t_uti[k]);
                        }
                        fila = sheet.createRow(7);
                        for (k = 0; k < d_uti.length; k++) {
                            celda = fila.createCell(k);
                            celda.setCellValue(d_uti[k]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
            if (combobox.getSelectedIndex() == 5) {

                datos_rec_hum.addValue(d_rh_a_lu, "Asistencias", "Lunes");
                datos_rec_hum.addValue(d_rh_a_ma, "Asistencias", "Martes");
                datos_rec_hum.addValue(d_rh_a_mi, "Asistencias", "Mircoles");
                datos_rec_hum.addValue(d_rh_a_ju, "Asistencias", "Jueves");
                datos_rec_hum.addValue(d_rh_a_vi, "Asistencias", "Viernes");
                datos_rec_hum.addValue(d_rh_a_sa, "Asistencias", "Sbado");
                datos_rec_hum.addValue(d_rh_a_do, "Asistencias", "Domingo");

                datos_rec_hum.addValue(d_rh_r_lu, "Retardos", "Lunes");
                datos_rec_hum.addValue(d_rh_r_ma, "Retardos", "Martes");
                datos_rec_hum.addValue(d_rh_r_mi, "Retardos", "Mircoles");
                datos_rec_hum.addValue(d_rh_r_ju, "Retardos", "Jueves");
                datos_rec_hum.addValue(d_rh_r_vi, "Retardos", "Viernes");
                datos_rec_hum.addValue(d_rh_r_sa, "Retardos", "Sbado");
                datos_rec_hum.addValue(d_rh_r_do, "Retardos", "Domingo");

                datos_rec_hum.addValue(d_rh_f_lu, "Faltas", "Lunes");
                datos_rec_hum.addValue(d_rh_f_ma, "Faltas", "Martes");
                datos_rec_hum.addValue(d_rh_f_mi, "Faltas", "Mircoles");
                datos_rec_hum.addValue(d_rh_f_ju, "Faltas", "Jueves");
                datos_rec_hum.addValue(d_rh_f_vi, "Faltas", "Viernes");
                datos_rec_hum.addValue(d_rh_f_sa, "Faltas", "Sbado");
                datos_rec_hum.addValue(d_rh_f_do, "Faltas", "Domingo");

                Grafica = ChartFactory.createBarChart3D("Recursos Humanos", "Das", "Nmero de Empleados",
                        datos_rec_hum, PlotOrientation.VERTICAL, true, true, false);

                ChartPanel panel_grafica = new ChartPanel(Grafica);
                JFrame frame_grafica = new JFrame("Grfico");

                JMenuBar menu = new JMenuBar();
                JMenu archivo = new JMenu("Archivo");
                JMenuItem guardar = new JMenuItem("Guardar como reporte...");
                guardar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Document document = new Document();
                        PdfWriter writer = null;
                        try {
                            writer = PdfWriter.getInstance(document,
                                    new FileOutputStream("Grfico Recursos Humanos.pdf"));
                        } catch (DocumentException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(450, 450);
                        Graphics2D g2 = tp.createGraphicsShapes(450, 450);
                        menu.setVisible(false);
                        frame_grafica.print(g2);
                        menu.setVisible(true);
                        g2.dispose();
                        cb.addTemplate(tp, 30, 400);
                        document.close();

                        HSSFWorkbook workbook = new HSSFWorkbook();
                        HSSFSheet sheet = workbook.createSheet("Reporte de Recursos Humanos");

                        Row fila = sheet.createRow(0);
                        File archivo = new File("Reporte de Recursos Humanos.xls");
                        Cell celda;

                        String[] t_asi = { "A lunes", "A martes", "A miercoles", "A jueves", "A viernes",
                                "A sabado", "A domingo" };
                        String[] t_ret = { "R lunes", "R martes", "R miercoles", "R jueves", "R viernes",
                                "R sabado", "R domingo" };
                        String[] t_fal = { "F lunes", "F martes", "F miercoles", "F jueves", "F viernes",
                                "F sabado", "F domingo" };
                        int[] d_asi = { d_rh_a_lu, d_rh_a_ma, d_rh_a_mi, d_rh_a_ju, d_rh_a_vi, d_rh_a_sa,
                                d_rh_a_do };
                        int[] d_ret = { d_rh_r_lu, d_rh_r_ma, d_rh_r_mi, d_rh_r_ju, d_rh_r_vi, d_rh_r_sa,
                                d_rh_r_do };
                        int[] d_fal = { d_rh_f_lu, d_rh_r_ma, d_rh_r_mi, d_rh_r_ju, d_rh_r_vi, d_rh_r_sa,
                                d_rh_r_do };

                        int i, j, k;
                        for (i = 0; i < t_asi.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(t_asi[i]);
                        }
                        fila = sheet.createRow(1);
                        for (i = 0; i < d_asi.length; i++) {
                            celda = fila.createCell(i);
                            celda.setCellValue(d_asi[i]);
                        }
                        fila = sheet.createRow(3);
                        for (j = 0; j < t_ret.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(t_ret[j]);
                        }
                        fila = sheet.createRow(4);
                        for (j = 0; j < d_ret.length; j++) {
                            celda = fila.createCell(j);
                            celda.setCellValue(d_ret[j]);
                        }
                        fila = sheet.createRow(6);
                        for (k = 0; k < t_fal.length; k++) {
                            celda = fila.createCell(k);
                            celda.setCellValue(t_fal[k]);
                        }
                        fila = sheet.createRow(7);
                        for (k = 0; k < d_fal.length; k++) {
                            celda = fila.createCell(k);
                            celda.setCellValue(d_fal[k]);
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(archivo);
                            workbook.write(out);
                            out.close();
                            System.out.println("Archivo creado exitosamente!");
                        } catch (IOException ex) {
                            System.out.println("Error de escritura");
                            ex.printStackTrace();
                        }
                    }
                });
                archivo.add(guardar);
                menu.add(archivo);
                frame_grafica.getContentPane().add(panel_grafica);
                frame_grafica.setBounds(60, 60, 450, 400);
                frame_grafica.setJMenuBar(menu);
                frame_grafica.setVisible(true);
                frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            }
        }
    });

    jPanel = new JPanel();
    jPanel.setLayout(null);

    jPanel.add(cal1);
    jPanel.add(cal2);
    jPanel.add(etiqueta);
    jPanel.add(combobox);
    jPanel.add(calendario);
    jPanel.add(aceptar);
    jFrame.setJMenuBar(jMenuBar);
    jFrame.add(jPanel);

    jFrame.setVisible(true);
}

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

License:Open Source License

public void saveImageAsPdfFile(JFreeChart chart, String filename) throws WebUtilException {
    try {/*from   w ww .  j av  a2  s  .c o m*/
        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:edu.gcsc.vrl.jfreechart.JFExport.java

License:Open Source License

/**
 * 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 w w w  .j  ava2  s  .com
 * @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:edu.ksu.cs.a4vm.bse.reporter.Reporter.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {

    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            File3 = chooser.getSelectedFile().getAbsolutePath();
        }//  ww  w  .ja va2s .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);

            if (dlm3.size() == 1) {
                String str;
                str = dlm3.get(0).toString();
                String[] parts = str.split(":");
                String part2 = parts[1];
                System.out.println(part2);
                int row = Integer.parseInt(part2) - 1;
                String[][] temp = new String[25][6];
                temp[0][0] = "Tag";
                temp[0][1] = bull1[row][7];
                temp[0][2] = "Comments";
                temp[0][3] = "";
                temp[0][4] = "Total Count";
                temp[0][5] = "";
                temp[1][0] = "Tatoo";
                temp[1][1] = bull1[row][8];
                temp[1][2] = "All Normal";
                temp[1][3] = "Yes";
                temp[2][0] = "RFID";
                temp[2][1] = bull1[row][6];
                temp[2][2] = "Eyes";
                temp[2][3] = bull1[row][10];
                temp[3][0] = "Lot#";
                temp[3][1] = bull1[row][5];
                temp[3][2] = "Feet";
                temp[3][3] = bull1[row][12];
                temp[4][0] = "Brand";
                temp[4][1] = bull1[row][2];
                temp[4][2] = "Legs";
                temp[4][3] = bull1[row][14];
                temp[5][0] = "Date of Birth";
                temp[5][1] = bull1[row][4];
                temp[5][2] = "Testicals";
                temp[5][3] = bull1[row][16];
                temp[6][0] = "Age";
                temp[6][1] = bull1[row][0];
                temp[6][2] = "Accessory Sex Glands";
                temp[6][3] = bull1[row][18];
                temp[7][0] = "Breed";
                temp[7][1] = bull1[row][3];
                temp[7][2] = "Inguinal";
                temp[7][3] = bull1[row][20];
                temp[8][0] = "Other";
                temp[8][1] = bull1[row][9];
                temp[8][2] = "Scrotal";
                temp[8][3] = bull1[row][22];
                temp[9][0] = "Clinic Info";
                temp[9][1] = "xx";
                temp[9][2] = "Epidydimides";
                temp[9][3] = bull1[row][24];
                temp[10][4] = "Measurements";
                temp[10][5] = "xx";
                temp[10][0] = "Clinic Name";
                temp[10][1] = bull1[row][73];
                temp[10][2] = "Penis";
                temp[10][3] = bull1[row][26];
                temp[11][4] = "Scrotal Cirumference";
                temp[11][5] = bull1[row][54];
                temp[11][0] = "Veterinarian Name";
                temp[11][1] = bull1[row][74] + " " + bull1[row][74];
                temp[11][2] = "Prepuce";
                temp[11][3] = bull1[row][28];
                temp[12][4] = "Body Condition";
                temp[12][5] = bull1[row][47];
                temp[12][0] = "Address";
                temp[12][1] = bull1[row][66] + " " + bull1[row][67];
                temp[12][2] = "Scrotum";
                temp[12][3] = bull1[row][30];
                temp[13][4] = "Pelvic X Measure";
                temp[13][5] = bull1[row][52];
                temp[13][0] = "City";
                temp[13][1] = bull1[row][68];
                temp[13][2] = "Sex Drive";
                temp[13][3] = "xx";
                temp[14][4] = "Pelvic Y Measure";
                temp[14][5] = bull1[row][53];
                temp[14][0] = "State";
                temp[14][1] = bull1[row][71];
                temp[14][2] = "Breeding seasons used";
                temp[14][3] = bull1[row][40];
                temp[15][4] = "Hip Hight";
                temp[15][5] = bull1[row][50];
                temp[15][0] = "Zip Code";
                temp[15][1] = bull1[row][72];
                temp[15][2] = "Performance last season";
                temp[15][3] = bull1[row][38];
                temp[16][4] = "Frame Score";
                temp[16][5] = bull1[row][49];
                temp[16][0] = "Email";
                temp[16][1] = bull1[row][69];
                temp[16][2] = "Single or Multi sire";
                temp[16][3] = bull1[row][41];
                temp[17][4] = "Other";
                temp[17][5] = bull1[row][48];
                temp[17][0] = "Phone";
                temp[17][1] = bull1[row][70];
                temp[17][2] = "Other";
                temp[17][3] = bull1[row][39];
                temp[18][4] = "Motility";
                temp[18][5] = "xx";
                temp[18][0] = "Classification";
                temp[18][1] = bull1[row][35];
                temp[18][2] = "Comments";
                temp[18][3] = bull1[row][37];
                temp[19][4] = "Individual Motility";
                temp[19][5] = bull1[row][45];
                temp[19][0] = "Comments";
                temp[19][1] = bull1[row][36];
                temp[19][2] = "";
                temp[19][3] = "";
                temp[20][4] = "Motility %";
                temp[20][5] = bull1[row][46];
                temp[20][0] = "";
                temp[20][1] = "";
                temp[20][2] = "";
                temp[20][3] = "";
                temp[21][4] = "Gross Motility";
                temp[21][5] = bull1[row][44];
                temp[21][0] = "";
                temp[21][1] = "";
                temp[21][2] = "";
                temp[21][3] = "";
                for (int i = 9; i <= 29; i += 2) {
                    if (bull1[row][i].equals("FALSE")) {
                        temp[1][4] = "No";
                        break;
                    }
                }
                int i;
                int total = 0;
                for (i = 77; i < header.length && i < bull1[row].length; i++) {

                    temp[i - 76][4] = header[i].split("_")[1];
                    temp[i - 76][5] = bull1[row][i];
                    total += Integer.parseInt(bull1[row][i]);

                }
                temp[0][5] = Integer.toString(total);
                for (int j = i; j <= 85; j++) {
                    temp[j - 76][4] = "";
                    temp[j - 76][5] = "";
                }
                PdfPTable table = new PdfPTable(6);
                PdfPCell cell11, cell12, cell13;
                cell11 = new PdfPCell(
                        new Phrase("Bull Info", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell11.setColspan(2);
                cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell11.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell11);
                cell12 = new PdfPCell(
                        new Phrase("Physical Exam", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell12.setColspan(2);
                cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell12.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell12);
                cell13 = new PdfPCell(
                        new Phrase("Morphology", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                cell13.setColspan(2);
                cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell13.setVerticalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell13);
                for (int l = 0; l <= 21; l++) {
                    for (int j = 0; j < 6; j++) {
                        // System.out.println(l+" "+j);
                        if (!temp[l][j].equals("xx") && temp[l][j] != null) {
                            cell = new PdfPCell(
                                    new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));

                            cell.setBorder(PdfPCell.NO_BORDER);
                            if ((l == 9 && j == 0) || (l == 13 && j == 2) || (l == 10 && j == 4)
                                    || (l == 18 && j == 4)) {
                                cell = new PdfPCell(new Phrase(temp[l][j],
                                        FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                                cell.setColspan(2);
                            }
                            table.addCell(cell);
                        }
                    }
                }
                table.setWidthPercentage(90f);
                Reporter re;
                re = new Reporter();
                doc.add(table);
                if (jCheckBox2.isSelected() || jCheckBox1.isSelected())
                    doc.newPage();
            }

            else {

                //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);
                Reporter re;
                re = new Reporter();
                re.insertCell(table, "Bull Info", Element.ALIGN_CENTER, 1, bfBold12);
                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;
                    re.insertCell(table, Bulls[row], Element.ALIGN_CENTER, 1, bf12);
                    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(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReporterArchive.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:edu.ksu.cs.a4vm.bse.reporter.Reporter.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
    // 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();/* w  w  w .j a  v  a 2s. co m*/
    window.setVisible(true);

    String Path;
    JFileChooser chooser = new JFileChooser();
    FileSystemView view = chooser.getFileSystemView();
    Path = view.getDefaultDirectory() + "/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);

        if (dlm3.size() == 1) {
            String str;
            str = dlm3.get(0).toString();
            String[] parts = str.split(":");
            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            String[][] temp = new String[25][6];
            temp[0][0] = "Tag";
            temp[0][1] = bull1[row][7];
            temp[0][2] = "Comments";
            temp[0][3] = "";
            temp[0][4] = "Total Count";
            temp[0][5] = "";
            temp[1][0] = "Tatoo";
            temp[1][1] = bull1[row][8];
            temp[1][2] = "All Normal";
            temp[1][3] = "Yes";
            temp[2][0] = "RFID";
            temp[2][1] = bull1[row][6];
            temp[2][2] = "Eyes";
            temp[2][3] = bull1[row][10];
            temp[3][0] = "Lot#";
            temp[3][1] = bull1[row][5];
            temp[3][2] = "Feet";
            temp[3][3] = bull1[row][12];
            temp[4][0] = "Brand";
            temp[4][1] = bull1[row][2];
            temp[4][2] = "Legs";
            temp[4][3] = bull1[row][14];
            temp[5][0] = "Date of Birth";
            temp[5][1] = bull1[row][4];
            temp[5][2] = "Testicals";
            temp[5][3] = bull1[row][16];
            temp[6][0] = "Age";
            temp[6][1] = bull1[row][0];
            temp[6][2] = "Accessory Sex Glands";
            temp[6][3] = bull1[row][18];
            temp[7][0] = "Breed";
            temp[7][1] = bull1[row][3];
            temp[7][2] = "Inguinal";
            temp[7][3] = bull1[row][20];
            temp[8][0] = "Other";
            temp[8][1] = bull1[row][9];
            temp[8][2] = "Scrotal";
            temp[8][3] = bull1[row][22];
            temp[9][0] = "Clinic Info";
            temp[9][1] = "xx";
            temp[9][2] = "Epidydimides";
            temp[9][3] = bull1[row][24];
            temp[10][4] = "Measurements";
            temp[10][5] = "xx";
            temp[10][0] = "Clinic Name";
            temp[10][1] = bull1[row][73];
            temp[10][2] = "Penis";
            temp[10][3] = bull1[row][26];
            temp[11][4] = "Scrotal Cirumference";
            temp[11][5] = bull1[row][54];
            temp[11][0] = "Veterinarian Name";
            temp[11][1] = bull1[row][74] + " " + bull1[row][74];
            temp[11][2] = "Prepuce";
            temp[11][3] = bull1[row][28];
            temp[12][4] = "Body Condition";
            temp[12][5] = bull1[row][47];
            temp[12][0] = "Address";
            temp[12][1] = bull1[row][66] + " " + bull1[row][67];
            temp[12][2] = "Scrotum";
            temp[12][3] = bull1[row][30];
            temp[13][4] = "Pelvic X Measure";
            temp[13][5] = bull1[row][52];
            temp[13][0] = "City";
            temp[13][1] = bull1[row][68];
            temp[13][2] = "Sex Drive";
            temp[13][3] = "xx";
            temp[14][4] = "Pelvic Y Measure";
            temp[14][5] = bull1[row][53];
            temp[14][0] = "State";
            temp[14][1] = bull1[row][71];
            temp[14][2] = "Breeding seasons used";
            temp[14][3] = bull1[row][40];
            temp[15][4] = "Hip Hight";
            temp[15][5] = bull1[row][50];
            temp[15][0] = "Zip Code";
            temp[15][1] = bull1[row][72];
            temp[15][2] = "Performance last season";
            temp[15][3] = bull1[row][38];
            temp[16][4] = "Frame Score";
            temp[16][5] = bull1[row][49];
            temp[16][0] = "Email";
            temp[16][1] = bull1[row][69];
            temp[16][2] = "Single or Multi sire";
            temp[16][3] = bull1[row][41];
            temp[17][4] = "Other";
            temp[17][5] = bull1[row][48];
            temp[17][0] = "Phone";
            temp[17][1] = bull1[row][70];
            temp[17][2] = "Other";
            temp[17][3] = bull1[row][39];
            temp[18][4] = "Motility";
            temp[18][5] = "xx";
            temp[18][0] = "Classification";
            temp[18][1] = bull1[row][35];
            temp[18][2] = "Comments";
            temp[18][3] = bull1[row][37];
            temp[19][4] = "Individual Motility";
            temp[19][5] = bull1[row][45];
            temp[19][0] = "Comments";
            temp[19][1] = bull1[row][36];
            temp[19][2] = "";
            temp[19][3] = "";
            temp[20][4] = "Motility %";
            temp[20][5] = bull1[row][46];
            temp[20][0] = "";
            temp[20][1] = "";
            temp[20][2] = "";
            temp[20][3] = "";
            temp[21][4] = "Gross Motility";
            temp[21][5] = bull1[row][44];
            temp[21][0] = "";
            temp[21][1] = "";
            temp[21][2] = "";
            temp[21][3] = "";
            for (int i = 9; i <= 29; i += 2) {
                if (bull1[row][i].equals("FALSE")) {
                    temp[1][4] = "No";
                    break;
                }
            }
            int i;
            int total = 0;
            for (i = 77; i < header.length && i < bull1[row].length; i++) {

                temp[i - 76][4] = header[i].split("_")[1];
                temp[i - 76][5] = bull1[row][i];
                total += Integer.parseInt(bull1[row][i]);

            }
            temp[0][5] = Integer.toString(total);
            for (int j = i; j <= 85; j++) {
                temp[j - 76][4] = "";
                temp[j - 76][5] = "";
            }
            PdfPTable table = new PdfPTable(6);
            PdfPCell cell11, cell12, cell13;
            cell11 = new PdfPCell(new Phrase("Bull Info", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell11.setColspan(2);
            cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell11.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell11);
            cell12 = new PdfPCell(
                    new Phrase("Physical Exam", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell12.setColspan(2);
            cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell12.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell12);
            cell13 = new PdfPCell(new Phrase("Morphology", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell13.setColspan(2);
            cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell13.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell13);
            for (int l = 0; l <= 21; l++) {
                for (int j = 0; j < 6; j++) {
                    // System.out.println(l+" "+j);
                    if (!temp[l][j].equals("xx") && temp[l][j] != null) {
                        cell = new PdfPCell(
                                new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));

                        cell.setBorder(PdfPCell.NO_BORDER);
                        if ((l == 9 && j == 0) || (l == 13 && j == 2) || (l == 10 && j == 4)
                                || (l == 18 && j == 4)) {
                            cell = new PdfPCell(
                                    new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            cell.setVerticalAlignment(Element.ALIGN_CENTER);
                            cell.setColspan(2);
                        }
                        table.addCell(cell);
                    }
                }
            }
            table.setWidthPercentage(90f);
            Reporter re;
            re = new Reporter();
            doc.add(table);
            if (jCheckBox2.isSelected() || jCheckBox1.isSelected())
                doc.newPage();
        } else {

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

            float[] columnWidths = new float[temp + 1];
            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);
            Reporter re;
            re = new Reporter();
            re.insertCell(table, "Bull Info", Element.ALIGN_CENTER, 1, bfBold12);
            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;
                re.insertCell(table, Bulls[row], Element.ALIGN_CENTER, 1, bf12);
                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();
        JOptionPane.showMessageDialog(null, dex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(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:edu.ksu.cs.a4vm.bse.reporter.Reporter.java

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {

    // 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();//w w  w.  j a  v a2s  .  c om
    window.setVisible(true);

    String Path;
    JFileChooser fr = new JFileChooser();
    FileSystemView fw = fr.getFileSystemView();
    //    System.out.println(fw.getDefaultDirectory());

    Path = fw.getDefaultDirectory() + "/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);
        if (dlm3.size() == 1) {
            String str;
            str = dlm3.get(0).toString();
            String[] parts = str.split(":");
            String part2 = parts[1];
            System.out.println(part2);
            int row = Integer.parseInt(part2) - 1;
            String[][] temp = new String[25][6];
            temp[0][0] = "Tag";
            temp[0][1] = bull1[row][7];
            temp[0][2] = "Comments";
            temp[0][3] = "";
            temp[0][4] = "Total Count";
            temp[0][5] = "";
            temp[1][0] = "Tatoo";
            temp[1][1] = bull1[row][8];
            temp[1][2] = "All Normal";
            temp[1][3] = "Yes";
            temp[2][0] = "RFID";
            temp[2][1] = bull1[row][6];
            temp[2][2] = "Eyes";
            temp[2][3] = bull1[row][10];
            temp[3][0] = "Lot#";
            temp[3][1] = bull1[row][5];
            temp[3][2] = "Feet";
            temp[3][3] = bull1[row][12];
            temp[4][0] = "Brand";
            temp[4][1] = bull1[row][2];
            temp[4][2] = "Legs";
            temp[4][3] = bull1[row][14];
            temp[5][0] = "Date of Birth";
            temp[5][1] = bull1[row][4];
            temp[5][2] = "Testicals";
            temp[5][3] = bull1[row][16];
            temp[6][0] = "Age";
            temp[6][1] = bull1[row][0];
            temp[6][2] = "Accessory Sex Glands";
            temp[6][3] = bull1[row][18];
            temp[7][0] = "Breed";
            temp[7][1] = bull1[row][3];
            temp[7][2] = "Inguinal";
            temp[7][3] = bull1[row][20];
            temp[8][0] = "Other";
            temp[8][1] = bull1[row][9];
            temp[8][2] = "Scrotal";
            temp[8][3] = bull1[row][22];
            temp[9][0] = "Clinic Info";
            temp[9][1] = "xx";
            temp[9][2] = "Epidydimides";
            temp[9][3] = bull1[row][24];
            temp[10][4] = "Measurements";
            temp[10][5] = "xx";
            temp[10][0] = "Clinic Name";
            temp[10][1] = bull1[row][73];
            temp[10][2] = "Penis";
            temp[10][3] = bull1[row][26];
            temp[11][4] = "Scrotal Cirumference";
            temp[11][5] = bull1[row][54];
            temp[11][0] = "Veterinarian Name";
            temp[11][1] = bull1[row][74] + " " + bull1[row][75];
            temp[11][2] = "Prepuce";
            temp[11][3] = bull1[row][28];
            temp[12][4] = "Body Condition";
            temp[12][5] = bull1[row][47];
            temp[12][0] = "Address";
            temp[12][1] = bull1[row][66] + " " + bull1[row][67];
            temp[12][2] = "Scrotum";
            temp[12][3] = bull1[row][30];
            temp[13][4] = "Pelvic X Measure";
            temp[13][5] = bull1[row][52];
            temp[13][0] = "City";
            temp[13][1] = bull1[row][68];
            temp[13][2] = "Sex Drive";
            temp[13][3] = "xx";
            temp[14][4] = "Pelvic Y Measure";
            temp[14][5] = bull1[row][53];
            temp[14][0] = "State";
            temp[14][1] = bull1[row][71];
            temp[14][2] = "Breeding seasons used";
            temp[14][3] = bull1[row][40];
            temp[15][4] = "Hip Hight";
            temp[15][5] = bull1[row][50];
            temp[15][0] = "Zip Code";
            temp[15][1] = bull1[row][72];
            temp[15][2] = "Performance last season";
            temp[15][3] = bull1[row][38];
            temp[16][4] = "Frame Score";
            temp[16][5] = bull1[row][49];
            temp[16][0] = "Email";
            temp[16][1] = bull1[row][69];
            temp[16][2] = "Single or Multi sire";
            temp[16][3] = bull1[row][41];
            temp[17][4] = "Other";
            temp[17][5] = bull1[row][48];
            temp[17][0] = "Phone";
            temp[17][1] = bull1[row][70];
            temp[17][2] = "Other";
            temp[17][3] = bull1[row][39];
            temp[18][4] = "Motility";
            temp[18][5] = "xx";
            temp[18][0] = "Classification";
            temp[18][1] = bull1[row][35];
            temp[18][2] = "Comments";
            temp[18][3] = bull1[row][37];
            temp[19][4] = "Individual Motility";
            temp[19][5] = bull1[row][45];
            temp[19][0] = "Comments";
            temp[19][1] = bull1[row][36];
            temp[19][2] = "";
            temp[19][3] = "";
            temp[20][4] = "Motility %";
            temp[20][5] = bull1[row][46];
            temp[20][0] = "";
            temp[20][1] = "";
            temp[20][2] = "";
            temp[20][3] = "";
            temp[21][4] = "Gross Motility";
            temp[21][5] = bull1[row][44];
            temp[21][0] = "";
            temp[21][1] = "";
            temp[21][2] = "";
            temp[21][3] = "";
            for (int i = 9; i <= 29; i += 2) {
                if (bull1[row][i].equals("FALSE")) {
                    temp[1][4] = "No";
                    break;
                }
            }
            int i;
            int total = 0;
            for (i = 77; i < header.length && i < bull1[row].length; i++) {

                temp[i - 76][4] = header[i].split("_")[1];
                temp[i - 76][5] = bull1[row][i];
                total += Integer.parseInt(bull1[row][i]);

            }
            temp[0][5] = Integer.toString(total);
            for (int j = i; j <= 85; j++) {
                temp[j - 76][4] = "";
                temp[j - 76][5] = "";
            }
            PdfPTable table = new PdfPTable(6);
            PdfPCell cell11, cell12, cell13;
            cell11 = new PdfPCell(new Phrase("Bull Info", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell11.setColspan(2);
            cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell11.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell11);
            cell12 = new PdfPCell(
                    new Phrase("Physical Exam", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell12.setColspan(2);
            cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell12.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell12);
            cell13 = new PdfPCell(new Phrase("Morphology", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
            cell13.setColspan(2);
            cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell13.setVerticalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell13);
            for (int l = 0; l <= 21; l++) {
                for (int j = 0; j < 6; j++) {
                    // System.out.println(l+" "+j);
                    if (!temp[l][j].equals("xx") && temp[l][j] != null) {
                        cell = new PdfPCell(
                                new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 10)));

                        cell.setBorder(PdfPCell.NO_BORDER);
                        if ((l == 9 && j == 0) || (l == 13 && j == 2) || (l == 10 && j == 4)
                                || (l == 18 && j == 4)) {
                            cell = new PdfPCell(
                                    new Phrase(temp[l][j], FontFactory.getFont(FontFactory.TIMES_ROMAN, 12)));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            cell.setVerticalAlignment(Element.ALIGN_CENTER);
                            cell.setColspan(2);
                        }
                        table.addCell(cell);
                    }
                }
            }
            table.setWidthPercentage(90f);
            Reporter re;
            re = new Reporter();
            doc.add(table);
            if (jCheckBox2.isSelected() || jCheckBox1.isSelected())
                doc.newPage();
        } else {

            //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);
            Reporter re;
            re = new Reporter();
            re.insertCell(table, "Bull Info", Element.ALIGN_CENTER, 1, bfBold12);
            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;
                re.insertCell(table, Bulls[row], Element.ALIGN_CENTER, 1, bf12);
                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(ReporterArchive.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReporterArchive.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);
}