Example usage for com.itextpdf.text Paragraph setAlignment

List of usage examples for com.itextpdf.text Paragraph setAlignment

Introduction

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

Prototype

public void setAlignment(int alignment) 

Source Link

Document

Sets the alignment of this paragraph.

Usage

From source file:contabilidad.Capital.java

public Capital() {
    jFrame = new JFrame("Capital");
    jFrame.setDefaultCloseOperation(jFrame.DISPOSE_ON_CLOSE);
    jFrame.setSize(800, 600);/*www .ja v a  2  s  . c  o  m*/
    jFrame.setLocationRelativeTo(null);
    jFrame.setIconImage(new ImageIcon(getClass().getResource("../imagenes/rana.jpg")).getImage());
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    System.out.println("X:" + screenSize.width + " Y:" + screenSize.height);
    int x = (screenSize.width / 2) - (jFrame.getSize().width / 2);
    int y = (screenSize.height / 2) - (jFrame.getSize().height / 2);
    jFrame.setLocation(x, y);

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

    JLabel capitalC = new JLabel("Capital Social: ");
    capitalC.setBounds(50, 90, 90, 20);
    jPanel.add(capitalC);

    JLabel cs = new JLabel("5000");
    cs.setBounds(140, 90, 90, 20);
    jPanel.add(cs);

    JLabel resultado = new JLabel("Resultado de ejercicio: ");
    resultado.setBounds(100, 130, 150, 20);
    jPanel.add(resultado);

    JLabel er = new JLabel("prueba");
    er.setBounds(250, 130, 90, 20);
    jPanel.add(er);

    JLabel capitalCT = new JLabel("Total Capital: ");
    capitalCT.setBounds(170, 170, 90, 20);
    jPanel.add(capitalCT);

    JLabel toc = new JLabel("prueba");
    toc.setBounds(270, 170, 90, 20);
    jPanel.add(toc);

    JMenuBar jMenuBar = new JMenuBar();
    JMenu jMenu = new JMenu("Inicio");
    JMenu jMenu2 = new JMenu("Reportes");
    JMenu jMenu3 = new JMenu("Ayuda");

    jMenuBar.add(jMenu);
    jMenuBar.add(jMenu2);
    jMenuBar.add(jMenu3);

    JMenuItem jMenuItem2 = new JMenuItem("Reporte PDF");
    jMenuItem2.addActionListener(new MenuListener(jFrame));
    jMenuItem2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            selecto = new JFileChooser();
            int op = selecto.showSaveDialog(null);
            if (op == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream archivo = new FileOutputStream(selecto.getSelectedFile() + ".pdf");
                    Document document = new Document();
                    document.addAuthor("Contabilidad");
                    document.addTitle("Capital");

                    PdfWriter writer = PdfWriter.getInstance(document,
                            new FileOutputStream(selecto.getSelectedFile() + ".pdf"));
                    writer.setInitialLeading(16);
                    Rectangle rct = new Rectangle(80, 104, 500, 688);
                    writer.setBoxSize("art", rct);
                    HeaderFooter event = new HeaderFooter();
                    writer.setPageEvent(event);

                    document.open();
                    document.add(new Paragraph("Capital"));
                    document.add(new Paragraph(" "));
                    Paragraph parrafo3 = new Paragraph("Fecha: 25/5/42");
                    parrafo3.setAlignment(2);//el 1 es para centrar
                    document.add(parrafo3);
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    Paragraph parrafo2 = new Paragraph("Capital Social :  5000 ");
                    parrafo2.setAlignment(6);//el 1 es para centrar
                    document.add(parrafo2);
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));

                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));

                    Paragraph parrafo5 = new Paragraph("Estado de resultados: ");
                    parrafo5.setAlignment(6);//el 1 es para centrar
                    document.add(parrafo5);

                    document.add(new Paragraph(" "));
                    document.add(new Paragraph(" "));

                    document.close();
                    archivo.close();
                    Runtime.getRuntime().exec("cmd /c start " + selecto.getSelectedFile() + ".pdf");
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                } catch (DocumentException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Capital.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }
    });

    JMenuItem jMenuItem3 = new JMenuItem("Salir");
    jMenuItem3.addActionListener(new MenuListener(jFrame));
    jMenuItem3.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            VentanaGeneral es = new VentanaGeneral();
            jFrame.dispose();
        }
    });

    JMenuItem jMenuItem7 = new JMenuItem("Acerca de");
    jMenuItem7.addActionListener(new MenuListener(jFrame));

    jMenu.add(jMenuItem3);
    jMenu2.add(jMenuItem2);
    jMenu3.add(jMenuItem7);

    jFrame.setJMenuBar(jMenuBar);

    JButton botonac = new JButton("Aceptar");
    botonac.setBounds(300, 300, 150, 30);
    botonac.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Reportes es = new Reportes();
            jFrame.dispose();
        }
    });
    jPanel.add(botonac);

    jFrame.add(jPanel);
    jFrame.setVisible(true);
}

From source file:control.AdminPDF.java

public static void generarInforme(ArrayList<Tarea> tareas, String usuario) {

    try {//from  w w w.  j  a va  2s.c o  m
        //Creamos la carpeta donde se almacenaran las facturas
        // Si quieres que las facturas se guarden en una carpeta del computador, 
        // aca colocas la ruta donde quieres que se guarden en lugar de src/facturas, 
        // tanto al crear carpeta y laFactura (de tipo File) y al crear archivo (de tipo FileOutputStream)
        //Ejemplo:  File carpeta = new File("D:\\facturas"); 
        //          FileOutputStream archivo = new FileOutputStream("D:\\facturas" + consecutivo + ".pdf");
        //          File laFactura = new File("src/facturas" + consecutivo + ".pdf");

        File carpeta = new File("web/pdfs");
        System.out.println(carpeta.exists());
        if (!carpeta.exists()) {
            carpeta.mkdirs();
        }
        String[] list = carpeta.list();
        consecutivo = list.length;
        System.out.println("Consecutivo es: " + consecutivo);
        int total = 0;
        FileOutputStream archivo = new FileOutputStream("web/pdfs/" + consecutivo + ".pdf");
        Document documento = new Document();
        PdfWriter.getInstance(documento, archivo);
        documento.open();
        Paragraph titulo = new Paragraph("Resumen de Actividades");
        titulo.setAlignment(Element.ALIGN_CENTER);
        documento.add(titulo);

        documento.add(new Paragraph(
                "------------------------------------------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph("Usuario: " + usuario));
        documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph("------------------------------------------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph(" "));
        documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph(" "));
        //         documento.add(new Paragraph(" "));
        documento.add(new Paragraph("  "));
        PdfPTable tabla = new PdfPTable(7);
        Image image = Image.getInstance("../EasyTasks/web/images/logo.png");

        //         tabla.addCell(image);
        Paragraph nombreBase = new Paragraph("Nombre ");
        Paragraph descripcionBase = new Paragraph("Descripcion     ");
        Paragraph fechaBase = new Paragraph("Fecha ");
        Paragraph prioridadBase = new Paragraph("Prioridad  ");
        Paragraph tagsBase = new Paragraph("Tags");
        Paragraph categoriaBase = new Paragraph("Categoria  ");
        Paragraph ubicacionBase = new Paragraph("Ubicacion    ");

        //         tabla.addCell(image);
        tabla.addCell(nombreBase);
        tabla.addCell(descripcionBase);
        tabla.addCell(fechaBase);
        tabla.addCell(prioridadBase);
        tabla.addCell(tagsBase);
        tabla.addCell(categoriaBase);
        tabla.addCell(ubicacionBase);
        for (int i = 0; i < tareas.size(); i++) {

            Tarea tareaNueva = tareas.get(i);
            Paragraph nombre = new Paragraph(tareaNueva.getNombre());
            Paragraph descripcion = new Paragraph(tareaNueva.getDescripcion());
            Paragraph fecha = new Paragraph(tareaNueva.getFechaLimite() + "");
            Paragraph prioridad = new Paragraph(tareaNueva.getPrioridad());
            Paragraph tags = null;
            for (int k = 0; k < tareaNueva.getTags().size(); k++) {
                tags = new Paragraph(tareaNueva.getTags().get(k));
            }
            Paragraph categoria = new Paragraph(tareaNueva.getCategoria());
            Paragraph ubicacion = new Paragraph(
                    tareaNueva.getUbiLatitud() + ", " + tareaNueva.getUbiLongitud());
            //            Paragraph tost = new Paragraph(tareaNueva.toStringSimple());

            tabla.addCell(nombre);
            tabla.addCell(descripcion);
            tabla.addCell(fecha);
            tabla.addCell(prioridad);
            tabla.addCell(tags);
            tabla.addCell(categoria);
            tabla.addCell(ubicacion);
            //            tabla.addCell(tost);

        }

        //         FileReader fr = new FileReader("src/archivos/pedidos.txt");
        //         BufferedReader bwa = new BufferedReader(fr);
        //         String elProducto = bwa.readLine();
        //         while (elProducto != null) {
        //            if (!elProducto.equalsIgnoreCase("")) {
        //               System.out.println("El producto: " + elProducto);
        //               String[] elProductoConPrecio = elProducto.split("-");
        //               Paragraph producto = new Paragraph(elProductoConPrecio[0]);
        //               Paragraph precio = new Paragraph(elProductoConPrecio[1]);
        //               total += Integer.parseInt(elProductoConPrecio[1]);
        //               precio.setAlignment(Element.ALIGN_RIGHT);
        //               tabla.addCell(producto);
        //               tabla.addCell(precio);
        //               elProducto = bwa.readLine();
        //            }
        //         }
        //         if (!darIva().equals("") && !darIva().equals("0")) {
        //            tabla.addCell("Subtotal");
        //            Paragraph elSubTotal = new Paragraph("" + total);
        //            elSubTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elSubTotal);
        //            tabla.addCell("Iva (" + darIva() + ")");
        //            int iva = total * Integer.parseInt(darIva()) / 100;
        //            tabla.addCell("" + iva);
        //            int precioConIva = total + iva;
        //            tabla.addCell("Total");
        //            Paragraph elTotal = new Paragraph("" + precioConIva);
        //            elTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elTotal);
        //         } else {
        //            tabla.addCell("Total");
        //            Paragraph elTotal = new Paragraph("" + total);
        //            elTotal.setAlignment(Element.ALIGN_RIGHT);
        //            tabla.addCell(elTotal);
        //         }
        documento.add(tabla);
        documento.add(new Paragraph(
                "----------------------------------------------------------------------------------------------"));
        documento.add(new Paragraph("Muchas gracias por utilizar nuestro servicio,"));
        documento.add(new Paragraph(""));
        //         Image image = Image.getInstance("logo.png");
        documento.addCreator("EasyTask Team");
        documento.add(image);
        documento.addCreationDate();
        //         PdfPCell cell2 = new PdfPCell(image, true);

        //         tabla.addCell(cell2);
        documento.add(new Paragraph(""));
        documento.add(new Paragraph("         EasyTask Team"));
        documento.close();
        File elInforme = new File("../EasyTasks/web/pdfs/" + usuario + ".pdf");
        Desktop.getDesktop().open(elInforme);
        //         BufferedWriter br = new BufferedWriter(new FileWriter("src//pedidos.txt"));
        //         br.write("");
        //         br.close();
        //         fr.close();
        //         bwa.close();
        archivo.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(AdminPDF.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}

From source file:Controlador.ControladorClasificacion.java

/**
 * Mtodo generarPDF que genera el PDF con la clasificacin al pulsar el
 * botn generar PDF//from  w  w w. j  ava  2s. c om
 *
 * @throws FileNotFoundException salta la excepcion
 * @throws DocumentException salta la excepcion
 * @throws IOException salta la excepcion
 */
public void generarPDF() throws FileNotFoundException, DocumentException, IOException {

    Calendar cal = Calendar.getInstance();
    String time = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(cal.getTime());

    File file = new File("Clasificacion.pdf");
    FileOutputStream fileout = new FileOutputStream(file.getAbsolutePath());
    Document document = new Document();
    PdfWriter.getInstance(document, fileout);

    Font fuente1 = new Font();
    Font fuente2 = new Font();
    Font fuente3 = new Font();
    fuente1.setStyle(Font.BOLD | Font.ITALIC | Font.UNDERLINE);
    fuente1.setSize(18);
    fuente1.setColor(0, 51, 204);
    fuente2.setStyle(Font.BOLD | Font.ITALIC);
    fuente2.setColor(0, 51, 204);
    fuente2.setSize(13);
    fuente3.setStyle(Font.BOLD | Font.ITALIC);
    fuente3.setSize(16);
    fuente3.setColor(255, 153, 0);

    document.open();

    Paragraph pa = new Paragraph("Fecha y hora: " + time);

    pa.setAlignment(Element.ALIGN_RIGHT);
    document.add(pa);

    /*String url = "imagenPDF.jpg";
    File file2 = new File(url);
    FileInputStream filein = new FileInputStream(file2.getAbsolutePath());
    //String url = "./imagenPDF.jpg";
    Image imagen = Image.getInstance(filein.getFD());  
    //System.out.println(file2.getAbsolutePath());
    imagen.scalePercent(20);
    document.add(imagen);*/
    document.add(new Paragraph("\n"));
    Paragraph p3 = new Paragraph("GESTOR DE CAMPEONATO DE BALONCESTO", fuente1);
    p3.setAlignment(Element.ALIGN_CENTER);
    document.add(p3);

    document.add(new Paragraph("\n"));
    String tipo_competicion = FicherosTipo.leerFichero();

    if (tipo_competicion.contains("Copa")) {
        Paragraph pa1 = new Paragraph("COPA", fuente3);
        pa1.setAlignment(Element.ALIGN_CENTER);
        document.add(pa1);
        document.add(new Paragraph(
                "---------------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph("\n"));
        int jornada_maxima = PartidoDAO.obtenerJornadaActual();

        for (int i = jornada_maxima; i > 0; i--) {
            List<Partido> listarPartidosJornada = PartidoDAO.listarPartidosJornada(i);
            for (Partido p : listarPartidosJornada) {

                List<PartidoJugado> listarEquiposporPartido = PartidoJugadoDAO
                        .listarEquiposporPartido(p.getIdPartido());

                int equipoA = listarEquiposporPartido.get(0).getIdEquipo();
                int equipoB = listarEquiposporPartido.get(1).getIdEquipo();

                Paragraph p2 = new Paragraph(
                        "Equipo A: " + EquipoDAO.obtenerNombreEquipo(equipoA) + " - Equipo B: "
                                + EquipoDAO.obtenerNombreEquipo(equipoB) + " - Resultado: " + p.getResultado(),
                        fuente2);
                p2.setAlignment(Element.ALIGN_LEFT);
                document.add(p2);
            }

        }

    } else if (tipo_competicion.contains("Liga")) {
        Paragraph pa1 = new Paragraph("LIGA", fuente3);
        pa1.setAlignment(Element.ALIGN_LEFT);
        document.add(pa1);
        document.add(new Paragraph(
                "---------------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph("\n"));
        List<Equipo> obtenerTodosEquipos = EquipoDAO.obtenerTodosEquipos();
        Collections.sort(obtenerTodosEquipos);
        System.out.println(obtenerTodosEquipos);
        for (Equipo p : obtenerTodosEquipos) {
            Paragraph pa2 = new Paragraph(p.getNombre(), fuente2);
            pa2.setAlignment(Element.ALIGN_LEFT);
            document.add(pa2);
        }

    }
    document.close();
    File myfile = new File("Clasificacion.pdf");
    Desktop.getDesktop().open(myfile);
}

From source file:Controlador.EmailWithPdf.java

/**
 * Writes the content of a PDF file (using iText API)
 * to the {@link OutputStream}./*from  w  w w.  j a  v a 2s  .  com*/
 * @param outputStream {@link OutputStream}.
 * @throws Exception
 */
public void writePdf(OutputStream outputStream) throws Exception {
    Document document = new Document(PageSize.LETTER, 50, 50, 50, 30);
    Font boldFontTitulo = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    Font boldFontTexto = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);
    Font FontTexto = new Font(Font.FontFamily.HELVETICA, 12);

    // document.setPageSize(null);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    Image imagen = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\BSeguroLogo.png");
    Image imagen2 = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\mapfre.png");

    DateFormat df = new SimpleDateFormat("dd/MM/YYYY");
    Calendar cdos = Calendar.getInstance();
    Date datediamas = new Date();
    Date dateaniomas = new Date();
    cdos.add(Calendar.DATE, 1);
    datediamas = cdos.getTime();
    String fechadiamas = df.format(datediamas);
    cdos.add(Calendar.YEAR, 1);
    dateaniomas = cdos.getTime();
    String fechavencimiento = df.format(dateaniomas);
    document.open();

    PdfContentByte canvas = writer.getDirectContent();
    Rectangle rect = new Rectangle(36, 36, 579, 756);
    rect.setBorder(Rectangle.BOX);
    rect.setBorderWidth(2);
    canvas.rectangle(rect);

    //         Rectangle rect= new Rectangle(36,108);
    //         rect.setBorder(Rectangle.BOX);
    //         
    //rect.setBorderColor(BaseColor.BLACK);
    //rect.setBorderWidth(2);
    //document.add(rect);
    document.addTitle("Cotizacion");
    document.addSubject("Cotizacion");
    document.addKeywords("Cotizacion, seguros");
    document.addAuthor("BSeguro");
    document.addCreator("Bseguro");

    imagen.scaleAbsoluteHeight(30f);
    imagen.setAbsolutePosition(45f, 720f);
    imagen2.scaleAbsoluteHeight(30f);
    imagen2.setAbsolutePosition(450f, 720f);
    document.add(imagen);
    document.add(imagen2);

    Paragraph paragraph2 = new Paragraph("DATOS DE TU POLIZA" + fechadiamas + " hasta: " + fechavencimiento,
            boldFontTitulo);
    Paragraph paragraph3 = new Paragraph(
            "DhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhATOS DE TU POLIZA",
            boldFontTitulo);

    paragraph2.setAlignment(Element.ALIGN_CENTER);

    document.add(paragraph2);
    document.add(paragraph3);

    document.close();

}

From source file:controlador.generadorticket.GenerarpdfticketVE.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w. j av  a 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("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");// Forzar a usar codificacin UTF-8 iso-8859-1        
    String Encabezado = (request.getParameter("encabezado"));
    String Encabezado1 = (request.getParameter("encabezado1"));
    String Encabezado2 = (request.getParameter("encabezado2"));
    String total = (request.getParameter("total"));
    String Tipo[] = request.getParameterValues("tipo");
    String Costo[] = request.getParameterValues("costo");
    String Observacion[] = request.getParameterValues("observacion");

    String Fecha = (request.getParameter("Fecha"));
    String Municipio = (request.getParameter("Municipio"));
    String Cliente = (request.getParameter("Cliente"));
    String Estado = (request.getParameter("Estado"));
    String Direccion = (request.getParameter("Direccion"));
    String Localidad = (request.getParameter("Localidad"));
    String Venta = (request.getParameter("Id_venta"));

    Font fuente = new Font(Font.FontFamily.COURIER, 10);
    Paragraph P = new Paragraph();
    Chunk c = new Chunk();
    P.setAlignment(Element.ALIGN_CENTER);

    try {
        FileOutputStream Archivo = new FileOutputStream("/home/rcortes/Ejemplo.pdf");
        Document doc = new Document();
        PdfWriter.getInstance(doc, Archivo);
        doc.open();
        doc.add(new Paragraph(Encabezado));
        doc.add(new Paragraph(Encabezado1));
        doc.add(new Paragraph(Encabezado2));
        PdfPTable tabla1 = new PdfPTable(3);
        doc.add(new Paragraph(" "));
        doc.add(new Paragraph("Venta: " + Venta));
        doc.add(new Paragraph("Cliente: " + Cliente));
        doc.add(new Paragraph("Estado: " + Estado));
        doc.add(new Paragraph("Municipio: " + Municipio));
        doc.add(new Paragraph("Localidad: " + Localidad));
        doc.add(new Paragraph("Direccin: " + Direccion));
        doc.add(new Paragraph(" "));
        tabla1.addCell("Tipo");
        tabla1.addCell("Monto");
        tabla1.addCell("Observacin");
        for (int i = 0; i < Tipo.length; i++) {
            tabla1.addCell(Tipo[i]);
            tabla1.addCell(Costo[i]);
            tabla1.addCell(Observacion[i]);
        }
        doc.add(tabla1);
        doc.add(new Paragraph(" "));
        doc.add(new Paragraph("Total:  " + total));
        doc.close();
        System.out.println("Se creo pdf\n");
    } catch (DocumentException e) {
        System.out.println(e);
    }
}

From source file:ControleurClients.ControleurClients.java

private void pageCommandes(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DocumentException {
    request.setAttribute("attente", commandef.getAttente(clientConnect));
    request.setAttribute("cours", commandef.getCours(clientConnect));
    request.setAttribute("effectuee", commandef.getEffectuee(clientConnect));

    List<Commande> attente = commandef.getAttente();
    List<Commande> cours = commandef.getCours();
    List<Commande> effectue = commandef.getEffectuee();
    if (!attente.isEmpty()) {
        for (Commande c : attente) {
            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/attente"
                            + c.getId().toString() + ".pdf"));

            document1.open();/*ww w . j  a  v a2 s . com*/
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("En attente : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total: " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);
            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }
    }

    if (!cours.isEmpty()) {
        for (Commande c : cours) {
            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/cours"
                            + c.getId().toString() + ".pdf"));

            document1.open();
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("En cours : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total : " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);
            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }
    }

    if (!effectue.isEmpty()) {
        for (Commande c : effectue) {
            new File("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/attente" + c.getId().toString()
                    + ".pdf").delete();
            new File("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/cours" + c.getId().toString()
                    + ".pdf").delete();

            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/effectue"
                            + c.getId().toString() + ".pdf"));

            document1.open();
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Effectue : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total : " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);

            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }

    }

    getServletContext().getRequestDispatcher("/WEB-INF/Commande.jsp").forward(request, response);
}

From source file:Controller.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library./*from   w w w  .j  a va2 s  . c  om*/
 * Creamos un documento PDF con iText usando diferentes elementos para aprender 
 * a usar esta librera.
 * @param pdfNewFile  <code>String</code> 
 *      pdf File we are going to write. 
 *      Fichero pdf en el que vamos a escribir. 
 */
//    public void createPDF(File pdfNewFile, ReparacionEntity reparacion) throws Exception {
public void createPDF(File pdfNewFile) throws Exception {
    // We create the document and set the file name.        
    // Creamos el documento e indicamos el nombre del fichero.
    try {
        //            ClienteController cc = new ClienteController();
        //            Cliente cliente = cc.buscarPorId(reparacion.getCliente());
        Document document = new Document();
        try {

            PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));

        } catch (FileNotFoundException fileNotFoundException) {
            System.out.println("No such file was found to generate the PDF "
                    + "(No se encontr el fichero para generar el pdf)" + fileNotFoundException);
        }
        document.open();
        // We add metadata to PDF
        // Aadimos los metadatos del PDF
        document.addTitle("Table export to PDF (Exportamos la tabla a PDF)");
        document.addSubject("Using iText (usando iText)");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Cdigo Xules");
        document.addCreator("Cdigo Xules");

        // First page
        // Primera pgina 
        Chunk chunk = new Chunk("RDEN DE TRABAJO", categoryFont);
        Chunk c2 = new Chunk("\n\n\nCentro de Formacin SATCAR6\n" + "Calle Artes Grficas n1 Nave 12 A\n"
                + "Pinto (28320), Madrid", smallFont);

        Chunk c3 = new Chunk("Datos del Cliente", smallBold);
        //            Chunk c4 = new Chunk("Nombre: "+cliente.getRazonSocial(),smallBold);
        //            Chunk c5 = new Chunk("Poblacin: "+cliente.getPoblacion(),smallBold);
        //            Chunk c6 = new Chunk("Provincia: "+cliente.getProvincia(),smallBold);
        //            Chunk c7 = new Chunk("Cdigo Postal: "+cliente.getCp(),smallBold);
        //            Chunk c8 = new Chunk("Num Telfono: Pepito"+cliente.getTlf1(),smallBold);
        Chunk c4 = new Chunk("Nombre: Jesus Eduardo Garcia Toril", smallBold);
        Chunk c5 = new Chunk("Poblacin: Pinto", smallBold);
        Chunk c6 = new Chunk("Provincia: Madrid", smallBold);
        Chunk c7 = new Chunk("Cdigo Postal: 28320", smallBold);
        Chunk c8 = new Chunk("Num Telfono: 659408182", smallBold);

        Paragraph parrafo = new Paragraph(chunk);
        Paragraph p2 = new Paragraph(c2);
        Paragraph p3 = new Paragraph(c3);
        Phrase ph1 = new Phrase(c4);
        Phrase ph2 = new Phrase(c5);
        Phrase ph3 = new Phrase(c6);
        Phrase ph4 = new Phrase(c7);
        Phrase ph5 = new Phrase(c8);

        // Let's create de first Chapter (Creemos el primer captulo)

        // We add an image (Aadimos una imagen)
        Image image;
        try {
            parrafo.setAlignment(Element.ALIGN_CENTER);
            image = Image.getInstance(iTextExampleImage);
            image.setAbsolutePosition(0, 750);
            p2.setAlignment(Element.ALIGN_LEFT);
            document.add(parrafo);
            document.add(image);
            document.add(p2);
            document.add(p3);
            document.add(ph1);
            document.add(ph2);
            document.add(ph3);
            document.add(ph4);
            document.add(ph5);

        } catch (BadElementException ex) {
            System.out.println("Image BadElementException" + ex);
        }

        // Second page - some elements
        // Segunda pgina - Algunos elementos

        // List by iText (listas por iText)
        String text = "test 1 2 3 ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        List list = new List(List.UNORDERED);
        ListItem item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "a b c align ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "supercalifragilisticexpialidocious ";
        for (int i = 0; i < 3; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);

        // How to use PdfPTable
        // Utilizacin de PdfPTable

        // We use various elements to add title and subtitle
        // Usamos varios elementos para aadir ttulo y subttulo
        Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont);
        anchor.setName("Table export to PDF (Exportamos la tabla a PDF)");
        Chapter chapTitle = new Chapter(new Paragraph(anchor), 1);
        Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);
        Section paragraphMore = chapTitle.addSection(paragraph);
        paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)"));
        Integer numColumns = 6;
        Integer numRows = 120;
        // We create the table (Creamos la tabla).
        PdfPTable table = new PdfPTable(numColumns);
        // Now we fill the PDF table 
        // Ahora llenamos la tabla del PDF
        PdfPCell columnHeader;
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int column = 0; column < numColumns; column++) {
            columnHeader = new PdfPCell(new Phrase("COL " + column));
            columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(columnHeader);
        }
        table.setHeaderRows(1);
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int row = 0; row < numRows; row++) {
            for (int column = 0; column < numColumns; column++) {
                table.addCell("Row " + row + " - Col" + column);
            }
        }
        // We add the table (Aadimos la tabla)
        paragraphMore.add(table);
        // We add the paragraph with the table (Aadimos el elemento con la tabla).
        document.add(chapTitle);
        document.close();
        System.out.println("Your PDF file has been generated!(Se ha generado tu hoja PDF!");
    } catch (DocumentException documentException) {
        System.out.println(
                "The file not exists (Se ha producido un error al generar un documento): " + documentException);
    }
}

From source file:controller.pdf.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w .  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.//  w ww . j a v  a 2s . 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("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.PDFGenerator.java

@Override
public void GenerateDocument(Resolution doc) {
    String resId = "RES-IC-" + format(doc.getId()) + "-" + Calendar.getInstance().get(Calendar.YEAR);

    Document pdf = createDocument(resId + ".pdf");

    if (pdf == null)
        return;//from   w w  w  .j  a v  a2s  .c o m

    try {
        pdf.open();
        Font boldFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD);
        Font parFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);

        Chunk chunk = new Chunk(doc.getTitle() + "\n\n", boldFont);
        Paragraph par = new Paragraph(chunk);
        par.setAlignment(Paragraph.ALIGN_CENTER);
        pdf.add(par);

        chunk = new Chunk(resId + "\n\n", boldFont);
        par = new Paragraph(chunk);
        par.setAlignment(Paragraph.ALIGN_CENTER);
        pdf.add(par);

        chunk = new Chunk("Atencin:    ", boldFont);
        par = new Paragraph(chunk);
        chunk = new Chunk(doc.getAttention() + "\n\n", parFont);
        par.add(chunk);
        par.setAlignment(Paragraph.ALIGN_LEFT);
        par.setIndentationLeft((float) 3.0);
        pdf.add(par);

        chunk = new Chunk(doc.getIntro() + "\n\n", parFont);
        par = new Paragraph(chunk);
        par.setAlignment(Paragraph.ALIGN_JUSTIFIED);
        pdf.add(par);

        chunk = new Chunk((doc.isOneresult() == true ? "RESULTANDO NICO:\n" : "RESULTANDO:\n"), boldFont);
        par = new Paragraph(chunk);
        chunk = new Chunk(doc.getResult() + "\n\n", parFont);
        par.add(chunk);
        par.setAlignment(Paragraph.ALIGN_JUSTIFIED);
        pdf.add(par);

        chunk = new Chunk((doc.isOneconsideration() == true ? "CONSIDERANDO NICO:\n" : "CONSIDERANDOS:\n"),
                boldFont);
        par = new Paragraph(chunk);
        chunk = new Chunk(doc.getConsider() + "\n\n", parFont);
        par.add(chunk);
        par.setAlignment(Paragraph.ALIGN_JUSTIFIED);
        pdf.add(par);

        chunk = new Chunk("RESUELVO:\n", boldFont);
        par = new Paragraph(chunk);
        chunk = new Chunk(doc.getResolve() + "\n\n", parFont);
        par.add(chunk);
        par.setAlignment(Paragraph.ALIGN_JUSTIFIED);
        pdf.add(par);

        chunk = new Chunk("NOTIFIQUESE:\n", boldFont);
        par = new Paragraph(chunk);
        par.setAlignment(Paragraph.ALIGN_LEFT);
        pdf.add(par);

        chunk = new Chunk(doc.getNotify(), parFont);
        par = new Paragraph(chunk);
        par.setAlignment(Paragraph.ALIGN_LEFT);
        par.setIndentationLeft(250);
        pdf.add(par);

        pdf.close();
    } catch (Exception ex) {
        System.out.println("Error writirn pdf.");
    }
}