Example usage for com.itextpdf.text Font Font

List of usage examples for com.itextpdf.text Font Font

Introduction

In this page you can find the example usage for com.itextpdf.text Font Font.

Prototype


public Font(final BaseFont bf, final float size, final int style, final BaseColor color) 

Source Link

Document

Constructs a Font.

Usage

From source file:br.com.tcc.view.MovimentoEntradaView.java

private void relat(String sql) throws SQLException, DocumentException, FileNotFoundException, IOException {
    /* Create Connection objects */
    Connection con = new ConnectionFactory().getConnection();
    Statement stmt = con.createStatement();

    int row = tblRegistro.getSelectedRow();
    int id = entradaRegistroList.get(row).getId();
    SimpleDateFormat horaformatada = new SimpleDateFormat("HH:mm:ss");
    Date horaAtual = new Date();
    hora = horaformatada.format(horaAtual);
    Date data = new Date();
    //  mes    = ""+Data.getMonth();//0 a 11 
    dia = "" + data.getDate();
    ano = "" + (1900 + data.getYear());
    switch (data.getMonth()) {
    case 0:/*from   w ww.  j av a2s  . c  om*/
        mes = "Janeiro";
        break;
    case 1:
        mes = "Fevereiro";
        break;
    case 2:
        mes = "Maro";
        break;
    case 3:
        mes = "Abril";
        break;
    case 4:
        mes = "Maio";
        break;
    case 5:
        mes = "Junho";
        break;
    case 6:
        mes = "Julho";
        break;
    case 7:
        mes = "Agosto";
        break;
    case 8:
        mes = "Setembro";
        break;
    case 9:
        mes = "Outubro";
        break;
    case 10:
        mes = "Novembro";
        break;
    case 11:
        mes = "Dezembro";
        break;
    }

    /* Define the SQL query */
    //         sql = "SELECT cliente.nome, funcionario.nome, tipopagamento.descricao, vendaregistro.dataVenda, vendaregistro.vlrSugerido, vendaregistro.totalVenda, vendaregistro.parcela, vendaregistro.1vencimento, vendaregistro.ativo FROM vendaregistro as vendaregistro INNER JOIN cliente as cliente ON (vendaregistro.idCliente = cliente.id) \n" +
    //"INNER JOIN funcionario as funcionario ON (vendaregistro.idFuncionario = funcionario.id) INNER JOIN tipopagamento as tipopagamento ON (vendaregistro.idTipoPagamento = tipopagamento.id) WHERE  dataVenda = CURRENT_DATE";
    ResultSet query = stmt.executeQuery(sql);
    /* Step-2: Initialize PDF documents - logical objects */
    Document PDFLogReport = new Document();
    PdfWriter.getInstance(PDFLogReport,
            new FileOutputStream("C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Entrada " + id + ".pdf"));
    PDFLogReport.open();

    Paragraph cabecalho = new Paragraph("AGRO EMPRESARIAL - SISTEMA DE GERENCIAMENTO\n"
            + "RUA GONALVES CHAVES, 602 PELOTAS/RS\n" + "FONE:(53) 3232-3232 BAIRRO: CENTRO\n"
            + "CNPJ: 12.345.678/1011-12\n" + "-------------------------------------------\n" + dia + "/" + mes
            + "/" + ano + "   " + hora + "   COD: " + id + " \n\n");
    cabecalho.setAlignment(Element.ALIGN_CENTER);

    PDFLogReport.add(cabecalho);
    //we have two columns in our table  
    PdfPTable LogTable = new PdfPTable(4);

    // Ttulo para a tabela
    Paragraph tableHeader = new Paragraph("Relatrio de Entrada de Estoque");

    PdfPCell header = new PdfPCell(tableHeader);

    // Definindo que o header vai ocupar as 2 colunas
    header.setColspan(4);
    // Definindo alinhamento do header
    header.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
    // Adicionando o header  tabela

    Font fonte = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD, BaseColor.BLACK);
    Font fonteDados = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL, BaseColor.BLACK);

    LogTable.addCell(header);
    LogTable.addCell(new Paragraph("Produto ", fonte));
    LogTable.addCell(new Paragraph("Quantidade", fonte));
    LogTable.addCell(new Paragraph("Valor Unitrio", fonte));
    LogTable.addCell(new Paragraph("Valor Total", fonte));
    //create a cell object  
    //         PdfPCell table_cell;  
    while (query.next()) {
        String produto = query.getString("produto.descricao");
        LogTable.addCell(new Paragraph(produto, fonteDados));
        String quantidade = query.getString("qtde");
        LogTable.addCell(new Paragraph(quantidade, fonteDados));
        String vlrSugerido = query.getString("vlrUnitario");
        LogTable.addCell(new Paragraph(vlrSugerido, fonteDados));
        String vlrTotal = query.getString("vlrTotal");
        LogTable.addCell(new Paragraph(vlrTotal, fonteDados));
    }
    /* Attach report table to PDF */
    PDFLogReport.add(LogTable);
    double valor = entradaRegistroList.get(row).getVlrTotal();
    Paragraph paragrafoValor = new Paragraph("Valor R$: " + valor);
    paragrafoValor.setAlignment(Element.ALIGN_RIGHT);
    PDFLogReport.add(paragrafoValor);

    PDFLogReport.close();
    /* Close all DB related objects */
    query.close();
    stmt.close();
    con.close();
    String file;
    file = "C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Entrada " + id + ".pdf";
    Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file);
}

From source file:br.com.tcc.view.MovimentoOrcamentoView.java

private void relat(String sql) throws IOException, DocumentException, SQLException {
    /* Create Connection objects */
    Connection con = new ConnectionFactory().getConnection();
    Statement stmt = con.createStatement();

    int row = tblRegistro.getSelectedRow();
    int id = orcamentoRegistroList.get(row).getId();
    SimpleDateFormat horaformatada = new SimpleDateFormat("HH:mm:ss");
    Date horaAtual = new Date();
    hora = horaformatada.format(horaAtual);
    Date data = new Date();
    //  mes    = ""+Data.getMonth();//0 a 11 
    dia = "" + data.getDate();
    ano = "" + (1900 + data.getYear());
    switch (data.getMonth()) {
    case 0:/*from   w w w . ja v a  2 s  . c om*/
        mes = "Janeiro";
        break;
    case 1:
        mes = "Fevereiro";
        break;
    case 2:
        mes = "Maro";
        break;
    case 3:
        mes = "Abril";
        break;
    case 4:
        mes = "Maio";
        break;
    case 5:
        mes = "Junho";
        break;
    case 6:
        mes = "Julho";
        break;
    case 7:
        mes = "Agosto";
        break;
    case 8:
        mes = "Setembro";
        break;
    case 9:
        mes = "Outubro";
        break;
    case 10:
        mes = "Novembro";
        break;
    case 11:
        mes = "Dezembro";
        break;
    }

    /* Define the SQL query */
    //         sql = "SELECT cliente.nome, funcionario.nome, tipopagamento.descricao, vendaregistro.dataVenda, vendaregistro.vlrSugerido, vendaregistro.totalVenda, vendaregistro.parcela, vendaregistro.1vencimento, vendaregistro.ativo FROM vendaregistro as vendaregistro INNER JOIN cliente as cliente ON (vendaregistro.idCliente = cliente.id) \n" +
    //"INNER JOIN funcionario as funcionario ON (vendaregistro.idFuncionario = funcionario.id) INNER JOIN tipopagamento as tipopagamento ON (vendaregistro.idTipoPagamento = tipopagamento.id) WHERE  dataVenda = CURRENT_DATE";
    ResultSet query = stmt.executeQuery(sql);
    /* Step-2: Initialize PDF documents - logical objects */
    Document PDFLogReport = new Document();
    PdfWriter.getInstance(PDFLogReport,
            new FileOutputStream("C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Oramento " + id + ".pdf"));
    PDFLogReport.open();

    Paragraph cabecalho = new Paragraph("AGRO EMPRESARIAL - SISTEMA DE GERENCIAMENTO\n"
            + "RUA GONALVES CHAVES, 602 PELOTAS/RS\n" + "FONE:(53) 3232-3232 BAIRRO: CENTRO\n"
            + "CNPJ: 12.345.678/1011-12\n" + "-------------------------------------------\n" + dia + "/" + mes
            + "/" + ano + "   " + hora + "   COD: " + id + " \n\n");
    cabecalho.setAlignment(Element.ALIGN_CENTER);

    PDFLogReport.add(cabecalho);
    //we have two columns in our table  
    PdfPTable LogTable = new PdfPTable(4);

    // Ttulo para a tabela
    Paragraph tableHeader = new Paragraph("Oramento");

    PdfPCell header = new PdfPCell(tableHeader);

    // Definindo que o header vai ocupar as 2 colunas
    header.setColspan(4);
    // Definindo alinhamento do header
    header.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
    // Adicionando o header  tabela

    Font fonte = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD, BaseColor.BLACK);
    Font fonteDados = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL, BaseColor.BLACK);

    LogTable.addCell(header);
    LogTable.addCell(new Paragraph("Produto ", fonte));
    LogTable.addCell(new Paragraph("Quantidade", fonte));
    LogTable.addCell(new Paragraph("Valor Unitrio", fonte));
    LogTable.addCell(new Paragraph("Valor Total", fonte));
    //create a cell object  
    //         PdfPCell table_cell;  
    while (query.next()) {
        String produto = query.getString("produto.descricao");
        LogTable.addCell(new Paragraph(produto, fonteDados));
        String quantidade = query.getString("qtde");
        LogTable.addCell(new Paragraph(quantidade, fonteDados));
        String vlrSugerido = query.getString("vlrUnitario");
        LogTable.addCell(new Paragraph(vlrSugerido, fonteDados));
        String vlrTotal = query.getString("vlrTotal");
        LogTable.addCell(new Paragraph(vlrTotal, fonteDados));
    }
    /* Attach report table to PDF */
    PDFLogReport.add(LogTable);
    double valor = orcamentoRegistroList.get(row).getVlrTotalOrcamento();
    Paragraph paragrafoValor = new Paragraph("Valor R$: " + valor);
    paragrafoValor.setAlignment(Element.ALIGN_RIGHT);
    PDFLogReport.add(paragrafoValor);

    PDFLogReport.close();
    /* Close all DB related objects */
    query.close();
    stmt.close();
    con.close();
    String file;
    file = "C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Oramento " + id + ".pdf";
    Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file);
}

From source file:br.com.tcc.view.MovimentoPedidoView.java

private void relat(String sql) throws SQLException, DocumentException, FileNotFoundException, IOException {
    /* Create Connection objects */
    Connection con = new ConnectionFactory().getConnection();
    Statement stmt = con.createStatement();

    int row = tblRegistro.getSelectedRow();
    int id = pedidoRegistroList.get(row).getId();
    SimpleDateFormat horaformatada = new SimpleDateFormat("HH:mm:ss");
    Date horaAtual = new Date();
    hora = horaformatada.format(horaAtual);
    Date data = new Date();
    //  mes    = ""+Data.getMonth();//0 a 11 
    dia = "" + data.getDate();
    ano = "" + (1900 + data.getYear());
    switch (data.getMonth()) {
    case 0:/*w  ww  . j  av  a 2  s  . c o  m*/
        mes = "Janeiro";
        break;
    case 1:
        mes = "Fevereiro";
        break;
    case 2:
        mes = "Maro";
        break;
    case 3:
        mes = "Abril";
        break;
    case 4:
        mes = "Maio";
        break;
    case 5:
        mes = "Junho";
        break;
    case 6:
        mes = "Julho";
        break;
    case 7:
        mes = "Agosto";
        break;
    case 8:
        mes = "Setembro";
        break;
    case 9:
        mes = "Outubro";
        break;
    case 10:
        mes = "Novembro";
        break;
    case 11:
        mes = "Dezembro";
        break;
    }

    /* Define the SQL query */
    //         sql = "SELECT cliente.nome, funcionario.nome, tipopagamento.descricao, vendaregistro.dataVenda, vendaregistro.vlrSugerido, vendaregistro.totalVenda, vendaregistro.parcela, vendaregistro.1vencimento, vendaregistro.ativo FROM vendaregistro as vendaregistro INNER JOIN cliente as cliente ON (vendaregistro.idCliente = cliente.id) \n" +
    //"INNER JOIN funcionario as funcionario ON (vendaregistro.idFuncionario = funcionario.id) INNER JOIN tipopagamento as tipopagamento ON (vendaregistro.idTipoPagamento = tipopagamento.id) WHERE  dataVenda = CURRENT_DATE";
    ResultSet query = stmt.executeQuery(sql);
    /* Step-2: Initialize PDF documents - logical objects */
    Document PDFLogReport = new Document();
    PdfWriter.getInstance(PDFLogReport,
            new FileOutputStream("C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Pedidos " + id + ".pdf"));
    PDFLogReport.open();

    Paragraph cabecalho = new Paragraph("AGRO EMPRESARIAL - SISTEMA DE GERENCIAMENTO\n"
            + "RUA GONALVES CHAVES, 602 PELOTAS/RS\n" + "FONE:(53) 3232-3232 BAIRRO: CENTRO\n"
            + "CNPJ: 12.345.678/1011-12\n" + "-------------------------------------------\n" + dia + "/" + mes
            + "/" + ano + "   " + hora + "   COD: " + id + " \n\n");
    cabecalho.setAlignment(Element.ALIGN_CENTER);

    PDFLogReport.add(cabecalho);
    //we have two columns in our table  
    PdfPTable LogTable = new PdfPTable(4);

    // Ttulo para a tabela
    Paragraph tableHeader = new Paragraph("Lista de Pedidos");

    PdfPCell header = new PdfPCell(tableHeader);

    // Definindo que o header vai ocupar as 2 colunas
    header.setColspan(4);
    // Definindo alinhamento do header
    header.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
    // Adicionando o header  tabela

    Font fonte = new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD, BaseColor.BLACK);
    Font fonteDados = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL, BaseColor.BLACK);

    LogTable.addCell(header);
    LogTable.addCell(new Paragraph("Produto ", fonte));
    LogTable.addCell(new Paragraph("Quantidade", fonte));
    LogTable.addCell(new Paragraph("Valor Unitrio", fonte));
    LogTable.addCell(new Paragraph("Valor Total", fonte));
    //create a cell object  
    //         PdfPCell table_cell;  
    while (query.next()) {
        String produto = query.getString("produto.descricao");
        LogTable.addCell(new Paragraph(produto, fonteDados));
        String quantidade = query.getString("qtdePedido");
        LogTable.addCell(new Paragraph(quantidade, fonteDados));
        String vlrSugerido = query.getString("vlrUnitario");
        LogTable.addCell(new Paragraph(vlrSugerido, fonteDados));
        String vlrTotal = query.getString("vlrTotal");
        LogTable.addCell(new Paragraph(vlrTotal, fonteDados));
    }
    /* Attach report table to PDF */
    PDFLogReport.add(LogTable);
    double valor = pedidoRegistroList.get(row).getVlrPedido();
    Paragraph paragrafoValor = new Paragraph("Valor R$: " + valor);
    paragrafoValor.setAlignment(Element.ALIGN_RIGHT);
    PDFLogReport.add(paragrafoValor);

    PDFLogReport.close();
    /* Close all DB related objects */
    query.close();
    stmt.close();
    con.close();
    String file;
    file = "C:\\Users\\Leonardo P Souza\\Desktop\\Relat\\Pedidos " + id + ".pdf";
    Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file);
}

From source file:Capa_Modelo.Reportes.java

public void generarReporteInventario() {
    Connection con;/*from w  ww.  j  a  va 2s  . c om*/
    ResultSet res;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Cantidad, Cantidadmin,  Cantidadmax, Medicamento.Nombre, Medicamento.FechaElaboracion, Medicamento.Composicion, Medicamento.FechaVencimiento, Medicamento.Laboratorio FROM Inventario inner join Medicamento on Inventario.ID_Medicamento = Medicamento.ID_Medicamento ");
        PdfWriter.getInstance(documento, new FileOutputStream(
                "reportes/reporte_de_inventario " + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2, 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Medicamentos", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(8);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Composicion");
            table.addCell("Laboratorio");
            table.addCell("Fecha de Elaboracion");
            table.addCell("Fecha de Vencimiento");
            table.addCell("Cantidad minima");
            table.addCell("Cantidad actual");
            table.addCell("Cantidad maxima");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            table.addCell(res.getString("Nombre"));
            table.addCell(res.getString("Composicion"));
            table.addCell(res.getString("Laboratorio"));
            table.addCell(res.getString("FechaElaboracion"));
            table.addCell(res.getString("FechaVencimiento"));
            table.addCell(res.getString("Cantidadmin"));
            table.addCell(res.getString("Cantidad"));
            table.addCell(res.getString("Cantidadmax"));
        }
        documento.add(table);
        documento.close();
        JOptionPane.showMessageDialog(null, "Reporte de Inventario generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error al conectar con la base de datos");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar la ruta del archivo");
    } catch (DocumentException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar el archivo");
    }

}

From source file:Capa_Modelo.Reportes.java

public void generarReporteVencimiento() {
    Connection con;//from  w w  w  .  ja v a  2  s. c om
    ResultSet res;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Cantidad, Cantidadmin, Cantidadmax, Medicamento.Nombre, Medicamento.FechaElaboracion, Medicamento.FechaVencimiento, Medicamento.Laboratorio FROM Inventario inner join Medicamento on Inventario.ID_Medicamento = Medicamento.ID_Medicamento ");
        PdfWriter.getInstance(documento, new FileOutputStream(
                "reportes/reporte_de_vencimiento " + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Vencimiento", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(4);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Laboratorio");
            table.addCell("Fecha de Vencimiento");
            table.addCell("Cantidad actual");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            if (vencido(res.getDate("FechaVencimiento"))) {
                table.addCell(res.getString("Nombre"));
                table.addCell(res.getString("Laboratorio"));
                table.addCell(res.getString("FechaVencimiento"));
                table.addCell(res.getString("Cantidad"));
            }
        }
        documento.add(table);
        documento.close();
        JOptionPane.showMessageDialog(null, "Reporte de Vencimiento generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error en conectar con base de datos");
    } catch (DocumentException ex) {
        Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, "El documento no se pudo generar");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reportes.class.getName()).log(Level.SEVERE, null, "EL archivo no se abri");
    }
}

From source file:Capa_Modelo.Reportes.java

public void generarReporteConsumoMedicamentos() {
    DecimalFormat df = new DecimalFormat("####0.00");
    Connection con;/*from   ww  w. j  av a  2  s .  c o  m*/
    ResultSet res;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    double consumo, cantidad;
    double porcentaje;
    consumo = cantidad = 0;
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio, Inventario.Cantidad, SUM(MedicinaPaciente.Cantidad) as Consumo FROM MedicinaPaciente INNER JOIN Medicamento ON MedicinaPaciente.ID_Medicamento = Medicamento.ID_Medicamento INNER JOIN Inventario ON MedicinaPaciente.ID_Medicamento = Inventario.ID_Medicamento  GROUP BY Medicamento.Nombre, Medicamento.Composicion , Medicamento.Laboratorio, Inventario.Cantidad ORDER BY Consumo");
        PdfWriter.getInstance(documento, new FileOutputStream(
                "reportes/reporte_de_consumo_medicamentos " + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Consumo Medicamentos", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(8);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Composicion");
            table.addCell("Laboratorio");
            table.addCell("Cantidad");
            table.addCell("Unidades consumidas");
            table.addCell("Porcentaje de consumo");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            consumo = res.getInt("Consumo");
            cantidad = res.getInt("Cantidad");
            porcentaje = consumo / cantidad * 100;
            System.out.println("consumo: " + consumo + " cantidad: " + cantidad + " porcentaje: " + porcentaje);
            table.addCell(res.getString("Nombre"));
            table.addCell(res.getString("Composicion"));
            table.addCell(res.getString("Laboratorio"));
            table.addCell(res.getString("Cantidad"));
            table.addCell(res.getString("Consumo"));
            table.addCell(((df.format(porcentaje))) + "%");

        }
        documento.add(table);
        documento.close();
        JOptionPane.showMessageDialog(null, "Reporte de Consumo de Medicamentos generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error al conectar con la base de datos");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar la ruta del archivo");
    } catch (DocumentException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar el archivo");
    }
}

From source file:Capa_Modelo.Reportes.java

public void generarReporteESMedicamentos() {
    Connection con;//from   w w w  .j  a v  a2s  .co  m
    ResultSet res, res2;
    Statement sentencia;
    Document documento = new Document(PageSize.A4);
    con = ConexionDB.GetConnection();
    try {
        sentencia = con.createStatement();
        res = sentencia.executeQuery(
                "SELECT Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio, Medicamento.FechaLlegada, Inventario.Cantidad FROM Medicamento INNER JOIN Inventario ON Medicamento.ID_Medicamento = Inventario.ID_Medicamento ORDER BY Inventario.Cantidad, Medicamento.Nombre desc");
        PdfWriter.getInstance(documento, new FileOutputStream("reportes/reporte_de_entrada-salida_medicamentos "
                + fechaActual() + " " + horaActual() + ".pdf"));
        documento.open();
        float[] columnWidths = { 2, 2, 2, 2, 2 };
        PdfPTable table = new PdfPTable(columnWidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);
        Font f = new Font(Font.FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de Entrada de Medicamentos", f));
        cell.setBackgroundColor(GrayColor.GRAYBLACK);
        cell.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell.setColspan(8);
        table.addCell(cell);
        table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table.addCell("Medicamento");
            table.addCell("Composicion");
            table.addCell("Laboratorio");
            table.addCell("Fecha de Entrada");
            table.addCell("Cantidad");
        }
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res.next()) {
            table.addCell(res.getString("Nombre"));
            table.addCell(res.getString("Composicion"));
            table.addCell(res.getString("Laboratorio"));
            table.addCell(res.getString("FechaLlegada"));
            table.addCell(res.getString("Cantidad"));
        }
        documento.add(table);
        documento.newPage();
        res2 = sentencia.executeQuery(
                "SELECT Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio, MedicinaPaciente.FechaEntrega, SUM(MedicinaPaciente.Cantidad) AS Entregados FROM Medicamento INNER JOIN MedicinaPaciente ON Medicamento.ID_Medicamento = MedicinaPaciente.ID_Medicamento  group by Medicamento.Nombre, Medicamento.Composicion, Medicamento.Laboratorio,MedicinaPaciente.FechaEntrega ORDER BY Entregados");
        float[] columnWidths2 = { 2, 2, 2, 2, 2 };
        PdfPTable table2 = new PdfPTable(columnWidths);
        table2.setWidthPercentage(100);
        table2.getDefaultCell().setUseAscender(true);
        table2.getDefaultCell().setUseDescender(true);
        PdfPCell cell2 = new PdfPCell(new Phrase("Reporte de Salida de Medicamentos", f));
        cell2.setBackgroundColor(GrayColor.GRAYBLACK);
        cell2.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        cell2.setColspan(8);
        table2.addCell(cell2);
        table2.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
        for (int i = 0; i < 2; i++) {
            table2.addCell("Medicamento");
            table2.addCell("Composicion");
            table2.addCell("Laboratorio");
            table2.addCell("Fecha de Salida");
            table2.addCell("Cantidad");
        }
        table2.setHeaderRows(3);
        table2.setFooterRows(1);
        table2.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        table2.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
        while (res2.next()) {
            table2.addCell(res2.getString("Nombre"));
            table2.addCell(res2.getString("Composicion"));
            table2.addCell(res2.getString("Laboratorio"));
            table2.addCell(res2.getString("FechaEntrega"));
            table2.addCell(res2.getString("Entregados"));
        }
        documento.add(table2);
        documento.close();
        JOptionPane.showMessageDialog(null,
                "Reporte de Entrada y Salida de Medicamentos generado correctamente");
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Error al conectar con la base de datos");
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar la ruta del archivo");
    } catch (DocumentException ex) {
        JOptionPane.showMessageDialog(null, "Error al generar el archivo");
    }
}

From source file:cis_690_report.DynamicReporter.java

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

    JFileChooser chooser = new JFileChooser();
    int option = chooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            File3 = chooser.getSelectedFile().getAbsolutePath();
        }//from   ww w.j a  v a2 s . co  m

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

        }

        String line = "";

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

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

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

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

        DecimalFormat df = new DecimalFormat("0.00");

        try {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //create section heading by cell merging

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

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

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

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

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

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

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

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

                        }
                    }

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

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

                chart.draw(graphics2d, rectangle2d);

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

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

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

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

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

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

                    chart.draw(graphics2d, rectangle2d);

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

                    doc.newPage();
                }
            }

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

        }
    }
    // TODO add your handling code here:

}

From source file:cis_690_report.DynamicReporter.java

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

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

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

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

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

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

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

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

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

    }

    String line = "";

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

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

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

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

    DecimalFormat df = new DecimalFormat("0.00");

    try {

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

        //file path

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

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

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

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

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

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

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

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

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

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

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

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

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

        //create section heading by cell merging

        //just some random data to fill 

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

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

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

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

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

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

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

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

                    }
                }

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

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

            chart.draw(graphics2d, rectangle2d);

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

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

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

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

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

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

                chart.draw(graphics2d, rectangle2d);

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

                doc.newPage();
            }
        }

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

    }
    controller.openDocument(Path);
}

From source file:cis_690_report.DynamicReporter.java

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

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

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

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

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

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

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

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

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

    }

    String line = "";

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

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

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

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

    DecimalFormat df = new DecimalFormat("0.00");

    try {

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

        //file path

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

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

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

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

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

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

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

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

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

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

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

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

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

        //create section heading by cell merging

        //just some random data to fill 

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

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

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

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

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

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

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

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

                    }
                }

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

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

            chart.draw(graphics2d, rectangle2d);

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

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

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

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

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

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

                chart.draw(graphics2d, rectangle2d);

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

                doc.newPage();
            }
        }

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

    }
    controller.openDocument(Path);
}