Example usage for com.itextpdf.text.pdf PdfPTable getDefaultCell

List of usage examples for com.itextpdf.text.pdf PdfPTable getDefaultCell

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable getDefaultCell.

Prototype

public PdfPCell getDefaultCell() 

Source Link

Document

Gets the default PdfPCell that will be used as reference for all the addCell methods except addCell(PdfPCell).

Usage

From source file:Control.ProcessaArq.java

public void gravaArquivoConsumoUsuarios(ArrayList<Usuario> lista, String caminho)
        throws IOException, DocumentException {

    Document doc = null;/*w  w w . j av  a 2 s. co m*/
    OutputStream os = null;
    Paragraph p = new Paragraph();
    Tratamento tempo = new Tratamento();
    DecimalFormat df = new DecimalFormat("#####.##");
    String informacao, tipo = new String();
    Double soma, valorTotal = 0.0;

    PdfPTable table = new PdfPTable(5); //tabela com 5 colunas
    float[] headerwidths = { 30, 80, 35, 35, 25 }; // define a largura de cada coluna  
    table.setWidths(headerwidths);

    caminho = localizaArquivo(false) + ".pdf";
    try {//configuraes da pgina          
        float fntSize, lineSpacing;
        fntSize = 8f;
        lineSpacing = 8f;
        doc = new Document(PageSize.A4.rotate(), 10, 10, 30, 40);

        os = new FileOutputStream(caminho);
        PdfWriter.getInstance(doc, os);
        doc.open();

        //cabecalho da tabela
        table.getDefaultCell().setBorder(0);
        table.getWidthPercentage();

        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table.getDefaultCell().setColspan(5);

        table.addCell(new Paragraph("CONSUMO POR USU?RIOS ") + banco.periodoFatura());

        table.getDefaultCell().setBorder(1);
        table.getDefaultCell().setColspan(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);

        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.addCell(new Paragraph(""));
        table.getDefaultCell().setBorder(1);

        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(new Paragraph("Cidade"));
        table.addCell(new Paragraph("Usurio"));
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(new Paragraph("Nmero"));
        table.addCell(new Paragraph("Tipo"));
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        table.addCell(new Paragraph("Valor"));
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

        soma = 0.0;
        for (int a = 0; a <= lista.size() - 1; a++) {

            //cidade
            informacao = new String();
            informacao = lista.get(a).getCidade();
            //    table.setTotalWidth(80);
            table.addCell(new Paragraph(informacao));

            //Usurio
            informacao = new String();
            informacao = lista.get(a).getNome();
            //    table.setTotalWidth(200);
            table.addCell(new Paragraph(informacao));

            //Nmero
            informacao = new String();
            informacao = String.valueOf(lista.get(a).getLinha());
            //    table.setTotalWidth(10);
            table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            table.addCell(new Paragraph(informacao));

            //Tipo
            informacao = new String();
            informacao = lista.get(a).getTipo();
            //    table.setTotalWidth(10);
            table.addCell(new Paragraph(informacao));

            //Valor
            informacao = new String();
            soma += lista.get(a).getValor();
            informacao = "R$" + df.format(lista.get(a).getValor());
            //    table.setTotalWidth(10);
            table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            table.addCell(new Paragraph(informacao));
        }

        // Total
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        informacao = new String();
        informacao = "Total";
        table.addCell(informacao);

        // tempo                               
        table.addCell("");
        table.addCell("");
        table.addCell("");

        // valor
        informacao = new String();
        informacao = "R$" + df.format(soma);
        table.addCell(informacao);
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

        doc.add(table);
        // fim da pgina
    } finally {
        if (doc != null) {
            //fechamento do documento
            doc.close();
        }
        if (os != null) {
            //fechamento da stream de sada
            os.close();
        }
    }
}

From source file:Control.ProcessaArq.java

public void gravaArquivoServicos(ArrayList<Conta> lista, String caminho) throws IOException, DocumentException {
    ArrayList<String> listaTipos;
    String local[];//from w  w  w. j ava 2  s .  c  om
    Document doc = null;
    OutputStream os = null;
    Paragraph p = new Paragraph();
    Tratamento tempo = new Tratamento();
    DecimalFormat df = new DecimalFormat("#####.##");
    String informacao, tempoServico, tempoSubTotal, tempoTotal, tipo = new String();
    Double soma, valorTotal = 0.0;

    PdfPTable table = new PdfPTable(3); //tabela com 3 colunas
    float[] headerwidths = { 85, 35, 25 }; // define a largura de cada coluna
    table.setWidths(headerwidths);

    caminho = localizaArquivo(false) + ".pdf";
    try {//configuraes da pgina          
        float fntSize, lineSpacing;
        fntSize = 10f;
        lineSpacing = 10f;
        doc = new Document(PageSize.A4.rotate(), 10, 10, 20, 10);

        os = new FileOutputStream(caminho);
        PdfWriter.getInstance(doc, os);
        doc.open();

        tempoTotal = "00:00:00";
        tempoServico = "00:00:00";
        tempoSubTotal = "00:00:00";
        listaTipos = new ArrayList<String>();

        //cabecalho da tabela
        table.getDefaultCell().setBorder(0);
        table.getWidthPercentage();

        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        table.getDefaultCell().setColspan(3);

        table.addCell(new Paragraph(tempo.verificaNomeServico(lista) + " " + banco.periodoFatura()));

        table.getDefaultCell().setBorder(1);
        table.getDefaultCell().setColspan(0);
        table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);

        for (int a = 0; a < lista.size() - 1; a++) {
            System.out.println(a + " - " + lista.get(a).getTipo());

            if (!listaTipos.contains(lista.get(a).getTipo())) {

                listaTipos.add(lista.get(a).getTipo());
                soma = 0.0;
                tipo = new String();
                informacao = new String();

                informacao = "" + listaTipos.get(listaTipos.size() - 1) + "";
                table.getDefaultCell().setBorder(1);
                table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                table.getDefaultCell().setColspan(3);
                table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);

                table.addCell(new Paragraph(informacao));

                table.getDefaultCell().setBorder(1);
                table.getDefaultCell().setColspan(0);
                table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);

                // contedo da tabela
                for (int b = 0; b <= lista.size() - 1; b++) {
                    if (lista.get(b).getTipo().equals(listaTipos.get(listaTipos.size() - 1))) {

                        soma += lista.get(b).getValor();
                        tempoServico = tempo.somaTempo(lista.get(b).getDuracao(), tempoServico);
                        tempoSubTotal = tempo.somaTempo(tempoServico, tempoSubTotal);
                        tempoTotal = tempo.somaTempo(tempoServico, tempoTotal);
                        tipo = listaTipos.get(listaTipos.size() - 1);

                        informacao = new String();
                        informacao = lista.get(b).getDescricaoServico();
                        table.setTotalWidth(80);
                        table.addCell(new Paragraph(informacao));

                        informacao = new String();
                        informacao = tempoServico + " (" + tempo.conversaoHoraMinuto(tempoServico) + ")";
                        table.setTotalWidth(30);
                        table.addCell(new Paragraph(informacao));

                        informacao = new String();
                        informacao = "R$" + df.format(lista.get(b).getValor());
                        table.setTotalWidth(20);
                        table.addCell(new Paragraph(informacao));

                        tempoServico = "00:00:00";
                        //    System.out.println(informacao);                                 
                    }
                }
                //rodap da tabela
                listaTipos.add(tipo);
                valorTotal += soma;

                // subtotal
                table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                informacao = new String();
                informacao = "Sub Total:";
                table.addCell(informacao);

                // tempo
                informacao = new String();
                informacao = tempoSubTotal + " (" + tempo.conversaoHoraMinuto(tempoSubTotal) + ")";
                table.addCell(informacao);

                // valor
                informacao = new String();
                informacao = "R$" + df.format(soma);
                table.addCell(informacao);
                table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);

                // espao entre tabelas

                table.getDefaultCell().setBorder(1);
                table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                table.getDefaultCell().setColspan(3);
                table.addCell(new Paragraph("* * * * *"));
                table.getDefaultCell().setColspan(0);
                table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                table.getDefaultCell().setBorder(0);

                tempoSubTotal = "00:00:00";
                //    System.out.println(informacao);   
            }
        }
        // fim da pgina

        // valor total
        informacao = new String();
        informacao = "Total Geral:  ";
        table.getDefaultCell().setBorder(1);
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(informacao);
        table.getDefaultCell().setBorder(1);

        // tempo
        informacao = new String();
        informacao = tempoTotal + " (" + tempo.conversaoHoraMinuto(tempoTotal) + ")";
        table.addCell(informacao);

        //valor
        informacao = new String();
        informacao = "R$" + df.format(valorTotal);
        table.addCell(informacao);

        doc.add(table);
        //    System.out.println(informacao);

    } finally {
        if (doc != null) {
            //fechamento do documento
            doc.close();
        }
        if (os != null) {
            //fechamento da stream de sada
            os.close();
        }
    }
}

From source file:Controller.ControllerCompra.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www  .j av  a2 s . co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        //int estado = 0;
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String facturaProveedor = (request.getParameter("txtNumeroFactura"));
            String nombreProveedor = (request.getParameter("txtNombre"));
            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra"));
            listObjDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listObjDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objCompra.setFacturaProveedor(facturaProveedor);
            _objCompra.setNombreProveedor(nombreProveedor);
            _objCompra.setTotalCompra(totalCompra);
            daoModelCompra = new ModelCompra();
            String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos),
                    "La compra ha sido registrada", "Ha ocurrido un error");
            daoModelCompra.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableCompra());
            break;
        }
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iText">
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> compra = (Map) material.get("Compra");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra                        
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n"));
                headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n"));
                headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        //</editor-fold>
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports">
        case "Imprimir2": {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String source = url + "/reports/newReport1.jrxml";
                JasperPrint jasperPrint = null;
                JasperReport jasperReport = null;
                JasperDesign jasperDesign = null;
                System.out.println(source);
                String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml";
                jasperDesign = JRXmlLoader.load(reportPath);
                jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id),
                        daoModelCompra.getConnection());
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            } catch (Exception ex) {
                for (StackTraceElement ruta : ex.getStackTrace()) {
                    System.err.println(ruta);
                }
            }
        }
            break;
        //</editor-fold>

        }
    }

}

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w.  j ava2 s  . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String documentoCliente = null;
            String nombreCliente = null;
            int numeroVenta = 0;
            if (Validador.validarDocumento(request.getParameter("documentoCliente"))
                    & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente"))
                    & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) {
                documentoCliente = (request.getParameter("documentoCliente"));
                nombreCliente = (request.getParameter("txtNombreCliente"));
                numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta"));
            } else {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos"));
                break;
            }

            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta"));
            listOjbDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listOjbDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objVenta.setIdVenta(numeroVenta);
            _objVenta.setDocumentoCliente(documentoCliente);
            _objVenta.setNombreCliente(nombreCliente);
            _objVenta.setTotalVenta(totalCompra);
            daoModelVenta = new ModelVenta();
            String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos),
                    "La venta ha sido registrada", "Ha ocurrido un error");
            daoModelVenta.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableVenta());
            break;
        }
        case "Contador": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getContador());
            break;
        }
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> venta = (Map) material.get("Venta");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra         
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Id. de la Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n"));
                headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n"));
                headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n"));
                headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Venta", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(venta.get("totalVenta")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        }
    }
}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }/*from   w ww  .j  av a2s  . com*/
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable(Paragraph preface, Invoice invoice) {
    PdfPTable table = new PdfPTable(2);

    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    table.addCell("Klantgegevens");
    table.addCell("Bedrijfsgegevens");
    table.addCell(invoice.getClientName());
    table.addCell(invoice.getCompanyName());
    table.addCell(invoice.getClientAddress());
    table.addCell(invoice.getCompanyAddress());
    table.addCell(invoice.getClientPostcodeCity());
    table.addCell(invoice.getCompanyPostcodeCity());
    table.addCell("");
    table.addCell("KVK nummer: " + invoice.getCompanyKVK());
    //table.addCell("");
    //table.addCell("Bankgegevens bedrijf");
    //table.addCell("");
    //table.addCell("BTW-nummer bedrijf");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);/* w  w  w .ja v  a 2 s.c o  m*/
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable2(Paragraph preface, Invoice invoice) {
    PdfPTable table = new PdfPTable(1);

    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    table.addCell(" Factuur nummer: " + invoice.getInvoiceNumber());
    table.addCell(" Factuuratum: " + DateFormatter.dateToString(invoice.getDate()));
    table.addCell(" Vervaldatum: " + DateFormatter.dateToString(invoice.getExpirationDate()));
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);//from ww  w .  ja  v a2s  .  c  o m
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable3(Paragraph preface, Invoice invoice) {
    PdfPTable table = new PdfPTable(4);

    //PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    //cell.setColspan(3);
    // table.addCell(cell);
    table.addCell(" Behandelcode ");
    table.addCell(" Aantal sessies ");
    table.addCell(" Prijs per sessie ");
    table.addCell(" Totaal ");
    table.addCell(invoice.getTreatmentCode());
    table.addCell(invoice.getAmountSessions());
    table.addCell("  " + invoice.getPricePerSession());
    table.addCell("  " + invoice.getTotalPrice().toString());
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);//from   w w w . j a  v  a2  s  .  c  om
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable4(Paragraph preface, Invoice invoice) {
    PdfPTable table = new PdfPTable(2);

    //PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    //cell.setColspan(3);
    // table.addCell(cell);

    table.addCell("Oude eigenrisico");
    table.addCell("Vergoede bedrag");
    table.addCell(" " + invoice.getOldDeductible().toString());
    table.addCell(" " + invoice.getAmountReimbursed());
    table.addCell("Huidige eigenrisco");
    table.addCell("Te betalen");
    table.addCell(" " + invoice.getDeductible().toString());
    table.addCell(" " + invoice.getAmountToPay().toString());
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);//from ww w  .  j av  a 2s. c  om

}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable5(Paragraph preface) {
    PdfPTable table = new PdfPTable(1);

    //PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    //cell.setColspan(3);
    // table.addCell(cell);
    table.addCell("Gelieve te betalen binnen 30 dagen");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);//from w  w w  .  ja  v  a  2 s .  c o  m
}