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

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

Introduction

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

Prototype

public void setWidths(final int relativeWidths[]) throws DocumentException 

Source Link

Document

Sets the relative widths of the table.

Usage

From source file:controller.CreateTranscript.java

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

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

    try {/*  ww w .  j av a 2  s . 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 w ww.j  av  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();

    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.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {/*ww w .  ja v  a 2s.c  o  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:dbedit.actions.ExportPdfAction.java

License:Open Source License

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

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

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

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

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

From source file:de.domjos.schooltools.core.utils.fileUtils.PDFBuilder.java

License:Open Source License

public void addTable(List<String> headers, float[] headerWidth, List<List<Map.Entry<String, BaseColor>>> cells)
        throws Exception {
    PdfPTable table = new PdfPTable(headers.size());
    if (headerWidth != null) {
        table.setWidths(headerWidth);
    }/*ww w  .j a v a 2s .  c om*/

    for (String header : headers) {
        PdfPCell cell = new PdfPCell(
                new Phrase(header, new Font(Font.FontFamily.HELVETICA, 18, Font.BOLDITALIC)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(cell);
    }

    for (List<Map.Entry<String, BaseColor>> row : cells) {
        for (Map.Entry<String, BaseColor> cellItem : row) {
            PdfPCell cell = new PdfPCell(
                    new Phrase(cellItem.getKey(), new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBackgroundColor(cellItem.getValue());
            table.addCell(cell);
        }
    }

    this.document.add(table);
}

From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Erzeugt das Inhaltsverzeichnis aus den bereits vorhandenen Elementen in
 * der Liste <code>listEntries</code>.
 * /*from w  ww  .  ja  va2s . c o m*/
 * @param docPdf
 *            Zieldokument, falls Inhaltsverzeichnis nicht temporr erzeugt
 *            wird
 * @param temp
 *            Gibt an, ob das Inhaltsverzeichnis temporr in einer neuen
 *            Datei/Dokument erzeugt werden soll
 * @return Anzahl der Seiten
 * @throws DocumentException
 * @throws IOException
 */
private int erzeugeInhaltsverzeichnis(Document docPdf, boolean temp) throws DocumentException, IOException {

    int anzPages = 0;
    Document docInhalt = docPdf;
    String filePathTempInhaltString = "";

    if (temp) {
        // temp. Dateinamen bestimmen
        File fileDokuFile = new File(dateiname);
        filePathTempInhaltString = fileDokuFile.getParent() + "/tmp_inhalt.pdf";
        // Neues Dokument erzeugen
        docInhalt = initPdfWriterAndDocument(filePathTempInhaltString, false);
    }

    // berschrift
    Chapter currChapter = new Chapter(getParagraphChapter("Inhaltsverzeichnis"), 0);
    // 0, damit keine Nummerierung
    currChapter.setNumberDepth(0);
    docInhalt.add(currChapter);
    // eine Zeile Abstand
    docInhalt.add(getEmptyLineTextHalf());

    for (ContPdfEntry currEntry : listEntries) {

        // Eintrag erzeugen inkl. Abstand
        String strEintrag = currEntry.getBezeichnung() + "  ";
        Chunk chunkBezeichnung;
        Chunk chunkSeitenzahlChunk;
        if (currEntry.getParentEntry() == null) {
            // 1. Ebene => fett, Abstand davor einfgen
            docInhalt.add(getEmptyLineTextHalf());
            chunkBezeichnung = getChunkTextBold(strEintrag);
            chunkSeitenzahlChunk = getChunkTextBold("" + currEntry.getPageNumber());
        } else {
            // 2. Ebene
            chunkBezeichnung = getChunkText(strEintrag);
            chunkSeitenzahlChunk = getChunkText("" + currEntry.getPageNumber());
        }
        // Referenz setzen
        chunkBezeichnung.setLocalGoto(currEntry.getDestination());
        chunkSeitenzahlChunk.setLocalGoto(currEntry.getDestination());
        // Abstandzeichen generieren, Breite auffllen
        float widthAbstand = docInhalt.getPageSize().getWidth() * 0.81f;
        ;
        while (chunkBezeichnung.getWidthPoint() <= widthAbstand) {
            chunkBezeichnung.append(".");
        }

        // Tabelle erzeugen und formatieren
        PdfPTable currTable = new PdfPTable(2);
        currTable.setWidthPercentage(100f);
        currTable.setWidths(new int[] { 96, 4 });

        // Inhalte einfgen
        // Zelle Bezeichnung
        PdfPCell currCellBezeichnung = new PdfPCell(new Phrase(chunkBezeichnung));
        currCellBezeichnung.setBorder(0);
        currCellBezeichnung.setHorizontalAlignment(Element.ALIGN_JUSTIFIED_ALL);

        // Zelle Seitennummer
        PdfPCell currCellPageNumberCell = new PdfPCell(new Phrase(chunkSeitenzahlChunk));
        currCellPageNumberCell.setBorder(0);
        currCellPageNumberCell.setHorizontalAlignment(Element.ALIGN_RIGHT);

        // Zellen zur Tabelle hinzufgen
        currTable.addCell(currCellBezeichnung);
        currTable.addCell(currCellPageNumberCell);

        docInhalt.add(currTable);
    }

    if (temp) {
        // Dokument schlieen
        docInhalt.close();

        // Anzahl der Seitenzahlen bestimmen
        PdfReader reader = new PdfReader(filePathTempInhaltString);
        anzPages = reader.getNumberOfPages();
        reader.close();

        // temp. Datei lschen
        File currFileInhaltFile = new File(filePathTempInhaltString);
        currFileInhaltFile.delete();
    }
    return anzPages;
}

From source file:de.fau.osr.util.matrix.MatrixTools.java

License:Open Source License

/**
 * /**//from  w w  w.  j av  a 2 s . c  om
 * saves matrix to {@code path} in pdf format
 * @param matrix matrix to save
 * @param path file where matrix will be saved
 */
public static boolean SaveMatrixToPdf(RequirementsTraceabilityMatrixByImpact matrix, File path,
        String matrixTitle) {
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        document.addTitle(matrixTitle);

        Paragraph headerPar = new Paragraph("Traceability Matrix");
        headerPar.add(new Paragraph(" ")); //new line
        document.add(headerPar);

        java.util.List<String> reqs = matrix.getRequirements();

        //table setup
        PdfPTable table = new PdfPTable(reqs.size() + 1); //reqs + "file name" col
        table.setHeaderRows(1);
        table.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0);
        table.setSpacingAfter(0);

        //file name col width/req col width 4:1
        float[] widths = new float[reqs.size() + 1];
        widths[0] = 4;
        for (int i = 0; i < reqs.size(); i++) {
            widths[i + 1] = 1;
        }
        table.setWidths(widths);

        //header row
        //add filename col to header
        addCell(table, "File name", 10, Element.ALIGN_LEFT);
        //add req cols to header
        for (String req : reqs) {
            addCell(table, "req-" + req, 8, Element.ALIGN_CENTER);
        }
        //content, row by row:
        for (int i = 0; i < matrix.getFiles().size(); i++) {
            //filename col
            String fileName = matrix.getFiles().get(i);
            addCell(table, fileName, 5, Element.ALIGN_LEFT, 18);

            //impact value cols
            for (String req : reqs) {
                RequirementFileImpactValue value = matrix
                        .getImpactValue(new RequirementFilePair(req, fileName));
                if (value == null) {
                    value = new RequirementFileImpactValue(0);
                }
                //round
                DecimalFormat df = new DecimalFormat("#.##");
                df.setRoundingMode(RoundingMode.CEILING);
                String valString = df.format(value.getImpactPercentage());

                addCell(table, valString, 10, Element.ALIGN_CENTER);
            }
        }

        document.add(table);

    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } finally {
        document.close();
    }
    return true;

}

From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java

License:Open Source License

public static PdfPTable setupTable(int paperWidthPoints, int marginsPoints, int labelWidthPoints, int columns,
        int subCellColumnCount, float relWidthTextCell, float relWidthBarcodeCell) throws DocumentException {
    PdfPTable table = new PdfPTable(subCellColumnCount);
    table.setLockedWidth(true); // force use of totalWidth in points, rather than percentWidth.
    float percentWidth = ((((float) paperWidthPoints) - (2f * ((float) marginsPoints)))
            / ((float) paperWidthPoints)) * 100f;
    //percentWidth = 100f;
    log.debug("Table Width Percent = " + percentWidth);
    table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
    float[] cellWidthsRatio = new float[subCellColumnCount];
    int cellNumber = 0;
    for (int c = 0; c < columns; c++) {
        cellWidthsRatio[cellNumber] = relWidthTextCell; // width of text cell
        cellNumber++;//from   w  ww  . j a v  a 2  s. c o m
        if (subCellColumnCount > 1) {
            cellWidthsRatio[cellNumber] = relWidthBarcodeCell; // width of barcode cell
            cellNumber++;
        }
    }
    table.setTotalWidth(paperWidthPoints - 2 * marginsPoints);
    // must set total width before setting relative cell widths.
    table.setWidths(cellWidthsRatio);
    log.debug("Width:" + table.getTotalWidth());
    return table;
}

From source file:edu.uc.modulocontable.general.GenerarKardexPDF.java

private void cabeceraTabla() throws DocumentException {
    PdfPTable tablePanelInicial = new PdfPTable(4);
    tablePanelInicial.setWidthPercentage(100);
    tablePanelInicial.setWidths(new int[] { 28, 15, 15, 15 });
    tablePanelInicial.getDefaultCell().setBorder(5);
    tablePanelInicial.setHorizontalAlignment(2);

    PdfPCell cell = new PdfPCell(new Paragraph("", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);/* www  .jav a 2  s  .c o  m*/
    cell.setBorder(0);
    tablePanelInicial.addCell(cell);

    cell = new PdfPCell(new Paragraph("Entrada", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);
    tablePanelInicial.addCell(cell);

    cell = new PdfPCell(new Paragraph("Salida", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);
    tablePanelInicial.addCell(cell);

    cell = new PdfPCell(new Paragraph("Saldo", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);
    tablePanelInicial.addCell(cell);

    documento.add(tablePanelInicial);
}

From source file:edu.uc.modulocontable.transaccion.GenerarComprobacion.java

private void cabeceraTabla() throws DocumentException {
    PdfPTable tablePanelInicial = new PdfPTable(5);
    tablePanelInicial.setWidthPercentage(100);
    tablePanelInicial.setWidths(new int[] { 10, 5, 5, 5, 5 });
    tablePanelInicial.getDefaultCell().setBorder(5);
    tablePanelInicial.setHorizontalAlignment(2);

    PdfPCell cell = new PdfPCell(new Paragraph("", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);/*from  w  w w .ja  va  2 s.  c o  m*/
    cell.setBorder(0);
    tablePanelInicial.addCell(cell);

    cell = new PdfPCell(new Paragraph("Suma", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);
    tablePanelInicial.addCell(cell);

    cell = new PdfPCell(new Paragraph("Saldos", FontFactory.getFont("arial", 10, Font.BOLD)));
    cell.setHorizontalAlignment(1);
    tablePanelInicial.addCell(cell);

    documento.add(tablePanelInicial);
}