Example usage for com.itextpdf.text.pdf PdfPCell PdfPCell

List of usage examples for com.itextpdf.text.pdf PdfPCell PdfPCell

Introduction

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

Prototype

public PdfPCell(PdfPCell cell) 

Source Link

Document

Constructs a deep copy of a PdfPCell.

Usage

From source file:Controller.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library./*from  ww  w.  ja  va  2s .com*/
 * 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.CreateTranscript.java

private void CreateTranscript(MyPerson p) {//,PrintWriter out){
    Document document = new Document();

    String name = p.getFName() + p.getLName();

    try {// w  ww .  j a  va  2s . c o  m
        if (p.getUserType() == 6) {

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\" + name + ".pdf"));
            document.open();

            PdfPTable table = new PdfPTable(8); // 8 columns.
            table.setWidthPercentage(100); //Width 100%
            table.setSpacingBefore(10f); //Space before table
            table.setSpacingAfter(10f); //Space after table

            //Set Column widths
            float[] columnWidths = { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
            table.setWidths(columnWidths);
            PdfPCell cell1 = new PdfPCell(new Paragraph("Subject Name"));
            cell1.setBorderColor(BaseColor.BLUE);
            cell1.setPaddingLeft(10);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell2 = new PdfPCell(new Paragraph("Subject Code"));
            cell2.setBorderColor(BaseColor.BLUE);
            cell2.setPaddingLeft(10);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell3 = new PdfPCell(new Paragraph("Written Grade"));
            cell3.setBorderColor(BaseColor.BLUE);
            cell3.setPaddingLeft(10);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell4 = new PdfPCell(new Paragraph("Midterm Grade"));
            cell4.setBorderColor(BaseColor.BLUE);
            cell4.setPaddingLeft(10);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell5 = new PdfPCell(new Paragraph("Final Exam Grade"));
            cell5.setBorderColor(BaseColor.BLUE);
            cell5.setPaddingLeft(10);
            cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell6 = new PdfPCell(new Paragraph("Final Grade"));
            cell6.setBorderColor(BaseColor.BLUE);
            cell6.setPaddingLeft(10);
            cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell7 = new PdfPCell(new Paragraph("Term"));
            cell7.setBorderColor(BaseColor.BLUE);
            cell7.setPaddingLeft(10);
            cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
            PdfPCell cell8 = new PdfPCell(new Paragraph("Registration Date"));
            cell8.setBorderColor(BaseColor.BLUE);
            cell8.setPaddingLeft(10);
            cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);

            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);
            table.addCell(cell5);
            table.addCell(cell6);
            table.addCell(cell7);
            table.addCell(cell8);

            ModelOfStudent modelOfStudent = new ModelOfStudent();
            ResultSet rs = modelOfStudent.ViewMyCourses(p.getCode());

            //    if(!rs.next()){out.println("<font color='blue'>There is no Courses Untill Now ^_^ </font>");}
            while (rs.next()) {

                table.addCell(rs.getString("SubjectName"));
                table.addCell(rs.getString("ID"));
                table.addCell(rs.getString("WritenGrade"));
                table.addCell(rs.getString("MidtermGrade"));
                table.addCell(rs.getString("FinalExamGrade"));
                table.addCell(rs.getString("FinalGrade"));
                table.addCell(rs.getString("Term"));
                table.addCell(rs.getString("StudentRegisterSubjectDate"));

                /* String SubjectRegisterDate=String.valueOf(rs.getDate("SubjectRegisterDate"));
                 table.addCell(SubjectRegisterDate);
                 */
            }

            //To avoid having the cell border and the content overlap, if you are having thick cell borders
            //cell1.setUserBorderPadding(true);
            //cell2.setUserBorderPadding(true);
            //cell3.setUserBorderPadding(true);
            document.add(new Paragraph("University: " + MyPerson.ReturnUniversityName(p.getCode())));
            document.add(new Paragraph("Faculity: " + MyPerson.ReturnFaculityName(p.getCode())));
            document.add(
                    new Paragraph("Student Name: " + p.getFName() + " " + p.getMName() + " " + p.getLName()));
            document.add(new Paragraph("Level: " + MyPerson.ReturnLevelName(p.getCode())));
            document.add(new Paragraph("Department: " + MyPerson.ReturnDepartmentName(p.getCode())));

            document.add(table);
            System.out.println(
                    "<script type='text/javascript' > alert('Successfull Creating Transcript ^_^ ');history.back();</script>");

            //out.println("Successfull Creating Transcript ^_^");
            document.close();
            writer.close();
        } //end of if student
    } catch (Exception e) {
        System.out.println("<script type='text/javascript' > alert('Failed Creating Transcript ^_^ Error:"
                + e.getMessage() + "  ');history.back();</script>");

        // out.println(""+e.getMessage());
        e.printStackTrace();
    }
}

From source file:controller.pdf.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  . jav  a  2  s . c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("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.Personagem.java

public PdfPCell Cel(String texto, int coluna, Font f) {
    PdfPCell c = new PdfPCell(new Paragraph(texto, f));
    c.setColspan(coluna);/*from ww w. j a  v a 2 s  .co m*/
    return c;
}

From source file:controller.PlanController.java

public Document PrintPressed(String Path) throws DocumentException, IOException {
    // step 1//from w  w w .j a va 2 s. co m
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(Path));
    // step 3
    document.open();
    // step 4
    PdfPTable tablaDatosPlan = new PdfPTable(2);

    tablaDatosPlan.setWidthPercentage(100);

    if (!Team.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Team") + ":" + Team.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Season.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Season") + ":" + Season.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Date.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Date") + ":" + Date.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Players.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Players") + ":" + Players.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Start.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Start") + ":" + Start.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!End.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("End") + ":" + End.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Place.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Place") + ":" + Place.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Equipment.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Equipment") + ":" + Equipment.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }

    document.add(tablaDatosPlan);

    document.add(new Phrase("\n"));
    document.add(new Phrase("\n"));

    PdfPTable tablaEjercicios = new PdfPTable(4);
    tablaEjercicios.setHeaderRows(contadorlineas);
    tablaEjercicios.addCell(messages.getString("Start"));
    tablaEjercicios.addCell(messages.getString("End"));
    tablaEjercicios.addCell(messages.getString("Drill"));
    tablaEjercicios.addCell(messages.getString("Notes"));
    int cont = 0;
    for (int aw = 4; aw < contadorlineas + 4; aw++) {

        tablaEjercicios.addCell(starColumn.getCellData(cont));
        tablaEjercicios.addCell(endColumn.getCellData(cont));
        tablaEjercicios.addCell(drillColumn.getCellData(cont));
        tablaEjercicios.addCell(notesColumn.getCellData(cont));
        cont++;
    }

    document.add(tablaEjercicios);
    int contadorListado = 0, contadorRecorrer = 0;

    if (checkboxDrills.isSelected()) {

        while (contadorListado < planData.size()) {
            contadorRecorrer = 0;

            while (contadorRecorrer < playData.size()) {
                System.out.println("Busco el ejercicio " + drillColumn.getCellData(contadorListado));
                if (drillColumn.getCellData(contadorListado)
                        .contains(playData.get(contadorRecorrer).getNombreJugada())) {
                    int contador = 1;
                    System.out.println("Ejercicio encontrado");
                    document.add(new Paragraph(
                            messages.getString("Drill") + " " + drillColumn.getCellData(contadorListado)));
                    while (contador < playData.get(contadorRecorrer).getContadorJugada() + 1) {

                        document.add(new Paragraph(messages.getString("Diagram") + " " + contador));
                        document.add(new Paragraph(" "));

                        Image image2 = Image.getInstance(playData.get(contadorRecorrer).getNombreJugada() + "-"
                                + playData.get(contadorRecorrer).getTipoJugada() + "-"
                                + playData.get(contadorRecorrer).getSubtipoJugada() + "_" + contador);
                        image2.scalePercent(50);

                        PdfPTable table1 = new PdfPTable(2);

                        table1.addCell(image2);
                        table1.addCell(
                                textPdf.textPdf(contador, playData.get(contadorRecorrer).getDescripcionJugada(),
                                        playData.get(contadorRecorrer).getContadorJugada()));
                        document.add(table1);

                        contador++;

                    }

                }
                contadorRecorrer++;

            }
            contadorListado++;
        }

    }
    // step 5
    document.close();
    return document;

}

From source file:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {/* w w w  .j av a2s  .co  m*/

        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();/* w ww .  j  a  va 2 s.  c  o  m*/
        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:crearpdf.CrearPDF.java

private void crearReportePDForacle(String select) throws Exception {

    Class.forName("oracle.jdbc.OracleDriver"); //Invocamos el Driver de Oracle
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "willson"/*usuario*/,
            "123456"/*contrasea*/); //Creamos la conexion para acceder a la base de datos
    Statement stmt = con.createStatement();
    ResultSet resultados = stmt.executeQuery(select); //Hacemos el select de la info que extraeremos de la base de datos
    Document reportePDF = new Document(PageSize.LETTER, 88, 88, 80, 15); //Creamos un nuevo Documento usando la libreria itextpdf importada.
    PdfWriter.getInstance(reportePDF, new FileOutputStream("REPORTE.pdf"));//Instanciamos y creamos el archivo
    reportePDF.open(); //Abrimos el archivo creado arriba.

    Paragraph parrafo = new Paragraph("Reporte del dia");
    parrafo.add("Este es el repote que nos da los datos");
    parrafo.setAlignment(Element.ALIGN_CENTER);

    PdfPTable Treportes = new PdfPTable(5);//Aqui asignamos el numero de columnas que tendra la tabla, en este casi 5.
    PdfPCell celdas_tabla;//Creamos las celdas que seran llenadas con los datos extraidos

    //Agregamos los titulos de cada Columna                   
    Treportes.addCell("ID");
    Treportes.addCell("Nombre");
    Treportes.addCell("Edad");
    Treportes.addCell("Mes Nacimiento");
    Treportes.addCell("Universidad");

    //ciclo para empezar a aadir los datos de la base de datos a las celdas correspondientes en el PDF
    ///System.out.println("Llenando pdf");
    while (resultados.next()) {

        String id = resultados.getString("ID");
        celdas_tabla = new PdfPCell(new Phrase(id));
        Treportes.addCell(celdas_tabla);
        String nombre = resultados.getString("NOMBRE");
        celdas_tabla = new PdfPCell(new Phrase(nombre));
        Treportes.addCell(celdas_tabla);
        String edad = resultados.getString("EDAD");
        celdas_tabla = new PdfPCell(new Phrase(edad));
        Treportes.addCell(celdas_tabla);
        String nacimiento = resultados.getString("MES_NACIMIENTO");
        celdas_tabla = new PdfPCell(new Phrase(nacimiento));
        Treportes.addCell(celdas_tabla);
        String universidad = resultados.getString("UNIVERSIDAD");
        celdas_tabla = new PdfPCell(new Phrase(universidad));
        Treportes.addCell(celdas_tabla);
        //System.out.println(id+" "+nombre+" "+edad);
    }/*w  ww  .j  a va 2 s.  c om*/
    // System.out.println("Listo!");
    parrafo.add(Treportes);
    reportePDF.add(parrafo);

    //reportePDF.add(Treportes); //Insertamos los datos de la tabla en el PDF.                      
    reportePDF.close(); //Cerramos el archivo PDF una vez completado

    //Cerrar todas las conexiones
    resultados.close();
    stmt.close();
    con.close();

}

From source file:crearpdf.CrearPDF.java

public static void main(String[] args) throws Exception {

    Class.forName("oracle.jdbc.OracleDriver"); //Invocamos el Driver de Oracle
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "willson"/*usuario*/,
            "123456"/*contrasea*/); //Creamos la conexion para acceder a la base de datos
    Statement stmt = con.createStatement();
    ResultSet resultados = stmt//from   w w  w . java  2  s.  c om
            .executeQuery("SELECT ID, NOMBRE, EDAD, MES_NACIMIENTO, UNIVERSIDAD FROM PERSONAS"); //Hacemos el select de la info que extraeremos de la base de datos
    Document reportePDF = new Document(PageSize.B4, 88, 88, 80, 15); //Creamos un nuevo Documento usando la libreria itextpdf importada.
    PdfWriter.getInstance(reportePDF, new FileOutputStream("REPORTE.pdf"));//Instanciamos y creamos el archivo
    reportePDF.open(); //Abrimos el archivo creado arriba.

    Paragraph parrafo = new Paragraph("Reporte del dia");
    parrafo.setAlignment(Element.ALIGN_CENTER);

    PdfPTable Treportes = new PdfPTable(5);//Aqui asignamos el numero de columnas que tendra la tabla, en este casi 5.
    PdfPCell celdas_tabla;//Creamos las celdas que seran llenadas con los datos extraidos

    //Agregamos los titulos de cada Columna                   
    Treportes.addCell("ID");
    Treportes.addCell("Nombre");
    Treportes.addCell("Edad");
    Treportes.addCell("Mes Nacimiento");
    Treportes.addCell("Universidad");

    //ciclo para empezar a aadir los datos de la base de datos a las celdas correspondientes en el PDF
    System.out.println("Llenando pdf");
    while (resultados.next()) {

        String id = resultados.getString("ID");
        celdas_tabla = new PdfPCell(new Phrase(id));
        Treportes.addCell(celdas_tabla);

        String nombre = resultados.getString("NOMBRE");
        celdas_tabla = new PdfPCell(new Phrase(nombre));
        Treportes.addCell(celdas_tabla);

        String edad = resultados.getString("EDAD");
        celdas_tabla = new PdfPCell(new Phrase(edad));
        Treportes.addCell(celdas_tabla);

        String nacimiento = resultados.getString("MES_NACIMIENTO");
        celdas_tabla = new PdfPCell(new Phrase(nacimiento));
        Treportes.addCell(celdas_tabla);

        String universidad = resultados.getString("UNIVERSIDAD");
        celdas_tabla = new PdfPCell(new Phrase(universidad));
        Treportes.addCell(celdas_tabla);

        System.out.println(id + " " + nombre + " " + edad);
    }
    System.out.println("Listo!");
    reportePDF.add(parrafo);
    reportePDF.add(Treportes); //Insertamos los datos de la tabla en el PDF.                      
    reportePDF.close(); //Cerramos el archivo PDF una vez completado

    //Cerrar todas las conexiones
    resultados.close();
    stmt.close();
    con.close();

}

From source file:CTD.planer2.util.ExportToPdf.java

/**
 * We create the table we want to add to our pdf
 * /*from   www. ja va2 s  .  c om*/
 * @param subCatPart
 * @throws BadElementException
 */
private static void createTable(Section subCatPart) throws BadElementException {

    // Get the number of days per Week from the Settings
    int daysPerWeek = App.theSettings.getDaysPerWeek();

    PdfPTable table = new PdfPTable(daysPerWeek + 1);

    String[] WeekDay = { "Zeit", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag",
            "Sonntag" };

    for (int i = 0; i < daysPerWeek + 1; i++) {
        PdfPCell c1 = new PdfPCell(new Phrase(WeekDay[i]));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        if (i == daysPerWeek) {
            table.setHeaderRows(1);
        }
    }

    // We take the first day to get the number of units and so the number of
    // times we have to run this.
    for (int j = 0; j < planExport.getWeekday(1).size(); j++) {
        // For each day available, we run this loop once.
        for (int k = 1; k < daysPerWeek + 1; k++) {
            // Read one unit per day and write it in a new cell of the pdf
            List<Units> tmp = planExport.getWeekday(k);
            // If it's the first day, we also want a first cell per line
            // containing the time this unit starts
            if (k == 1) {
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                String time = df.format(tmp.get(j).getTime());
                table.addCell(time);
                String room = " ";
                // Check whether a room is given
                if (tmp.get(j).getRooms().size() < 1) {
                    room = " ";
                } else {
                    room = tmp.get(j).getRooms().get(0).toString();
                }
                String teacher = " ";
                if (tmp.get(j).getPerson() == null) {
                    teacher = " ";
                } else {
                    teacher = tmp.get(j).toString();
                }
                String subject = " ";
                if (tmp.get(j).getSubjects().size() < 1) {
                    subject = " ";
                } else {
                    subject = tmp.get(j).getSubjects().get(0).toString();
                }
                // If the plan is for a room, we just need the time and the
                // teachers name
                if (CPlaner.selRoom != null) {
                    table.addCell(teacher);
                    // If the plan is for a class, we need the time, the
                    // room and the teachers name
                } else if (CPlaner.selClass != null) {
                    table.addCell(room + ", " + teacher);
                    // For a teachers plan, we need the room and the subject
                } else {
                    table.addCell(room + ", " + subject);
                }
            } else {
                // If it's not the first day, we don't need to print the
                // start time again
                String room = " ";
                // Check again whether a room is given
                if (tmp.get(j).getRooms().size() < 1) {
                    room = " ";
                } else {
                    room = tmp.get(j).getRooms().get(0).toString();
                }
                String teacher = " ";
                if (tmp.get(j).getPerson() == null) {
                    teacher = " ";
                } else {
                    teacher = tmp.get(j).toString();
                }
                String subject = " ";
                if (tmp.get(j).getSubjects().size() < 1) {
                    subject = " ";
                } else {
                    subject = tmp.get(j).getSubjects().get(0).toString();
                }
                // If the plan is for a room, we just need the time and the
                // teachers name
                if (CPlaner.selRoom != null) {
                    table.addCell(teacher);
                    // If the plan is for a class, we need the time, the
                    // room and the teachers name
                } else if (CPlaner.selClass != null) {
                    table.addCell(room + ", " + teacher);
                    // For a teachers plan, we need the room and the subject
                } else {
                    table.addCell(room + ", " + subject);
                }
            }
        }
    }

    // Add the whole table we've just created to the pdf file
    subCatPart.add(table);

}