Example usage for com.itextpdf.text Phrase Phrase

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

Introduction

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

Prototype

public Phrase(final float leading, final String string) 

Source Link

Document

Constructs a Phrase with a certain leading and a certain String.

Usage

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w  .  j av  a  2  s  .  com*/
 *
 * @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:controller.DownloadCVServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from w  w w  . j  a  va 2  s  . c om
 * @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 {
    //protect servlet
    HttpSession session = request.getSession();
    Admin loggedInAdmin = (Admin) session.getAttribute("admin");

    //check if admin is logged in
    if (loggedInAdmin == null) {
        response.sendRedirect("login.jsp");
        return;
    }

    String[] appIDs = request.getParameterValues("download");

    ServletOutputStream sOut = response.getOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    //prepare fonts
    Font font = FontFactory.getFont("Arial", 10);

    for (String appIDStr : appIDs) {
        int appID = Integer.parseInt(appIDStr);
        Application application = ApplicationDAO.retrieveByAppID(appID);
        Job job = JobDAO.retrieveJobById(application.getJobID());

        ZipEntry entry = new ZipEntry(application.getFullname() + "_CV.pdf");
        zos.putNextEntry(entry);

        String path = System.getenv("OPENSHIFT_DATA_DIR");

        if (path == null) {
            path = getServletContext().getRealPath("/templates/Personal_Particulars_Form.pdf");
        } else {
            path += "Personal_Particulars_Form.pdf";
        }

        try {
            //Prepare PdfStamper
            PdfReader reader = new PdfReader(path);
            PdfStamper stamper = new PdfStamper(reader, zos);
            stamper.setRotateContents(false);
            stamper.getWriter().setCloseStream(false);

            //Get first page
            PdfContentByte canvas = stamper.getOverContent(1);

            //Application ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getAppID() + "", font), 110, 555, 0);

            //Date Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getDateApplied(), font), 110, 526, 0);

            //Position Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(job.getPostingTitle(), font), 36,
                    442, 0);

            //Job ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getJobID() + "", font), 405, 442, 0);

            //Name
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getFullname(), font),
                    36, 350, 0);

            //Street
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getBlkStreetUnit(), font), 36, 305, 0);

            //Postal Code
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getPostalCode(), font), 377, 305, 0);

            //Nationality
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNricType(), font),
                    36, 260, 0);

            //NRIC
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNric(), font), 289,
                    260, 0);

            //DOB
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getDob(), font), 36,
                    215, 0);

            //Gender
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getGender(), font),
                    379, 215, 0);

            //Contact Number
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getContactNo(), font),
                    36, 170, 0);

            //Email Address
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getEmailAddress(), font), 36, 125, 0);

            //Declaration
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("X", font), 50, 80, 0);

            //Generated on
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
            Date date = new Date();
            String today = dateFormat.format(date);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(today, font), 437, 15, 0);

            stamper.close();
            reader.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    zos.close();
    response.setContentType("application/zip");
    response.addHeader("Content-Disposition", "attachment; filename=CVs.zip");

    sOut.write(baos.toByteArray());
    sOut.close();
}

From source file:controller.pdf.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww.  ja v a  2  s. c om
 *
 * @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("application/pdf");

    OutputStream out = response.getOutputStream();

    try {

        String especialidad = request.getParameter("especialidad");
        String turno = request.getParameter("turno");
        String dia = request.getParameter("dia");

        Document documento = new Document();
        documento.setPageSize(PageSize.A4);
        documento.setPageSize(PageSize.A4.rotate());

        //                Rectangle one = new Rectangle(70,140);
        //                documento.setPageSize(one);
        //                documento.setMargins(2, 2, 2, 2);

        PdfWriter.getInstance(documento, out);

        documento.open();

        Paragraph par1 = new Paragraph();
        Font fonttitulo = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD, BaseColor.BLACK);
        if (turno.equalsIgnoreCase("M")) {
            par1.add(new Phrase("Citas del dia: " + dia + " Turno Maana", fonttitulo));
        } else {
            par1.add(new Phrase("Citas del dia: " + dia + " Turno Tarde", fonttitulo));
        }

        par1.setAlignment(Element.ALIGN_CENTER);
        par1.add(new Phrase(Chunk.NEWLINE));
        par1.add(new Phrase(Chunk.NEWLINE));
        par1.add(new Phrase(Chunk.NEWLINE));
        documento.add(par1);

        PdfPTable tabla = new PdfPTable(9);
        PdfPCell celda1 = new PdfPCell(
                new Paragraph("Codigo Cita", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda2 = new PdfPCell(
                new Paragraph("Especialidad", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda3 = new PdfPCell(
                new Paragraph("Codigo Paciente", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda4 = new PdfPCell(new Paragraph("Nombre", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda5 = new PdfPCell(
                new Paragraph("Apellido Paterno", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda6 = new PdfPCell(
                new Paragraph("Apellido Materno", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda7 = new PdfPCell(new Paragraph("Hora", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda8 = new PdfPCell(new Paragraph("Doctor", FontFactory.getFont("Arial", 12, Font.BOLD)));
        PdfPCell celda9 = new PdfPCell(new Paragraph("Da", FontFactory.getFont("Arial", 12, Font.BOLD)));

        tabla.addCell(celda1);
        tabla.addCell(celda2);
        tabla.addCell(celda3);
        tabla.addCell(celda4);
        tabla.addCell(celda5);
        tabla.addCell(celda6);
        tabla.addCell(celda7);
        tabla.addCell(celda8);
        tabla.addCell(celda9);

        try {

            Connection conex = conexion.obtener();

            PreparedStatement consulta2 = conex.prepareStatement("call pacientegeneral_select();");
            ResultSet resultado2 = consulta2.executeQuery();

            while (resultado2.next()) {

                PreparedStatement consulta = conex.prepareStatement("call cita_select();");
                ResultSet resultado = consulta.executeQuery();

                while (resultado.next()) {

                    if (turno.equalsIgnoreCase("M") && resultado.getString(4).charAt(6) == 'A'
                            && resultado.getInt(3) == resultado2.getInt(1)
                            && resultado.getString(7).equalsIgnoreCase(dia)
                            && resultado.getString(2).equalsIgnoreCase(especialidad)) {

                        tabla.addCell(resultado.getString(1));
                        tabla.addCell(resultado.getString(2));
                        tabla.addCell(resultado2.getString(1));
                        tabla.addCell(resultado2.getString(2));
                        tabla.addCell(resultado2.getString(3));
                        tabla.addCell(resultado2.getString(4));
                        tabla.addCell(resultado.getString(4));
                        tabla.addCell(resultado.getString(5));
                        tabla.addCell(resultado.getString(7));

                    }

                }
            }

            conexion.cerrar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.toString());
        }

        try {

            Connection conex = conexion.obtener();

            PreparedStatement consulta2 = conex.prepareStatement("call pacientegeneral_select();");
            ResultSet resultado2 = consulta2.executeQuery();

            while (resultado2.next()) {

                PreparedStatement consulta = conex.prepareStatement("call cita_select();");
                ResultSet resultado = consulta.executeQuery();

                while (resultado.next()) {

                    if (turno.equalsIgnoreCase("T") && resultado.getString(4).charAt(6) == 'P'
                            && resultado.getInt(3) == resultado2.getInt(1)
                            && resultado.getString(7).equalsIgnoreCase(dia)
                            && resultado.getString(2).equalsIgnoreCase(especialidad)) {

                        tabla.addCell(resultado.getString(1));
                        tabla.addCell(resultado.getString(2));
                        tabla.addCell(resultado2.getString(1));
                        tabla.addCell(resultado2.getString(2));
                        tabla.addCell(resultado2.getString(3));
                        tabla.addCell(resultado2.getString(4));
                        tabla.addCell(resultado.getString(4));
                        tabla.addCell(resultado.getString(5));
                        tabla.addCell(resultado.getString(7));

                    }

                }
            }

            conexion.cerrar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.toString());
        }

        float[] columnWidths = new float[] { 15f, 30f, 18f, 23f, 23f, 23f, 20f, 25f, 18f };
        tabla.setWidths(columnWidths);

        documento.add(tabla);
        documento.close();

    } catch (Exception ex) {
        ex.getMessage();
    }

    String redirectURL = "citasemana.jsp";
    response.sendRedirect(redirectURL);

}

From source file:controller.pdfcita.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w.  j ava  2s .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("application/pdf");

    OutputStream out = response.getOutputStream();

    String codigocita = request.getParameter("codigocita");
    String nombre = request.getParameter("nombre");
    String especialidad = request.getParameter("especialidad");
    String fecha = request.getParameter("fecha");
    String hora = request.getParameter("hora");
    String doctor = request.getParameter("doctor");

    try {

        try {

            Document documento = new Document();
            Rectangle one = new Rectangle(400, 280);
            documento.setPageSize(one);
            PdfWriter.getInstance(documento, out);

            documento.open();

            Paragraph par1 = new Paragraph();
            Font fontitulo = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);
            par1.add(new Phrase("Cita", fontitulo));
            par1.setAlignment(Element.ALIGN_CENTER);
            par1.add(new Phrase(Chunk.NEWLINE));
            par1.add(new Phrase(Chunk.NEWLINE));
            documento.add(par1);

            Paragraph par2 = new Paragraph();
            Font fontescrip = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL, BaseColor.BLACK);
            par2.add(
                    new Phrase("LUGAR DE CONSULTA :  POLICL?NICO NUESTRA SEORA DE LOS ANGELES", fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("CODIGO DE CITA :  " + codigocita, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("PACIENTE :  " + nombre, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("ESPECIALIDAD :  " + especialidad, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("FECHA :  " + fecha, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("HORA DE CITA :  " + hora, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("DOCTOR(A) :  " + doctor, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("COSTO DE CITA :  10.00 SOLES", fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase(
                    "El paciente tendr que imprimir esta cita y acercarse a caja para cancelar el monto de la cita para posteriormente acudir a su cita en el consultorio establecido en el recibo.",
                    fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            //par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase(
                    "                                                                                                                      - Administracin",
                    fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.setAlignment(Element.ALIGN_JUSTIFIED);
            documento.add(par2);

            documento.close();

        } catch (Exception ex) {
            ex.getMessage();
        }

    } finally {
        out.close();
    }

    ////            try{
    //                
    //                
    //                
    //                Document document = new Document();
    //                Rectangle one = new Rectangle(70,140);
    //                document.setPageSize(one);
    //                
    //                document.open();
    //                Paragraph par1=new Paragraph();
    //                Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK);   
    //                
    //                par1.add(new Phrase("Citas del dia: Turno Maana",fonttitulo)); 
    //                document.add(par1);
    //                
    //                
    //                
    //                
    ////                Paragraph p = new Paragraph("Hi");
    ////                document.add(p);
    ////                document.setPageSize(two);
    ////                document.setMargins(20, 20, 20, 20);
    ////                document.newPage();
    ////                document.add(p);
    //                document.close();
    //                
    //                
    //                
    ////                String especialidad=request.getParameter("especialidad");
    ////                String turno=request.getParameter("turno");
    ////                String dia=request.getParameter("dia");
    //                
    ////                Document documento=new Document();
    ////                documento.setPageSize(PageSize.A4);
    ////                documento.setPageSize(PageSize.A4.rotate());
    ////                PdfWriter.getInstance(documento, out);
    ////                
    ////                documento.open();
    //                
    ////                Paragraph par1=new Paragraph();
    ////                Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK);
    ////                if (turno.equalsIgnoreCase("M")) {
    ////                par1.add(new Phrase("Citas del dia: "+dia+" Turno Maana",fonttitulo));    
    ////                }
    ////                else{par1.add(new Phrase("Citas del dia: "+dia+" Turno Tarde",fonttitulo));}
    ////                
    ////                
    ////                par1.setAlignment(Element.ALIGN_CENTER);
    ////                par1.add(new Phrase(Chunk.NEWLINE));
    ////                par1.add(new Phrase(Chunk.NEWLINE));
    ////                documento.add(par1);
    ////                
    ////                PdfPTable tabla=new PdfPTable(9);
    ////                PdfPCell celda1=new PdfPCell(new Paragraph("Codigo Cita",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda2=new PdfPCell(new Paragraph("Especialidad",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda3=new PdfPCell(new Paragraph("Codigo Paciente",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda4=new PdfPCell(new Paragraph("Nombre",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda5=new PdfPCell(new Paragraph("Apellido Paterno",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda6=new PdfPCell(new Paragraph("Apellido Materno",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda7=new PdfPCell(new Paragraph("Hora",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda8=new PdfPCell(new Paragraph("Doctor",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda9=new PdfPCell(new Paragraph("Da",FontFactory.getFont("Arial", 12, Font.BOLD)));
    //                
    ////                tabla.addCell(celda1);
    ////                tabla.addCell(celda2);
    ////                tabla.addCell(celda3);
    ////                tabla.addCell(celda4);
    ////                tabla.addCell(celda5);
    ////                tabla.addCell(celda6);
    ////                tabla.addCell(celda7);
    ////                tabla.addCell(celda8);
    ////                tabla.addCell(celda9);
    ////                
    ////                try{
    ////                    
    ////                              Connection conex=conexion.obtener();
    ////                                
    ////                            PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();");
    ////                            ResultSet resultado2=consulta2.executeQuery();
    ////                            
    ////                            while(resultado2.next()){
    ////                                
    ////                                PreparedStatement consulta=conex.prepareStatement("call cita_select();");
    ////                            ResultSet resultado=consulta.executeQuery();
    ////                                
    ////                            while(resultado.next()){
    ////                                
    ////                                if (turno.equalsIgnoreCase("M") && resultado.getString(4).charAt(6)=='A' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) {
    ////
    ////                                    tabla.addCell(resultado.getString(1));
    ////                                    tabla.addCell(resultado.getString(2));
    ////                                    tabla.addCell(resultado2.getString(1));
    ////                                    tabla.addCell(resultado2.getString(2));
    ////                                    tabla.addCell(resultado2.getString(3));
    ////                                    tabla.addCell(resultado2.getString(4));
    ////                                    tabla.addCell(resultado.getString(4));
    ////                                    tabla.addCell(resultado.getString(5));
    ////                                    tabla.addCell(resultado.getString(7));
    ////                                    
    ////                                    }
    ////                                
    ////                            }    
    ////                            }
    ////                            
    ////                        conexion.cerrar();
    ////                        }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());}
    //                
    //                
    //                
    //                
    ////                try{
    ////                    
    ////                              Connection conex=conexion.obtener();
    ////                                
    ////                            PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();");
    ////                            ResultSet resultado2=consulta2.executeQuery();
    ////                            
    ////                            while(resultado2.next()){
    ////                                
    ////                                PreparedStatement consulta=conex.prepareStatement("call cita_select();");
    ////                            ResultSet resultado=consulta.executeQuery();
    ////                                
    ////                            while(resultado.next()){
    ////                                
    ////                                if (turno.equalsIgnoreCase("T") && resultado.getString(4).charAt(6)=='P' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) {
    ////
    ////                                    tabla.addCell(resultado.getString(1));
    ////                                    tabla.addCell(resultado.getString(2));
    ////                                    tabla.addCell(resultado2.getString(1));
    ////                                    tabla.addCell(resultado2.getString(2));
    ////                                    tabla.addCell(resultado2.getString(3));
    ////                                    tabla.addCell(resultado2.getString(4));
    ////                                    tabla.addCell(resultado.getString(4));
    ////                                    tabla.addCell(resultado.getString(5));
    ////                                    tabla.addCell(resultado.getString(7));
    ////                                    
    ////                                    }
    ////                                
    ////                            }    
    ////                            }
    ////                            
    ////                        conexion.cerrar();
    ////                        }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());}
    //                
    //                
    //                
    //                
    //                
    //                
    ////            float[] columnWidths = new float[]{15f, 30f, 18f, 23f, 23f, 23f, 20f, 25f, 18f};
    ////                tabla.setWidths(columnWidths);
    ////                
    ////                            documento.add(tabla);
    //                            document.close();    
    //                
    //            }catch(Exception ex){ex.getMessage();}
    //            
    //            String redirectURL="principal.jsp";
    ////            response.sendRedirect(redirectURL);

}

From source file:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {//from  ww w  . ja v  a2s.  com

        DonHang donhang = new DonHang();
        donhang.init(maDH);
        float CONVERT = 28.346457f;// 1 cm
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Content-disposition","inline; filename=kiran.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\"");
        response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\"");
        //step 1: creation of a document-object
        Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT,
                1.0f * CONVERT);
        //step 2: we create a writer that listens to the document
        // and directs a PDF-stream to a temporary buffer
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        Font font = new Font(bf, 18, Font.BOLD);
        Font font11 = new Font(bf, 11, Font.NORMAL);
        Font font11_bo = new Font(bf, 11, Font.BOLD);
        Font font12 = new Font(bf, 12, Font.NORMAL);
        Font font10 = new Font(bf, 10, Font.NORMAL);
        Font font9 = new Font(bf, 9, Font.NORMAL);
        //step 3: we open the document
        document.open();

        PdfPTable tab_Header1;
        tab_Header1 = new PdfPTable(1);
        tab_Header1.setWidthPercentage(100);

        tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell1;
        cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn:....................................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);
        ///////////////////////////////bn sn phm
        float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT };

        PdfPTable tab_Header2;
        tab_Header2 = new PdfPTable(crDonHang.length);
        tab_Header2.setWidthPercentage(100);
        tab_Header2.setWidths(crDonHang);
        tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER);
        NumberFormat formatter = new DecimalFormat("#,###,###");

        String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" };

        for (int i = 0; i < crheader.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);
        }
        int stt = 1;
        for (SanPhamDH sp : donhang.getListSP()) {

            PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getTenSP(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getSoluong(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            stt++;
        }
        cell1 = new PdfPCell(tab_Header2);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n hng:   "
                + formatter.format(
                        Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn:   "
                + formatter.format(Double
                        .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton:   "
                + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: "
                + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy      thng       nm       ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingRight(1.0f * CONVERT);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        PdfPTable tab_Header3;
        tab_Header3 = new PdfPTable(3);
        tab_Header3.setWidthPercentage(100);

        tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(tab_Header3);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        document.add(tab_Header1);

        document.close();
        //step 6: we output the writer as bytes to the response output
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        baos.flush();
        faces.responseComplete();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Controllers.ExportController.java

public static void exportExam(String path) {
    model = (DefaultTableModel) tableExam.getModel();
    int selectRow = tableExam.getSelectedRow();

    if (selectRow != -1) {
        int idExam = (int) model.getValueAt(selectRow, 0) - 1;
        exams = ExamModel.readExam();/* www.  j a va 2  s.  c  om*/
        Exam ex = exams.getExam(idExam);

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(path));
            document.open();
            BaseFont f = BaseFont.createFont("/font/vuArial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font titleExamFont = new Font(f, 25.0f, Font.BOLD);
            Font titlePartFont = new Font(f, 18.0f, Font.BOLD);
            Font headFont = new Font(f, 13.0f, Font.BOLD);
            Font suggestionFont = new Font(f, 13.0f, Font.ITALIC);
            Font contentFont = new Font(f, 13.0f, Font.NORMAL);
            Paragraph align = new Paragraph(" ");
            Paragraph title = new Paragraph(ex.getNameExam(), titleExamFont);
            title.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(title);
            document.add(align);

            ArrayList<Question> question = ex.getQuestions();

            boolean haveMultipleChoice = false;
            boolean haveEssay = false;
            // Kim tra xem c phn t lun khng
            for (Question q : question) {
                if (q instanceof Essay) {
                    haveEssay = true;
                }
                // Kim tra xem c phn trc nghim khng}
                else {
                    haveMultipleChoice = true;
                }
                if (haveEssay && haveMultipleChoice)
                    break;
            }

            int count;
            if (haveMultipleChoice) {
                count = 0;
                Paragraph titlePart = new Paragraph("Trc nghim", titlePartFont);
                document.add(align);
                document.add(titlePart);
                document.add(align);
                for (Question q : question)
                    if (q instanceof MultipleChoice) {
                        count++;
                        Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont);
                        Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont);
                        Paragraph questionParagraph = new Paragraph();
                        questionParagraph.add(numberQuestion);
                        questionParagraph.add(contentQuestion);
                        document.add(questionParagraph);

                        MultipleChoice mc = (MultipleChoice) q;
                        ArrayList<Answer> answers = mc.getAnswers();

                        boolean ok = true;
                        for (int i = 0; i < answers.size(); ++i) {
                            Answer answer = answers.get(i);
                            if (answer.getContentAnswer().length() > 30)
                                ok = false;
                        }

                        if (ok == true) {
                            PdfPTable table = new PdfPTable(2);
                            for (int i = 0; i < answers.size(); ++i) {
                                Answer answer = answers.get(i);
                                PdfPCell answerParagraph = new PdfPCell(new Paragraph(
                                        (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont));
                                answerParagraph.setBorder(Rectangle.NO_BORDER);
                                table.addCell(answerParagraph);
                            }
                            document.add(table);
                        } else {
                            PdfPTable table = new PdfPTable(1);
                            for (int i = 0; i < answers.size(); ++i) {
                                Answer answer = answers.get(i);
                                PdfPCell answerParagraph = new PdfPCell(new Paragraph(
                                        (char) (65 + i) + ". " + answer.getContentAnswer(), contentFont));
                                answerParagraph.setBorder(Rectangle.NO_BORDER);
                                table.addCell(answerParagraph);
                            }
                            document.add(table);
                        }
                    }
            }

            if (haveEssay) {
                count = 0;
                Paragraph titlePart = new Paragraph("T Lun", titlePartFont);
                document.add(align);
                document.add(titlePart);
                document.add(align);
                for (Question q : question)
                    if (q instanceof Essay) {
                        count++;
                        Phrase numberQuestion = new Phrase("Cu " + count + ": ", headFont);
                        Phrase contentQuestion = new Phrase(q.getContentQuestion(), contentFont);
                        Paragraph questionParagraph = new Paragraph();
                        questionParagraph.add(numberQuestion);
                        questionParagraph.add(contentQuestion);

                        Essay es = (Essay) q;
                        Phrase headerSuggestion = new Phrase("Gi : ", suggestionFont);
                        Phrase contentSuggestion = new Phrase(es.getSuggest(), contentFont);
                        Paragraph suggestion = new Paragraph();
                        suggestion.add(headerSuggestion);
                        suggestion.add(contentSuggestion);
                        document.add(questionParagraph);
                        document.add(suggestion);
                    }
            }

            document.close();
        } catch (FileNotFoundException exp) {
            exp.printStackTrace();
        } catch (DocumentException exp) {
            exp.printStackTrace();
        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }
}

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  w  w.  j a va2  s .co  m*/
        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:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Writes the logos and the address of the institute.
 *///w w  w .ja v  a  2  s.  com
private void writeLogo() {
    try {
        Font generatedByFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 8);
        Image aidger = Image.getInstance(getClass().getResource("/de/aidger/res/pdf/AidgerLogo.png"));
        aidger.scaleAbsolute(80.0f, 20.0f);
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(reader.getPageSize(1).getRight());
        PdfPCell cell = new PdfPCell(new Phrase(_("Generated by: "), generatedByFont));
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setPaddingBottom(5);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        table.addCell(cell);
        cell = new PdfPCell(Image.getInstance(aidger));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(0);
        table.addCell(cell);
        table.writeSelectedRows(0, -1, 0, 25, contentByte);
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Creates the table of employments./*from   w w w . j av  a  2 s  .  co m*/
 */
private void createTable() {
    try {
        Font tableTitleFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 10);
        String[] tableTitles = { "Zeitraum", "Veranstaltung", "Umfang" };
        PdfPTable contentTable = new PdfPTable(1);
        PdfPTable titleTable = new PdfPTable(new float[] { 0.2f, 0.6f, 0.2f });
        /*
         * Create the titles of the table entries.
         */
        for (int i = 0; i < tableTitles.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(tableTitles[i], tableTitleFont));
            titleTable.addCell(cell);
        }
        PdfPCell cell = new PdfPCell(titleTable);
        cell.setPaddingTop(10.0f);
        cell.setPaddingBottom(2.0f);
        cell.setBorder(0);
        contentTable.addCell(cell);
        cell = new PdfPCell(addRows());
        cell.setBorder(0);
        contentTable.addCell(cell);
        float xPos = 60, yPos = 500, width = reader.getPageSize(1).getWidth() - 120f;
        if (form.getFieldPositions("TableField") != null) {
            FieldPosition position = form.getFieldPositions("TableField").get(0);
            xPos = position.position.getLeft();
            yPos = position.position.getTop();
            width = position.position.getWidth();
        }
        contentTable.setTotalWidth(width);
        contentTable.writeSelectedRows(0, -1, xPos, yPos, contentByte);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Adds the rows of employments to the table.
 *//*from  w w  w.j a va2s.  c o m*/
private PdfPTable addRows() {
    PdfPTable contentTable = new PdfPTable(new float[] { 0.2f, 0.6f, 0.2f });
    try {
        Font tableContentFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 9);
        for (String[] row : tableRows) {
            for (int i = 0; i < row.length; i++) {
                PdfPCell cell = new PdfPCell(new Phrase(row[i], tableContentFont));
                cell.setPaddingBottom(5);
                contentTable.addCell(cell);
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return contentTable;
}