Example usage for com.lowagie.text.pdf PdfPCell setHorizontalAlignment

List of usage examples for com.lowagie.text.pdf PdfPCell setHorizontalAlignment

Introduction

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

Prototype

public void setHorizontalAlignment(int horizontalAlignment) 

Source Link

Document

Sets the horizontal alignment for the cell.

Usage

From source file:permit.PermitPdf.java

License:Open Source License

/**
 * handles the letter header/* w w  w  . ja  va 2 s.c  o m*/
 */
PdfPTable getHeader() {
    //
    String str = "";
    String spacer = "   ";
    //
    PdfPTable headTable = null;
    try {
        //
        // for http url use
        //
        Image image = Image.getInstance(url + "js/images/city_logo3.jpg");

        Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
        Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
        float[] widths = { 25f, 40f, 35f }; // percentages
        headTable = new PdfPTable(widths);
        headTable.setWidthPercentage(100);
        headTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        headTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        // image.setWidthPercentage(33.0f);
        image.scalePercent(15f);
        PdfPCell cell = new PdfPCell(image);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        headTable.addCell(cell);
        //
        float[] width = { 33f };
        PdfPTable midTable = new PdfPTable(width);
        midTable.setWidthPercentage(33);
        midTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        midTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        Phrase phrase = new Phrase();
        Chunk ch = new Chunk("City of Bloomington ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        midTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("Planning and Transportation Department ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        midTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("bloomington.in.gov", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        midTable.addCell(cell);
        //
        headTable.addCell(midTable);
        //
        PdfPTable rightTable = new PdfPTable(width);
        rightTable.setWidthPercentage(33);
        rightTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        rightTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        phrase = new Phrase();
        ch = new Chunk("401 N Morton St Suite 130 ", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("PO Box 100 \nBloomington, IN 47404", fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("\n Phone: (812) 349-3423\nFax (812) 349-3520\nEmail: planning@bloomington.in.gov",
                fntb);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        headTable.addCell(rightTable);
    } catch (Exception ex) {
        logger.error(ex);
    }
    return headTable;
}

From source file:permit.PermitPdf.java

License:Open Source License

void writePage(HttpServletResponse res, Permit permit) {
    ///*ww  w.  j  av a2 s.c  o  m*/
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    String fileName = "row_permit_" + permit.getId() + ".pdf";
    Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
    Document document = new Document(pageSize, 36, 36, 18, 18);
    ServletOutputStream out = null;
    Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
    Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fnts = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL);
    Font fntbs = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    String spacer = "   ";
    PdfPTable header = getHeader();
    Bond bond = permit.getBond();
    Invoice invoice = permit.getInvoice();
    if (bond == null)
        bond = new Bond();
    if (invoice == null)
        invoice = new Invoice();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        String str = "";
        document.open();
        document.add(header);
        //
        // title
        float[] width = { 100f }; // one cell
        PdfPTable table = new PdfPTable(width);
        table.setWidthPercentage(100.0f);
        PdfPCell cell = new PdfPCell(new Phrase("Right Of Way Excavation Permit", fntb));
        //         
        cell.setBorder(Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        document.add(table);
        //
        // we need these later
        Paragraph pp = new Paragraph();
        Chunk ch = new Chunk(" ", fntb);
        Phrase phrase = new Phrase();
        //
        float[] widths = { 14f, 20f, 17f, 18f, 13f, 20f }; // percentages
        table = new PdfPTable(widths);
        table.setWidthPercentage(100.0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        // first row
        cell = new PdfPCell(new Phrase("Company", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getCompany().getName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Status", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getStatus(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Permit", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getPermit_num(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 2nd row
        //
        cell = new PdfPCell(new Phrase("Responsible", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getContact().getFullName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Inspector", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getReviewer().getFullName(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Date Issued", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getDate(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 3rd row
        cell = new PdfPCell(new Phrase("Project", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getProject(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Permit Fee", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("$" + permit.getFee(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Start Date", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(permit.getStart_date(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        // 4th row
        cell = new PdfPCell(new Phrase("Bond Amount", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("$" + bond.getAmount(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Expiration Date", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(bond.getExpire_date(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Invoice", fntb));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(invoice.getStatus(), fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        document.add(table);
        //
        phrase = new Phrase(new Chunk(spacer, fnt));
        document.add(phrase);
        //
        float[] widths2 = { 25f, 15f, 15f, 25f, 10f, 10f };
        table = new PdfPTable(widths2);
        table.setWidthPercentage(100.0f);
        cell = new PdfPCell(new Phrase("Address", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Cut Type", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Utility", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Description", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Width", fntb));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("Length", fntb));
        table.addCell(cell);
        List<Excavation> list = permit.getExcavations();
        if (list != null && list.size() > 0) {
            for (Excavation one : list) {
                cell = new PdfPCell(new Phrase(one.getAddress().getAddress(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getCut_type(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getUtility_type().getName(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getCut_description(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getWidth(), fnt));
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(one.getLength(), fnt));
                table.addCell(cell);
            }
        }
        document.add(table);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.setLeading(0f, 1f);
        ch = new Chunk("\nSpecial Provisions\n", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        ch = new Chunk(permit.getNotes() + "\n", fnt);
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        ch = new Chunk("Standards Conditions of Approval\n", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        pp = new Paragraph();
        pp.setIndentationLeft(12);
        pp.setAlignment(Element.ALIGN_LEFT);
        pp.setLeading(0f, 1f);
        ch = new Chunk("1 - " + conditions[0] + "\n", fntbs);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        //
        int jj = 1;
        for (int j = 1; j < conditions.length; j++) {
            jj = j + 1;
            pp = new Paragraph();
            pp.setLeading(0f, 1f);
            pp.setIndentationLeft(12);
            pp.setAlignment(Element.ALIGN_LEFT);
            ch = new Chunk(jj + " - " + conditions[j] + "\n", fnts);
            phrase = new Phrase();
            phrase.add(ch);
            pp.add(phrase);
            document.add(pp);
        }

        pp = new Paragraph();
        pp.setIndentationLeft(20);
        pp.setAlignment(Element.ALIGN_RIGHT);
        ch = new Chunk("\n\n___________________\n", fnt);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        ch = new Chunk(permit.getReviewer().getFullName(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        pp.add(phrase);
        document.add(pp);
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        logger.error(ex);
    }

}

From source file:permit.ReceiptPdf.java

License:Open Source License

void writePages(HttpServletResponse res, Receipt receipt) {
    ////from   w  w  w . j ava 2 s  . com
    // paper size legal (A4) 8.5 x 11
    // page 1-inch = 72 points
    //
    Invoice invoice = receipt.getInvoice();
    String fileName = "row_receipt_" + receipt.getId() + ".pdf";
    Rectangle pageSize = new Rectangle(612, 792); // 8.5" X 11"
    Document document = new Document(pageSize, 36, 36, 18, 18);
    ServletOutputStream out = null;
    Font fnt = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
    Font fntb = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fnts = new Font(Font.TIMES_ROMAN, 8, Font.NORMAL);
    Font fntbs = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    String spacer = "   ";
    PdfPTable header = getHeader();
    Company company = invoice.getCompany();
    Contact contact = null;
    if (invoice.hasContact()) {
        contact = invoice.getContact();
    }
    List<Page> pages = invoice.getPages();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        String str = "";
        document.open();
        document.add(header);
        //
        // title
        float[] width = { 100f }; // one cell
        PdfPTable table = new PdfPTable(width);
        table.setWidthPercentage(100.0f);
        PdfPCell cell = new PdfPCell(new Phrase("RECEIPT", fntb));
        //         
        cell.setBorder(Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        document.add(table);
        //
        // we need these later
        Paragraph pp = new Paragraph();
        Chunk ch = new Chunk(" ", fntb);
        Phrase phrase = new Phrase();
        //
        float[] widths = { 35f, 30f, 35f }; // percentages
        table = new PdfPTable(widths);
        table.setWidthPercentage(100.0f);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        // first row
        float[] widthOne = { 100f };
        PdfPTable leftTable = new PdfPTable(widthOne);
        leftTable.setWidthPercentage(35.0f);
        leftTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        if (company != null) {
            ch = new Chunk("Company\n", fntb);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(company.getName() + "\n", fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        if (contact != null) {
            phrase = new Phrase();
            ch = new Chunk(contact.getFullName(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            phrase = new Phrase();
            ch = new Chunk(contact.getAddress(), fnt);
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
            ch = new Chunk(contact.getCityStateZip(), fnt);
            phrase = new Phrase();
            phrase.add(ch);
            cell = new PdfPCell(phrase);
            cell.setBorder(Rectangle.NO_BORDER);
            leftTable.addCell(cell);
        }
        table.addCell(leftTable);
        //
        // middle cell
        //
        cell = new PdfPCell(new Phrase(spacer, fnt));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        //
        float[] widths2 = { 50f, 50f }; // percentages
        PdfPTable rightTable = new PdfPTable(widths2);
        rightTable.setWidthPercentage(35.0f);
        rightTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        //
        ch = new Chunk("Receipt No.", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(receipt.getId(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Invoice No.", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(invoice.getInvoice_num(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Receipt Date", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk(receipt.getDate(), fnt);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Amount Paid $", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk("$" + receipt.getAmount_paid(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        ch = new Chunk("Payment Method ", fntb);
        phrase = new Phrase();
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        phrase = new Phrase();
        ch = new Chunk(receipt.getPayment_type(), fnt);
        phrase.add(ch);
        cell = new PdfPCell(phrase);
        cell.setBorder(Rectangle.NO_BORDER);
        rightTable.addCell(cell);
        //
        table.addCell(rightTable);
        //
        document.add(table);
        //
        phrase = new Phrase(new Chunk(spacer, fnt));
        document.add(phrase);
        //
        int jj = 0;
        if (pages != null) {
            for (Page page : pages) {
                jj++;
                PdfPTable borderTable = new PdfPTable(widthOne);
                borderTable.setWidthPercentage(100.0f);
                borderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                float[] widthTwo = { 50f, 50f };
                PdfPTable titleTable = new PdfPTable(widthTwo);
                titleTable.setWidthPercentage(75.0f);
                titleTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                phrase = new Phrase("Receipt Number ", fntb);
                ch = new Chunk(receipt.getId(), fnt);
                phrase.add(ch);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                phrase = new Phrase(page.getPage_num(), fnt);
                cell = new PdfPCell(phrase);
                cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                cell.setBorder(Rectangle.NO_BORDER);
                titleTable.addCell(cell);
                //
                borderTable.addCell(titleTable);
                float[] width4 = { 25f, 40f, 25f, 10f };
                PdfPTable contTable = new PdfPTable(width4);
                cell = new PdfPCell(new Phrase("Excavation Permit Number", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Project", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Date Issued", fntb));
                contTable.addCell(cell);
                cell = new PdfPCell(new Phrase("Permit Fee", fntb));
                contTable.addCell(cell);
                List<Permit> permits = page.getPermits();
                if (permits != null) {
                    for (Permit permit : permits) {
                        cell = new PdfPCell(new Phrase(permit.getPermit_num(), fnt));
                        contTable.addCell(cell);
                        phrase = new Phrase(permit.getProject() + "\n", fnt);
                        List<Excavation> cuts = permit.getExcavations();
                        if (cuts != null) {
                            for (Excavation one : cuts) {
                                ch = new Chunk(one.getAddress() + " (" + one.getCut_type() + ")", fnt);
                                phrase.add(ch);
                            }
                        }
                        cell = new PdfPCell(phrase);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(permit.getDate(), fnt));
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase("$" + permit.getFee(), fnt));
                        cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                        contTable.addCell(cell);
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        //
                        // space line
                        //
                        cell.setColspan(4);
                        contTable.addCell(cell);
                    }
                }
                if (page.getNeededLines() > 0) { // first page 
                    for (int j = 0; j < page.getNeededLines(); j++) {
                        cell = new PdfPCell(new Phrase(spacer, fnt));
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                        contTable.addCell(cell);
                    }
                }
                if (jj == pages.size()) {
                    cell = new PdfPCell(new Phrase("Total Invoice Amount\n" + invoice.getTotal(), fntb));
                    cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
                    cell.setColspan(4);
                    contTable.addCell(cell);
                }
                borderTable.addCell(contTable);
                cell = new PdfPCell(new Phrase("Thank You.", fnt));

                cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                cell.setBorder(Rectangle.NO_BORDER);
                borderTable.addCell(cell);
                borderTable.addCell(titleTable); // receipt and date
                document.add(borderTable);
                if (jj < pages.size()) {
                    document.newPage();
                }
            }
        }
        //
        document.close();
        writer.close();
        res.setHeader("Expires", "0");
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        // res.setHeader("Content-Disposition","attachment; filename="+fileName);         
        res.setHeader("Pragma", "public");
        //
        // setting the content type
        res.setContentType("application/pdf");
        //
        // the contentlength is needed for MSIE!!!
        res.setContentLength(baos.size());
        //
        out = res.getOutputStream();
        if (out != null) {
            baos.writeTo(out);
        }
    } catch (Exception ex) {
        logger.error(ex);
    }

}

From source file:pruebareportes.rptEmpleadosSinMarcar.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**/*from   w  w  w.j av  a  2s.co m*/
     * Procesamiento para info para generar tablas
     */
    //List<RegistroAsistencia> registros = rg.buscarXEmpleadoXFecha1(dnis, fechaInicio, fechaFin);
    Calendar fechaInicioC = Calendar.getInstance();
    Calendar fechaFinC = Calendar.getInstance();
    fechaInicioC.setTime(fechaInicio);
    fechaFinC.setTime(fechaFin);

    int diaMesInicio, diaMesFin;
    diaMesInicio = fechaInicioC.get(Calendar.DAY_OF_MONTH);
    diaMesFin = fechaFinC.get(Calendar.DAY_OF_MONTH);
    //Definir numero de columnas de dias
    //        ArrayList<Integer> listaInt = new ArrayList<Integer>();
    //        Calendar fechaRegistro = Calendar.getInstance();
    //        for(RegistroAsistencia registro:registros){
    //            fechaRegistro.setTime(registro.getFecha());
    //            Integer diaRegistro = fechaRegistro.get(Calendar.DAY_OF_MONTH);
    //            if(listaInt.contains(diaRegistro)!=true){
    //                if(diaRegistro>=diaMesInicio && diaRegistro<=diaMesFin){
    //                    listaInt.add(diaRegistro);
    //                }
    //            }
    //        }
    //Ordenamos arraylist
    //        int indice,menor,aux;
    //        for (int i = 0; i < listaInt.size(); i++) {
    //            menor = listaInt.get(i);
    //            indice = i;
    //            aux=0;
    //            for (int j = i+1; j < listaInt.size(); j++) {
    //                aux = listaInt.get(j);
    //                indice = aux < menor ? j : indice;
    //                menor = aux < menor ? aux : menor;
    //            }
    //            listaInt.set(indice, listaInt.get(i));
    //            listaInt.set(i,menor);
    //        }
    /**
     * Procesamiento para elaborar tabla con datos
     */
    int nroColumnas = 1;
    PdfPTable tabla = new PdfPTable(nroColumnas);
    tabla.setWidthPercentage(100);
    //Asignamos los tamaos a las columnas
    //        int[] widthColumna = new int[nroColumnas];
    //        for (int i = 0; i < nroColumnas; i++) {
    //            if(i==0){
    //                widthColumna[i]=6;
    //            }else if(i==(nroColumnas-1)){
    //                widthColumna[i]=2;
    //            }else{
    //                widthColumna[i]=1;
    //            }
    //        }
    //        tabla.setWidths(widthColumna);
    //Definimos celdas iniciales
    Font fontCabecera = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fontCelda = new Font(Font.TIMES_ROMAN, 9);
    PdfPCell h1 = new PdfPCell(new Phrase("Nombre del empleado", fontCabecera));
    h1.setHorizontalAlignment(3);
    h1.setGrayFill(0.7f);
    h1.setRowspan(1);
    h1.setColspan(1);
    tabla.addCell(h1);

    //        PdfPCell h2 = new PdfPCell(new Phrase("Das Hbiles",fontCabecera));
    //        h2.setHorizontalAlignment(1);
    //        h2.setGrayFill(0.7f);
    //        h2.setColspan(nroColumnas-2);
    //        tabla.addCell(h2);
    //        
    //        PdfPCell h3 = new PdfPCell(new Phrase("Total (minutos)",fontCabecera));
    //        h3.setHorizontalAlignment(3);
    //        h3.setGrayFill(0.7f);
    //        h3.setColspan(1);
    //        h3.setRowspan(2);
    //        tabla.addCell(h3);

    //        PdfPCell diaColumna = new PdfPCell();
    //        for (int i = 0; i < (nroColumnas-2); i++) {
    //            String celda = (listaInt.get(i).toString());
    //            diaColumna.setPhrase(new Phrase(celda,fontCabecera));
    //            diaColumna.setHorizontalAlignment(1);
    //            tabla.addCell(diaColumna);
    //        }
    Calendar cal = Calendar.getInstance();
    List<Integer> conteoDias = new ArrayList<Integer>();

    //        for (int i = 0; i < dnis.size(); i++) {
    //            
    //            List<Empleado> listaEmpleado = new ArrayList<Empleado>();
    //            listaEmpleado = em.buscarXPatron(dnis.get(i));
    //            Empleado empleado = new Empleado();
    //            empleado = listaEmpleado.get(0);
    //            BigDecimal totalTardanza= new BigDecimal(0.00);
    //            PdfPCell celdaNombre = new PdfPCell(new Phrase(empleado.getApellidoPaterno()+" "+empleado.getApellidoMaterno()+" "+empleado.getNombre(),fontCelda));
    //            celdaNombre.setHorizontalAlignment(0);
    //            tabla.addCell(celdaNombre);
    //            List<RegistroAsistencia> registrosDni = rg.buscarXEmpleadoXFecha2(dnis.get(i), fechaInicio, fechaFin);
    //            System.out.println("Numero de registros: "+registrosDni.size());
    //            
    ////            for (RegistroAsistencia registro : registrosDni) {
    ////                cal.setTime(registro.getFecha());
    ////                for (int j = 0; j < listaInt.size(); j++) {
    ////                    if(cal.get(Calendar.DAY_OF_MONTH)==listaInt.get(j)){
    ////                        if(registro.getMinTardanza()!=null){
    ////                            int numero = registro.getMinTardanza().intValue();
    ////                            String celda = ""+numero;
    ////                            celdaNombre.setPhrase(new Phrase(celda,fontCelda));
    ////                            celdaNombre.setHorizontalAlignment(1);
    ////                            tabla.addCell(celdaNombre);                       
    ////                            totalTardanza = totalTardanza.add(registro.getMinTardanza());
    ////                        }else{
    ////                            String celda = "0.0";
    ////                            celdaNombre.setPhrase(new Phrase(celda,fontCelda));
    ////                            celdaNombre.setHorizontalAlignment(1);
    ////                            tabla.addCell(celdaNombre);
    ////                        }
    ////                        conteoDias.add(listaInt.get(j));
    ////                        break;
    ////                    }else{
    ////                        if(conteoDias.contains(listaInt.get(j))){
    ////                            
    ////                        }else{
    ////                            String celda = "n.r";
    ////                            celdaNombre.setPhrase(new Phrase(celda,fontCelda));
    ////                            celdaNombre.setHorizontalAlignment(1);
    ////                            tabla.addCell(celdaNombre);
    ////                            conteoDias.add(listaInt.get(j));
    ////                        }                       
    ////                    }
    ////                }
    ////            }
    ////            if(registrosDni.size()<(nroColumnas-2)){
    ////                int dfNumRegistros = (nroColumnas-2)-registrosDni.size();
    ////                for (int j = 0; j < dfNumRegistros; j++) {
    ////                    String celda = "n.r";
    ////                    celdaNombre.setPhrase(new Phrase(celda,fontCelda));
    ////                    celdaNombre.setHorizontalAlignment(1);
    ////                    tabla.addCell(celdaNombre);
    ////                }
    ////            }
    //           
    //            
    ////            System.out.println("ConteoDias: "+conteoDias.size());
    ////            System.out.println("Total tardanzas: "+totalTardanza);
    ////            conteoDias.clear();
    ////            String tardanzaTotal = totalTardanza.toString();
    ////            celdaNombre.setPhrase(new Phrase(tardanzaTotal,fontCelda));
    ////            celdaNombre.setHorizontalAlignment(1);
    ////            tabla.addCell(celdaNombre);
    //        }
    return tabla;
}

From source file:pruebareportes.rptTardC.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**//from   ww w.j a va  2 s. co m
     * Procesamiento para info para generar tablas
     */
    List<RegistroAsistencia> registros = rg.buscarXEmpleadoXFecha1(dnis, fechaInicio, fechaFin);
    Calendar fechaInicioC = Calendar.getInstance();
    Calendar fechaFinC = Calendar.getInstance();
    fechaInicioC.setTime(fechaInicio);
    fechaFinC.setTime(fechaFin);

    int diaMesInicio, diaMesFin;
    diaMesInicio = fechaInicioC.get(Calendar.DAY_OF_MONTH);
    diaMesFin = fechaFinC.get(Calendar.DAY_OF_MONTH);
    //Definir numero de columnas de dias
    ArrayList<Integer> listaInt = new ArrayList<Integer>();
    Calendar fechaRegistro = Calendar.getInstance();
    for (RegistroAsistencia registro : registros) {
        fechaRegistro.setTime(registro.getFecha());
        Integer diaRegistro = fechaRegistro.get(Calendar.DAY_OF_MONTH);
        if (listaInt.contains(diaRegistro) != true) {
            if (diaRegistro >= diaMesInicio && diaRegistro <= diaMesFin) {
                listaInt.add(diaRegistro);
            }
        }
    }
    //Ordenamos arraylist
    int indice, menor, aux;
    for (int i = 0; i < listaInt.size(); i++) {
        menor = listaInt.get(i);
        indice = i;
        aux = 0;
        for (int j = i + 1; j < listaInt.size(); j++) {
            aux = listaInt.get(j);
            indice = aux < menor ? j : indice;
            menor = aux < menor ? aux : menor;
        }
        listaInt.set(indice, listaInt.get(i));
        listaInt.set(i, menor);
    }
    /**
     * Procesamiento para elaborar tabla con datos
     */
    int nroColumnas = listaInt.size() + 2;
    PdfPTable tabla = new PdfPTable(nroColumnas);
    tabla.setWidthPercentage(100);
    //Asignamos los tamaos a las columnas
    int[] widthColumna = new int[nroColumnas];
    for (int i = 0; i < nroColumnas; i++) {
        if (i == 0) {
            widthColumna[i] = 6;
        } else if (i == (nroColumnas - 1)) {
            widthColumna[i] = 2;
        } else {
            widthColumna[i] = 1;
        }
    }
    tabla.setWidths(widthColumna);
    //Definimos celdas iniciales
    Font fontCabecera = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fontCelda = new Font(Font.TIMES_ROMAN, 9);
    PdfPCell h1 = new PdfPCell(new Phrase("Nombre del empleado", fontCabecera));
    h1.setHorizontalAlignment(3);
    h1.setGrayFill(0.7f);
    h1.setRowspan(2);
    h1.setColspan(1);
    tabla.addCell(h1);

    PdfPCell h2 = new PdfPCell(new Phrase("Das Hbiles", fontCabecera));
    h2.setHorizontalAlignment(1);
    h2.setGrayFill(0.7f);
    h2.setColspan(nroColumnas - 2);
    tabla.addCell(h2);

    PdfPCell h3 = new PdfPCell(new Phrase("Total (minutos)", fontCabecera));
    h3.setHorizontalAlignment(3);
    h3.setGrayFill(0.7f);
    h3.setColspan(1);
    h3.setRowspan(2);
    tabla.addCell(h3);

    PdfPCell diaColumna = new PdfPCell();
    for (int i = 0; i < (nroColumnas - 2); i++) {
        String celda = (listaInt.get(i).toString());
        diaColumna.setPhrase(new Phrase(celda, fontCabecera));
        diaColumna.setHorizontalAlignment(1);
        tabla.addCell(diaColumna);
    }
    Calendar cal = Calendar.getInstance();
    List<Integer> conteoDias = new ArrayList<Integer>();

    for (int i = 0; i < dnis.size(); i++) {

        List<Empleado> listaEmpleado = new ArrayList<Empleado>();
        listaEmpleado = em.buscarXPatron(dnis.get(i));
        Empleado empleado = new Empleado();
        empleado = listaEmpleado.get(0);
        BigDecimal totalTardanza = new BigDecimal(0.00);
        PdfPCell celdaNombre = new PdfPCell(new Phrase(empleado.getApellidoPaterno() + " "
                + empleado.getApellidoMaterno() + " " + empleado.getNombre(), fontCelda));
        celdaNombre.setHorizontalAlignment(0);
        tabla.addCell(celdaNombre);
        List<RegistroAsistencia> registrosDni = rg.buscarXEmpleadoXFecha2(dnis.get(i), fechaInicio, fechaFin);
        System.out.println("Numero de registros: " + registrosDni.size());
        if (!registrosDni.isEmpty()) {
        }
        for (RegistroAsistencia registro : registrosDni) {
            cal.setTime(registro.getFecha());
            for (int j = 0; j < listaInt.size(); j++) {
                if (cal.get(Calendar.DAY_OF_MONTH) == listaInt.get(j)) {
                    if (registro.getMinTardanza() != null) {
                        int numero = registro.getMinTardanza().intValue();
                        String celda = "" + numero;
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                        totalTardanza = totalTardanza.add(registro.getMinTardanza());
                    } else {
                        String celda = "0.0";
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                    }
                    conteoDias.add(listaInt.get(j));
                    break;
                } else {
                    if (conteoDias.contains(listaInt.get(j))) {

                    } else {
                        String celda = "n.r";
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                        conteoDias.add(listaInt.get(j));
                    }
                }
            }
        }
        if (registrosDni.size() < (nroColumnas - 2)) {
            int dfNumRegistros = (nroColumnas - 2) - registrosDni.size();
            for (int j = 0; j < dfNumRegistros; j++) {
                String celda = "n.r";
                celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                celdaNombre.setHorizontalAlignment(1);
                tabla.addCell(celdaNombre);
            }
        }

        System.out.println("ConteoDias: " + conteoDias.size());
        System.out.println("Total tardanzas: " + totalTardanza);
        conteoDias.clear();
        String tardanzaTotal = totalTardanza.toString();
        celdaNombre.setPhrase(new Phrase(tardanzaTotal, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
    }
    return tabla;
}

From source file:pruebareportes.rptTardCx.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**/*from  w  w w  . ja  v  a2 s  . c o  m*/
     * Procesamiento para info para generar tablas
     */
    //List<RegistroAsistencia> registros = rg.buscarXEmpleadoXFecha1(dnis, fechaInicio, fechaFin);
    Calendar fechaInicioC = Calendar.getInstance();
    Calendar fechaFinC = Calendar.getInstance();
    fechaInicioC.setTime(fechaInicio);
    fechaFinC.setTime(fechaFin);

    int diaMesInicio, diaMesFin;
    diaMesInicio = fechaInicioC.get(Calendar.DAY_OF_MONTH);
    diaMesFin = fechaFinC.get(Calendar.DAY_OF_MONTH);

    // Dias contados desde un inicio y fin fecha
    ArrayList<Integer> listaInt = new ArrayList<>();
    for (int i = diaMesInicio; i <= diaMesFin; i++) {
        listaInt.add(i);
    }
    //Ordenamos arraylist
    int indice, menor, aux;
    for (int i = 0; i < listaInt.size(); i++) {
        menor = listaInt.get(i);
        indice = i;
        aux = 0;
        for (int j = i + 1; j < listaInt.size(); j++) {
            aux = listaInt.get(j);
            indice = aux < menor ? j : indice;
            menor = aux < menor ? aux : menor;
        }
        listaInt.set(indice, listaInt.get(i));
        listaInt.set(i, menor);
    }
    /**
     * Procesamiento para elaborar tabla con datos
     */
    //agrege una columna mas (Descuento sin goce)
    int nroColumnas = listaInt.size() + 3;
    PdfPTable tabla = new PdfPTable(nroColumnas);
    tabla.setWidthPercentage(100);
    //Asignamos los tamaos a las columnas 
    //MOdifique para tomar en cuenta la nueva columna de dewscuento
    int[] widthColumna = new int[nroColumnas];
    for (int i = 0; i < nroColumnas; i++) {
        if (i == 0) {
            widthColumna[i] = 6;
        } else if (i == (nroColumnas - 1) || i == (nroColumnas - 2)) {
            widthColumna[i] = 2;
        } else {
            widthColumna[i] = 1;
        }
    }
    tabla.setWidths(widthColumna);
    //Definimos celdas iniciales
    Font fontCabecera = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fontCelda = new Font(Font.TIMES_ROMAN, 9);
    PdfPCell h1 = new PdfPCell(new Phrase("Nombre del empleado", fontCabecera));
    h1.setHorizontalAlignment(3);
    h1.setGrayFill(0.7f);
    h1.setRowspan(2);
    h1.setColspan(1);
    tabla.addCell(h1);

    PdfPCell h2 = new PdfPCell(new Phrase("Das Hbiles", fontCabecera));
    h2.setHorizontalAlignment(1);
    h2.setGrayFill(0.7f);
    h2.setColspan(nroColumnas - 3);
    tabla.addCell(h2);

    PdfPCell h3 = new PdfPCell(new Phrase("Total (minutos)", fontCabecera));
    h3.setHorizontalAlignment(3);
    h3.setGrayFill(0.7f);
    h3.setColspan(1);
    h3.setRowspan(2);
    tabla.addCell(h3);

    //Agregado de columna de descuento sin goce
    PdfPCell h4 = new PdfPCell(new Phrase("Descuento S/G", fontCabecera));
    h4.setHorizontalAlignment(3);
    h4.setGrayFill(0.7f);
    h4.setColspan(1);
    h4.setRowspan(2);
    tabla.addCell(h4);

    PdfPCell diaColumna = new PdfPCell();
    for (int i = 0; i < (nroColumnas - 3); i++) {
        String celda = (listaInt.get(i).toString());
        diaColumna.setPhrase(new Phrase(celda, fontCabecera));
        diaColumna.setHorizontalAlignment(1);
        tabla.addCell(diaColumna);
    }
    Calendar cal = Calendar.getInstance();
    List<Integer> conteoDias = new ArrayList<>();
    int diasDescuento = 0;
    double minDescuento = 0;

    for (int i = 0; i < dnis.size(); i++) {

        List<Empleado> listaEmpleado = new ArrayList<>();
        listaEmpleado = em.buscarXPatron(dnis.get(i));
        Empleado empleado;
        empleado = listaEmpleado.get(0);
        BigDecimal totalTardanza = new BigDecimal(0.00);
        PdfPCell celdaNombre = new PdfPCell(new Phrase(empleado.getApellidoPaterno() + " "
                + empleado.getApellidoMaterno() + " " + empleado.getNombre(), fontCelda));
        celdaNombre.setHorizontalAlignment(0);
        tabla.addCell(celdaNombre);
        List<RegistroAsistencia> registrosDni = rg.buscarXEmpleadoXFecha2(dnis.get(i), fechaInicio, fechaFin);
        System.out.println(
                "Numero de registros: " + registrosDni.size() + " Empleado: " + empleado.getApellidoPaterno()
                        + " " + empleado.getApellidoPaterno() + " " + empleado.getNombre());
        List<Integer> listaPermisos = new ArrayList<>();
        if (!registrosDni.isEmpty()) {
            for (RegistroAsistencia registro : registrosDni) {
                //========================DESCUENTOS LICENCIAS=================================================
                AsignacionPermiso asignaciones = asp.buscarXDia(empleado.getNroDocumento(),
                        registro.getFecha());
                if (asignaciones != null) {
                    System.out.println("Asignacion: " + asignaciones.getPermiso().toString());
                    Permiso permisoProcesar = asignaciones.getPermiso();
                    System.out.println("Tiene un permiso" + permisoProcesar.getMotivo());
                    if (permisoProcesar.getTipoPermiso().getTipoDescuento() == 'S') {
                        if (permisoProcesar.getOpcion() == 'F') {
                            if (!listaPermisos.contains(permisoProcesar.getId().intValue())) {
                                Date fechaInicio1 = permisoProcesar.getFechaInicio();
                                Date fechaFin1 = permisoProcesar.getFechaFin();
                                if (fechaInicio1.compareTo(fechaFin1) < 0) {
                                    cal.setTime(fechaInicio1);
                                    int diaInicio = cal.get(Calendar.DAY_OF_MONTH);
                                    cal.setTime(fechaFin1);
                                    int diaFin = cal.get(Calendar.DAY_OF_MONTH);
                                    diasDescuento += diaFin - diaInicio + 1;
                                } else if (fechaInicio1.compareTo(fechaFin1) == 0) {
                                    diasDescuento = 1;
                                }
                                listaPermisos.add(permisoProcesar.getId().intValue());
                            }
                        } else {
                            if (permisoProcesar.getOpcion() == 'H') {
                                Date horaInicio1 = permisoProcesar.getHoraInicio();
                                Date horaFin1 = permisoProcesar.getHoraFin();
                                if (horaInicio1.compareTo(horaFin1) < 0) {
                                    minDescuento = permisoProcesar.getHoraFin().getTime()
                                            - permisoProcesar.getHoraInicio().getTime();
                                }
                            }

                        }
                    }
                } else {
                    System.out.println("No hay registros");
                }
                //========================DESCUENTOS LICENCIAS=================================================
                cal.setTime(registro.getFecha());
                for (int j = 0; j < listaInt.size(); j++) {
                    if (cal.get(Calendar.DAY_OF_MONTH) == listaInt.get(j)) {
                        if (registro.getMinTardanza() != null) {
                            int numero = registro.getMinTardanza().intValue();
                            String celda = "" + numero;
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                            totalTardanza = totalTardanza.add(registro.getMinTardanza());
                        } else {
                            String celda = "0.0";
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                        }
                        conteoDias.add(listaInt.get(j));
                        break;
                    } else {
                        if (conteoDias.contains(listaInt.get(j))) {

                        } else {
                            String celda = "n.r";
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                            conteoDias.add(listaInt.get(j));
                        }
                    }
                }
            }
        } else {
            for (Integer dia : listaInt) {
                String celda = "n.r";
                celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                celdaNombre.setHorizontalAlignment(1);
                tabla.addCell(celdaNombre);
            }
        }

        System.out.println("ConteoDias: " + conteoDias.size());
        System.out.println("Total tardanzas: " + totalTardanza);
        conteoDias.clear();
        //String tardanzaTotal = totalTardanza.toString();
        String hora1 = "";
        if (totalTardanza.intValue() < 60) {
            hora1 = totalTardanza.intValue() + " min";
        } else if (totalTardanza.intValue() >= 60 && totalTardanza.intValue() < 480) {
            int resto = totalTardanza.intValue() % 60;
            int totalH = (totalTardanza.intValue() - resto) / 60;
            hora1 = totalH + " h " + resto + " min";
        } else if (totalTardanza.intValue() >= 480) {
            int restoHoras = totalTardanza.intValue() % 480;
            int totalD = (totalTardanza.intValue() - restoHoras) / 480;
            int restoMinutos = restoHoras % 60;
            int totalH = (restoHoras - restoMinutos) / 60;
            hora1 = totalD + " d " + totalH + " h " + restoMinutos + " m";
        }
        celdaNombre.setPhrase(new Phrase(hora1, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
        //Descuento
        int minutosT = diasDescuento * 480;
        int minutosTotal = (int) (minutosT + minDescuento);
        String hora = "";
        if (minutosTotal < 60) {
            hora = minutosTotal + " min";
        } else if (minutosTotal >= 60 && minutosTotal < 480) {
            int resto = minutosTotal % 60;
            int totalH = (minutosTotal - resto) / 60;
            hora = totalH + " h " + resto + " min";
        } else if (minutosTotal >= 480) {
            int restoHoras = minutosTotal % 480;
            int totalD = (minutosTotal - restoHoras) / 480;
            int restoMinutos = restoHoras % 60;
            int totalH = (restoHoras - restoMinutos) / 60;
            hora = totalD + " d " + totalH + " h " + restoMinutos + " m";
        }
        celdaNombre.setPhrase(new Phrase(hora, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
    }
    return tabla;
}

From source file:questions.tables.RotatedCells.java

public static void main(String[] args) {
    Document document = new Document();
    try {/*from   w  w  w.j a  v  a  2 s . c o m*/
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();

        float[] widths = { 1, 4 };
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(40);
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph("test 1"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        table.addCell("Cell without any rotation.");

        cell = new PdfPCell(new Paragraph("test 2"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(90);
        table.addCell(cell);
        table.addCell("Cell rotated 90 degrees.");

        cell = new PdfPCell(new Paragraph("test 3"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(180);
        table.addCell(cell);
        table.addCell("Cell upside down.");

        cell = new PdfPCell(new Paragraph("test 4"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(270);
        table.addCell(cell);
        table.addCell("Cell rotated 270 degrees.");
        document.add(table);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
}

From source file:questions.tables.TableHeaderAlternateBackground.java

public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4.rotate());
    try {/*from   w  w  w.  ja  v a 2  s . co m*/
        // step 2:
        // we create a writer
        PdfWriter.getInstance(
                // that listens to the document
                document,
                // and directs a PDF-stream to a file
                new FileOutputStream(RESULT));
        // step 3: we open the document
        document.open();
        // step 4: we add a table to the document
        PdfPTable datatable = new PdfPTable(10);
        datatable.setTableEvent(new AlternateBackground());
        int headerwidths[] = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 };
        datatable.setWidths(headerwidths);
        datatable.setWidthPercentage(100);
        datatable.getDefaultCell().setPadding(5);

        // The header starts with a cell that spans 10 columns
        PdfPCell cell = new PdfPCell(new Phrase("Administration - System Users Report",
                FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2);
        cell.setColspan(10);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setUseDescender(true);
        datatable.addCell(cell);
        // We need 4 cells with rowspan 2
        datatable.getDefaultCell().setBorderWidth(2);
        datatable.getDefaultCell().setBackgroundColor(Color.YELLOW);
        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell("User Id");
        datatable.addCell("Name\nAddress");
        datatable.addCell("Company");
        datatable.addCell("Department");
        datatable.getDefaultCell().setBackgroundColor(null);
        // we use a nested table to fake this
        PdfPTable permissions = new PdfPTable(6);
        permissions.getDefaultCell().setBackgroundColor(Color.YELLOW);
        permissions.getDefaultCell().setBorderWidth(2);
        permissions.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        permissions.getDefaultCell().setColspan(6);
        permissions.addCell("Permissions");
        permissions.getDefaultCell().setColspan(1);
        permissions.addCell("Admin");
        permissions.addCell("Data");
        permissions.addCell("Expl");
        permissions.addCell("Prod");
        permissions.addCell("Proj");
        permissions.addCell("Online");
        PdfPCell permission = new PdfPCell(permissions);
        permission.setColspan(6);
        datatable.addCell(permission);
        // this is the end of the table header
        // as far as PdfPTable is concerned there are 2 rows in the header
        datatable.setHeaderRows(2);

        // we add the data to the table
        datatable.getDefaultCell().setBorderWidth(1);
        for (int i = 1; i < 50; i++) {
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            datatable.addCell("myUserId");
            datatable.addCell("Person " + i);
            datatable.addCell("No Name Company");
            datatable.addCell("D" + i);
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (int j = 0; j < 6; j++)
                datatable.addCell(Math.random() > .5 ? "Yes" : "No");
        }
        document.add(datatable);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape/*ww  w.  j a va2s  .c o m*/
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

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

From source file:rollyroll.com.servlet.ModuloServlet.java

private void exportar_ModulosaPDF(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {// w w  w. j  av  a2s. c  o  m
        //            String[] headers = new String[]{"CODIGO", "NOMBRE", "ACCION", "ORDEN", "ICONO", "ESTADO"};
        String[] headers = new String[] { "NOMBRE", "ACCION", "ICONO" };

        ArrayList<Modulo> lista = null;
        lista = moduloService.listar_Modulos();

        PdfPTable table = new PdfPTable(headers.length);
        table.setHorizontalAlignment(0);
        table.setWidthPercentage(95);
        float[] espaciocolumna = new float[] { 25f, 38f, 50f };
        table.setWidths(espaciocolumna);
        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            PdfPCell cell = new PdfPCell();
            cell.setBackgroundColor(Color.YELLOW);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setPhrase(new Phrase(header.toUpperCase(), new Font(Font.HELVETICA, 10, Font.BOLD)));
            table.addCell(cell);
        }
        table.completeRow();
        PdfPCell cell;

        //            int codigomodulo = 0;
        String nombremodulo = "";
        String accionmodulo = "";
        //            int ordenmodulo = 0;
        String iconomodulo = "";
        //            int estadomodulo = 0;

        for (Modulo modulo : lista) {
            //                codigomodulo += Integer.parseInt(modulo.getCodigomodulo());
            nombremodulo += modulo.getNombremodulo();
            accionmodulo += modulo.getAccionmodulo();
            //                ordenmodulo += Integer.parseInt(modulo.getOrdenmoduloS());
            iconomodulo += modulo.getIconomodulo();
            //                estadomodulo += Byte.parseByte(modulo.getEstadomoduloS());

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getCodigomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
            //                
            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getNombremodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getAccionmodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getOrdenmoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getIconomodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getEstadomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
        }

        table.completeRow();

        //incia diseo de documento exportado
        Document document = new Document(PageSize.A4.rotate(), 20, 5, 5, 5);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();

        document.addTitle("Reporte de Ventas Generales");
        document.add(
                new Paragraph("Reporte: Ventas Generales 2016", new Font(Font.HELVETICA, 16, Font.UNDERLINE)));
        document.add(new Paragraph("_"));
        document.add(table);
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph(
                "Leyenda: AB: Inicio, BA: Retorno (Importante: No se consideran unidades sin GPS)"));
        document.addAuthor("Quispe Roque Alex Christian");

        table = new PdfPTable(4);
        table.setHorizontalAlignment(0);
        table.setWidthPercentage(40);
        espaciocolumna = new float[] { 10f, 40f, 20f, 20f };
        table.setWidths(espaciocolumna);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setPhrase(new Phrase("RESUMEN", new Font(Font.HELVETICA, 10, Font.BOLD)));
        cell.setColspan(7);
        table.addCell(cell);
        table.completeRow();

        //aqui iniciamos asignacion de datos
        //===================================================================
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setBackgroundColor(Color.yellow);
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("FLOTA OPERATIVA", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase(lista.size() + "", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("UNIDADES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //            table.completeRow();
        //
        //            //==================================================================================
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("2", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setBackgroundColor(Color.yellow);
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("NRO DE VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase((totalAB + totalBA) + "", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            table.completeRow();
        //==================================================================================
        document.add(Chunk.NEWLINE);
        document.add(table);

        document.left(1);
        document.top(1);
        document.close();
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //            response.setHeader("Content-Disposition", "attachment; filename=ReporteGeneraldeModulos.pdf");
        response.setHeader("Content-Disposition", "filename=ReporteGeneraldeModulos.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        response.setContentLength(baos.size());
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception e) {
        RequestDispatcher rd2;
        rd2 = request.getRequestDispatcher("vista/include/error_404.jsp");
        rd2.forward(request, response);
        System.out.println(
                "rollyroll.com.servlet.ModuloServlet.exportar_ModulosaPDF() => ERROR GRAVE AL GENERAR PDF");
        e.getMessage();
    }
}