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

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

Introduction

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

Prototype

public void setWidths(int relativeWidths[]) throws DocumentException 

Source Link

Document

Sets the relative widths of the table.

Usage

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getCompleteOrderPDFReport(Properties ctx, int orderId, String trxName)
        throws OperationException {
    String docStatus = null;//from w ww. j a v a2s.c  o m
    String dateOrdered = null;
    String orderType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String paymentBy = null;
    String customerName = null;
    String customerAddress = null;
    String documentNo = null;
    String currency = "Rs ";
    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol() + " ";
    MOrder order = new MOrder(ctx, orderId, trxName);

    // getting payment info
    int[] invoiceIds = MInvoice.getAllIDs(MInvoice.Table_Name,
            "AD_CLIENT_ID=" + Env.getAD_Client_ID(ctx) + " and C_ORDER_ID=" + order.get_ID(), null);
    double paymentByCash = 0.0;
    double paymentByCard = 0.0;
    double paymentByCheque = 0.0;

    MInvoice invoice = null;
    String paymentRule = null;
    boolean isMixed = false;

    for (int i = 0; i < invoiceIds.length; i++) {
        invoice = new MInvoice(ctx, invoiceIds[i], trxName);

        if (i == 0) {
            paymentRule = invoice.getPaymentRule();
        } else {
            if (!paymentRule.equalsIgnoreCase(invoice.getPaymentRule())) {
                isMixed = true;
            }
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Cash)) {
            paymentByCash += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CASH;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_CreditCard)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_DirectDebit)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Check)) {
            paymentByCheque += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CHEQUE;
        }

    } // for

    if (isMixed) {
        paymentBy = "Mixed (Cash:" + formatter.format(paymentByCash) + " Card:"
                + formatter.format(paymentByCard) + " Cheque:" + formatter.format(paymentByCheque) + ")";
    }

    // getting orgInfo
    MOrg org = new MOrg(ctx, order.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    orderType = order.getOrderType();

    // getting orderInfo
    docStatus = order.getDocStatusName();
    documentNo = order.getDocumentNo();

    Date d = new Date(order.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = order.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = order.getBill_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebOrderLineBean> orderLineList = POSManager.populateOrderLines(ctx, order);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        String imageURI = PathInfo.PROJECT_HOME + "images/logo.gif";
        // "images/pos/openBLUE_POS_Logo.gif";

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(orderType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("Ref No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 5
        cell = new PdfPCell(new Paragraph(new Chunk("Payment By: " + paymentBy, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(6);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 4, 1, 2, 2, 2 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));
        t.addCell(new Paragraph(new Chunk("Price", headerFont)));
        t.addCell(new Paragraph(new Chunk("VAT", headerFont)));
        t.addCell(new Paragraph(new Chunk("Total", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;
        int totalQty = 0;
        double totalAmt = 0.0;
        double totalTaxAmt = 0.0;
        double grandTotal = 0.0;

        BigDecimal qty = null;
        BigDecimal lineAmt = null;
        BigDecimal taxAmt = null;
        BigDecimal lineTotalAmt = null;

        for (WebOrderLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();
            lineAmt = orderlineBean.getLineNetAmt();
            taxAmt = orderlineBean.getTaxAmt();
            lineTotalAmt = orderlineBean.getLineTotalAmt();

            totalQty += qty.intValue();
            totalAmt += lineAmt.doubleValue();
            totalTaxAmt += taxAmt.doubleValue();
            grandTotal += lineTotalAmt.doubleValue();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(taxAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineTotalAmt.doubleValue()), simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // setting table footer
        t.getDefaultCell().setBackgroundColor(new Color(240, 240, 240));

        PdfPCell c = new PdfPCell(new Paragraph(new Chunk("ORDER TOTAL", headerFont)));
        c.setColspan(2);
        c.setBackgroundColor(new Color(240, 240, 240));
        t.addCell(c);

        t.addCell(new Paragraph(new Chunk(totalQty + "", simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalTaxAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(grandTotal), simpleFont)));

        t.setSplitRows(true);
        cell.addElement(t);
        // ------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

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

    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getShipmentPDFReport(Properties ctx, int minoutId, String trxName)
        throws OperationException {
    String docStatus = null;/*from   w  w w  .jav  a 2  s.c o m*/
    String dateOrdered = null;
    String docType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String phone = "      ";
    String fax = "       ";

    String customerName = null;
    String customerAddress = null;
    String documentNo = null;

    MInOut minout = MinOutManager.loadMInOut(ctx, minoutId, trxName);

    // getting orgInfo
    MOrg org = new MOrg(ctx, minout.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);
    MBPartner orgPartner = new MBPartner(ctx, org.getLinkedC_BPartner_ID(trxName), trxName);
    MBPartnerLocation meLocation[] = MBPartnerLocation.getForBPartner(ctx, orgPartner.get_ID());

    if (meLocation.length != 1)
        throw new OperationException("Should have only 1 location for organisation business partner!!");

    MBPartnerLocation orgLocation = meLocation[0];

    if (orgLocation.getPhone() != null)
        phone = orgLocation.getPhone();

    if (orgLocation.getFax() != null)
        fax = orgLocation.getFax();
    ;

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    MDocType doctype = MDocType.get(ctx, minout.getC_DocType_ID());
    docType = doctype.getName();

    // getting orderInfo
    docStatus = minout.getDocStatusName();
    documentNo = minout.getDocumentNo();

    Date d = new Date(minout.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = minout.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = minout.getC_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebMinOutLineBean> orderLineList = MinOutManager.getWebMinOutLines(ctx, minout);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        // TODO: make this part dynamic <------------------------------
        // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!
        String imageURI = PathInfo.PROJECT_HOME + "images/pos/openBLUE_POS_Logo.gif";
        logo = Image.getInstance(imageURI);

        // MAttachment attachment = new
        // MAttachment(ctx,MOrg.Table_ID,org.getID(),null);
        // logo = Image.getInstance(attachment.getEntries()[0].getData());

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Phone: " + phone, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Fax: " + fax, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(docType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        /*
         * //row 5 cell = new PdfPCell(new Paragraph(new Chunk("Payment By:
         * "+paymentBy,headerFont))); cell.setColspan(2);
         * cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
         * cell.setBorderWidth(cellBorderWidth); table.addCell(cell);
         */

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(3);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 10, 1 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;

        BigDecimal qty = null;

        for (WebMinOutLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

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

    return reportName;
}

From source file:org.posterita.core.CrossTabReportGenerator.java

License:Open Source License

protected void writeDocument(Document document) throws OperationException {
    try {/*from   w  ww .  ja va2  s. c o m*/
        int noOfRows = dataSource.size();
        String longestText = "";
        int columnCount = 0;

        Object[] obj = null;

        Object[] header = (Object[]) dataSource.get(0);
        columnCount = header.length;

        PdfPTable table = new PdfPTable(columnCount);
        table.setWidthPercentage(100);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.getDefaultCell().setPaddingBottom(5);
        table.getDefaultCell().setPaddingTop(5);

        //adding the headers
        for (int i = 0; i < columnCount; i++) {
            if (i == 0) {
                longestText = header[i].toString();
                table.addCell(new Paragraph(header[i].toString()));
            } else {
                Image img = getTextAsImage(header[i].toString());
                img.setRotationDegrees(90);
                img.setAlignment(Image.ALIGN_BOTTOM);

                PdfPCell cell = new PdfPCell(img);
                cell.setPadding(4);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
                //cell.setBackgroundColor(new Color(0, 0, 255));

                table.addCell(cell);
            }
        }

        //adding the data 
        for (int j = 1; j < noOfRows; j++) {
            obj = (Object[]) dataSource.get(j);

            for (int k = 0; k < columnCount; k++) {
                if (k == 0) {
                    String text = obj[0].toString();

                    if (new Chunk(text, HEADER_FONT).getWidthPoint() > new Chunk(longestText, HEADER_FONT)
                            .getWidthPoint()) {
                        longestText = text;
                    }

                    Chunk txtck = new Chunk(obj[0].toString(), HEADER_FONT);
                    PdfPCell cell = new PdfPCell(new Paragraph(txtck));

                    if (j == noOfRows - 1) {
                        cell.setBackgroundColor(new Color(170, 170, 170));
                    }

                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell.setPaddingBottom(5);
                    cell.setPaddingTop(5);
                    cell.setPaddingLeft(5);

                    table.addCell(cell);
                } else {
                    Chunk txtck = new Chunk(obj[k].toString(), DATA_FONT);

                    if (k == columnCount - 1) {
                        PdfPCell cell = new PdfPCell(new Paragraph(txtck));
                        cell.setBackgroundColor(new Color(170, 170, 170));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setPaddingBottom(5);
                        cell.setPaddingTop(5);

                        table.addCell(cell);
                    } else {
                        PdfPCell cell = new PdfPCell(new Paragraph(txtck));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setPaddingBottom(5);
                        cell.setPaddingTop(5);

                        if (j == noOfRows - 1) {
                            cell.setBackgroundColor(new Color(170, 170, 170));
                        }

                        table.addCell(cell);
                    }
                }

            }

        }

        //setting table width
        Chunk dataChk = new Chunk("9999", DATA_FONT);
        Chunk headerChk = new Chunk(longestText, HEADER_FONT);

        float dataChkLength = dataChk.getWidthPoint() + 2 * CELLPADDING;
        float headerChkLength = headerChk.getWidthPoint() + 2 * CELLPADDING;

        float tableWidth = headerChkLength + dataChkLength * columnCount;
        float actualTableWidth = document.getPageSize().getWidth() - 2 * MARGIN;

        float columnWidth = dataChkLength;

        if (tableWidth < actualTableWidth) {
            columnWidth = (actualTableWidth - headerChkLength) / (columnCount - 1);
        }

        float[] widths = new float[columnCount];
        widths[0] = headerChkLength + 2 * CELLPADDING;

        for (int i = 1; i < columnCount; i++) {
            widths[i] = columnWidth;
        }

        table.setWidths(widths);

        //writing the table      
        document.add(table);
    } catch (DocumentException e) {
        throw new OperationException(e);
    }

}

From source file:org.tellervo.desktop.print.ProSheet.java

License:Open Source License

/**
 * Get PdfPTable containing the ring width data for this series
 * /*from   w w  w .  j  a  v a2s.  c o m*/
 * @return PdfPTable
 * @throws DocumentException 
 */
private void getElementTable() throws DocumentException {

    PdfPTable tbl = new PdfPTable(5);

    PdfPCell headerCell = new PdfPCell();

    tbl.setWidthPercentage(100f);
    float[] widths = { 0.1f, 0.4f, 0.2f, 0.1f, 0.2f };

    tbl.setWidths(widths);

    // Set up header
    headerCell.setPhrase(new Phrase("Element", tableHeaderFont));
    headerCell.setBorderWidthBottom(headerLineWidth);
    headerCell.setBorderWidthTop(headerLineWidth);
    headerCell.setBorderWidthLeft(0);
    headerCell.setBorderWidthRight(0);
    headerCell.setPaddingTop(5);
    headerCell.setPaddingBottom(5);
    tbl.addCell(headerCell);

    headerCell.setPhrase(new Phrase("Comments", tableHeaderFont));
    tbl.addCell(headerCell);

    headerCell.setPhrase(new Phrase("Taxon", tableHeaderFont));
    tbl.addCell(headerCell);

    headerCell.setPhrase(new Phrase("# Rings", tableHeaderFont));
    tbl.addCell(headerCell);

    headerCell.setPhrase(new Phrase("Dates", tableHeaderFont));
    tbl.addCell(headerCell);

    // Loop through rows
    for (org.tellervo.desktop.sample.Element e : this.elements) {
        Sample s = null;

        try {
            s = e.load();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            continue;
        }

        // Find element details for this series 
        SearchParameters param = new SearchParameters(SearchReturnObject.DERIVED_SERIES);
        param.addSearchConstraint(SearchParameterName.SERIESDBID, SearchOperator.EQUALS,
                s.getIdentifier().getValue().toString());

        EntitySearchResource<TridasObject> searchResource = new EntitySearchResource<TridasObject>(param,
                TridasObject.class);
        searchResource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT,
                TellervoRequestFormat.COMPREHENSIVE);
        TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(searchResource);
        searchResource.query();
        dialog.setVisible(true);

        List<TridasObject> oblist = searchResource.getAssociatedResult();

        if (oblist.size() != 1) {
            System.out.println(e.getName() + " has more than one (or no) associated objects so skipping");
            continue;
        }
        TridasObject obj = oblist.get(0);

        List<TridasElement> ellist = obj.getElements();
        if (ellist.size() != 1) {
            System.out.println(e.getName() + " has more than one (or no) associated element so skipping");
            continue;
        }
        TridasElement el = ellist.get(0);

        // make lab code
        LabCode labcode = new LabCode();
        labcode.appendSiteCode(((TridasObjectEx) obj).getLabCode());
        labcode.setElementCode(el.getTitle());

        PdfPCell dataCell = new PdfPCell();
        dataCell.setBorderWidthBottom(0);
        dataCell.setBorderWidthTop(0);
        dataCell.setBorderWidthLeft(0);
        dataCell.setBorderWidthRight(0);
        dataCell.setPaddingTop(5);
        dataCell.setPaddingBottom(5);
        dataCell.setHorizontalAlignment(Element.ALIGN_LEFT);

        // Title Column
        dataCell.setPhrase(new Phrase(LabCodeFormatter.getSamplePrefixFormatter().format(labcode).toString(),
                tableBodyFont));
        tbl.addCell(dataCell);

        // Comments Column
        if (el.getComments() != null)
            dataCell.setPhrase(new Phrase(el.getComments(), tableBodyFont));
        else
            dataCell.setPhrase(new Phrase(" ", tableBodyFont));
        tbl.addCell(dataCell);

        // Taxon Column
        dataCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        dataCell.setPhrase(new Phrase(el.getTaxon().getNormal().toString(), tableBodyFont));
        tbl.addCell(dataCell);

        // Rings Column
        dataCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        dataCell.setPhrase(new Phrase(String.valueOf(s.countRings()), tableBodyFont));
        tbl.addCell(dataCell);

        // Dates column
        String datingLabel;
        String datingType = s.getSeries().getInterpretation().getDating().getType().value().toString();
        datingLabel = s.getSeries().getInterpretation().getFirstYear().getValue().toString();
        if (datingType == "Absolute") {
            datingLabel += s.getSeries().getInterpretation().getFirstYear().getSuffix().toString();
        }
        datingLabel += " - " + String.valueOf(
                s.getSeries().getInterpretation().getFirstYear().getValue().intValue() + s.countRings() - 1);
        if (datingType == "Relative") {
            datingLabel += " (Rel. Date)";
        }

        dataCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        dataCell.setPhrase(new Phrase(datingLabel, tableBodyFont));
        tbl.addCell(dataCell);
    }

    // Add table to document
    document.add(tbl);
}

From source file:org.tellervo.desktop.print.SeriesReport.java

License:Open Source License

private void getTableKey() throws DocumentException, IOException, IOException {
    PdfPTable mainTable = new PdfPTable(12);
    float[] widths = { 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f };
    mainTable.setWidths(widths);
    mainTable.setWidthPercentage(100);/* w w w  .  ja v  a  2  s  .  co  m*/

    PdfPTable userRemarksTable = new PdfPTable(2);
    float[] widths2 = { 0.083f, 0.92f };
    userRemarksTable.setWidths(widths2);
    userRemarksTable.setWidthPercentage(100);

    Boolean userRemarkUsed = false;

    DecadalModel model;
    model = new UnitAwareDecadalModel(s);
    int rows = model.getRowCount();
    List<TridasRemark> masterList = null;

    // Loop through rows
    for (int row = 0; row < rows; row++) {
        // Loop through columns
        for (int col = 0; col < 11; col++) {
            org.tellervo.desktop.Year year = model.getYear(row, col);
            List<TridasRemark> remarksList = null;
            remarksList = s.getRemarksForYear(year);

            // If masterlist is still null initialize it with this remarks list
            if (remarksList.size() > 0 && masterList == null)
                masterList = remarksList;

            for (TridasRemark remark : remarksList) {
                if (!masterList.contains(remark))
                    masterList.add(remark);
            }
        }
    }

    for (TridasRemark remark : masterList) {
        PdfPCell iconCell = new PdfPCell();
        PdfPCell equalsCell = new PdfPCell();
        PdfPCell descriptionCell = new PdfPCell();

        iconCell.setBorder(0);
        equalsCell.setBorder(0);
        descriptionCell.setBorder(0);

        iconCell.setVerticalAlignment(Element.ALIGN_TOP);
        equalsCell.setVerticalAlignment(Element.ALIGN_TOP);
        descriptionCell.setVerticalAlignment(Element.ALIGN_TOP);

        Image icon = null;
        String remarkStr = null;

        // Get actual icon (either tridas or tellervo)
        if (remark.isSetNormalTridas()) {
            remarkStr = remark.getNormalTridas().toString().toLowerCase();
            remarkStr = remarkStr.replace("_", " ");
            icon = getTridasIcon(remark.getNormalTridas());
            if (icon == null)
                icon = Builder.getITextImageMissingIcon();
        } else if (TELLERVO.equals(remark.getNormalStd())) {
            remarkStr = remark.getNormal();
            icon = getCorinaIcon(remark.getNormal());
            if (icon == null)
                icon = Builder.getITextImageMissingIcon();
        } else {
            if (!userRemarkUsed) {
                remarkStr = "User Remark (See Below)";
                icon = Builder.getITextImageIcon("user.png");
                userRemarkUsed = true;
            } else {
                // User remark and we already have a key for this so continue
                continue;
            }
        }

        iconCell.addElement(icon);
        equalsCell.addElement(new Phrase("=", tableBodyFont));
        descriptionCell.addElement(new Phrase(WordUtils.capitalize(remarkStr), tableBodyFont));

        mainTable.addCell(iconCell);
        mainTable.addCell(equalsCell);
        mainTable.addCell(descriptionCell);
    }

    // Pad out empty cells
    PdfPCell blankCell = new PdfPCell();
    blankCell.addElement(new Phrase(""));
    blankCell.setBorder(0);
    for (int i = 0; i < 12; i++) {
        mainTable.addCell(blankCell);
    }

    document.add(mainTable);

    if (userRemarkUsed) {
        PdfPCell yearCell = new PdfPCell();
        yearCell.setBorder(0);
        yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        yearCell.addElement(new Phrase("Year", tableHeaderFont));
        userRemarksTable.addCell(yearCell);

        PdfPCell remarkCell = new PdfPCell();
        remarkCell.setBorder(0);
        remarkCell.addElement(new Phrase("User ring remarks", tableHeaderFont));
        userRemarksTable.addCell(remarkCell);

        for (int row = 0; row < rows; row++) {
            // Loop through columns
            for (int col = 0; col < 11; col++) {
                org.tellervo.desktop.Year year = model.getYear(row, col);
                List<TridasRemark> remarksList = null;
                remarksList = s.getRemarksForYear(year);

                for (TridasRemark remark : remarksList) {
                    if (remark.isSetNormalTridas() || remark.isSetNormalStd())
                        continue;

                    yearCell = new PdfPCell();
                    yearCell.setBorder(0);
                    yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                    yearCell.addElement(new Phrase(year.toString(), tableHeaderFont));
                    userRemarksTable.addCell(yearCell);

                    remarkCell = new PdfPCell();
                    remarkCell.setBorder(0);
                    remarkCell.addElement(new Phrase(remark.getValue(), tableBodyFont));
                    userRemarksTable.addCell(remarkCell);
                }
            }
        }

        document.add(userRemarksTable);
    }
}

From source file:org.tellervo.desktop.print.SeriesReport.java

License:Open Source License

/**
 * Get PdfPTable containing the ring width data for this series
 * /*from  w  w w .j  a  va  2 s .  c o m*/
 * @return PdfPTable
 * @throws DocumentException 
 * @throws IOException 
 * @throws MalformedURLException 
 */
private void getDataTable(Boolean wj) throws DocumentException, MalformedURLException, IOException {
    // THE actual table
    PdfPTable mainTable = new PdfPTable(11);
    // Cell for column headers
    PdfPCell colHeadCell = new PdfPCell();
    // Model for data
    DecadalModel model;
    // Flag to show if there are *any* ring remarks
    Boolean hasRemarks = false;

    float[] columnWidths = new float[] { 20f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f };
    mainTable.setWidths(columnWidths);
    mainTable.setWidthPercentage(100f);

    if (wj == true) {
        if (s.hasWeiserjahre() == true) {
            model = new WJTableModel(s);
            document.add(new Chunk("Weiserjahre:", subSubSectionFont));
        } else {
            return;
        }
    } else {
        model = new UnitAwareDecadalModel(s);
        document.add(new Chunk("Ring widths:", subSubSectionFont));
    }

    int rows = model.getRowCount();

    // Do column headers
    if (wj == true) {
        colHeadCell.setPhrase(new Phrase("inc/dec", tableHeaderFont));
    } else if (this.s.getTridasUnits() == null) {
        // Unitless
        colHeadCell.setPhrase(new Phrase(" ", tableHeaderFont));
    } else {
        // Normal tridas units
        try {
            /*if(this.s.getTridasUnits().getNormalTridas().equals(NormalTridasUnit.MICROMETRES))
            {
               colHeadCell.setPhrase(new Phrase("microns", tableHeaderFont));
            }*/

            // Use the current default display units

            colHeadCell.setPhrase(new Phrase(displayUnits.value(), tableHeaderFont));

            /*if(displayUnits.equals(NormalTridasUnit.MICROMETRES))
            {
               colHeadCell.setPhrase(new Phrase("microns", tableHeaderFont));
            }
            else if(displayUnits.equals(NormalTridasUnit.HUNDREDTH_MM))
            {
               colHeadCell.setPhrase(new Phrase("1/100th mm", tableHeaderFont));
            }
            */

        } catch (Exception e) {
            colHeadCell.setPhrase(new Phrase(" ", tableHeaderFont));
        }
    }
    colHeadCell.setBorderWidthBottom(headerLineWidth);
    colHeadCell.setBorderWidthTop(headerLineWidth);
    colHeadCell.setBorderWidthLeft(headerLineWidth);
    colHeadCell.setBorderWidthRight(headerLineWidth);
    mainTable.addCell(colHeadCell);
    for (int i = 0; i < 10; i++) {
        colHeadCell.setPhrase(new Phrase(Integer.toString(i), tableHeaderFont));
        colHeadCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        colHeadCell.setBorderWidthBottom(headerLineWidth);
        colHeadCell.setBorderWidthTop(headerLineWidth);
        colHeadCell.setBorderWidthLeft(lineWidth);
        colHeadCell.setBorderWidthRight(lineWidth);

        if (i == 0)
            colHeadCell.setBorderWidthLeft(headerLineWidth);
        if (i == 9)
            colHeadCell.setBorderWidthRight(headerLineWidth);
        mainTable.addCell(colHeadCell);
    }

    // Loop through rows
    for (int row = 0; row < rows; row++) {
        // Loop through columns
        for (int col = 0; col < 11; col++) {
            // Mini table to hold remark icons
            PdfPTable remarksMiniTable = new PdfPTable(3);
            float[] widths = { 0.3f, 0.3f, 0.6f };
            remarksMiniTable.setWidths(widths);
            remarksMiniTable.setWidthPercentage(100);

            // Get ring value or year number for first column
            Phrase cellValuePhrase = null;
            Object value = model.getValueAt(row, col);
            if (value == null) {
                cellValuePhrase = new Phrase("");
            } else {
                /*if(displayUnits.equals(NormalTridasUnit.HUNDREDTH_MM))
                {
                   try{
                   Integer val = (Integer) value;
                   val =val/10;
                   cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col));
                   } catch (Exception e){
                      cellValuePhrase = new Phrase(value.toString(), getTableFont(col));
                        
                   }
                }
                else if(displayUnits.equals(NormalTridasUnit.FIFTIETH_MM))
                {
                   try{
                   Integer val = (Integer) value;
                   val =val/20;
                   cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col));
                   } catch (Exception e){
                      cellValuePhrase = new Phrase(value.toString(), getTableFont(col));
                        
                   }               
                }
                else if(displayUnits.equals(NormalTridasUnit.TWENTIETH_MM))
                {
                   try{
                   Integer val = (Integer) value;
                   val =val/50;
                   cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col));
                   } catch (Exception e){
                      cellValuePhrase = new Phrase(value.toString(), getTableFont(col));
                        
                   }               
                }
                else if(displayUnits.equals(NormalTridasUnit.TENTH_MM))
                {
                   try{
                   Integer val = (Integer) value;
                   val =val/100;
                   cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col));
                   } catch (Exception e){
                      cellValuePhrase = new Phrase(value.toString(), getTableFont(col));
                        
                   }               
                }
                else if(displayUnits.equals(NormalTridasUnit.MICROMETRES))
                {*/
                cellValuePhrase = new Phrase(value.toString(), getTableFont(col));
                //}
            }

            // Get any remarks and compile them into a mini table
            org.tellervo.desktop.Year year = model.getYear(row, col);
            List<TridasRemark> remarksList = null;
            remarksList = s.getRemarksForYear(year);

            // If there are remarks, cycle through them adding cells to the mini table
            if (col != 0 && remarksList.size() > 0) {
                hasRemarks = true;
                // Get icons for remarks
                int cellnum = 1;
                int remarknum = 0;
                for (TridasRemark remark : remarksList) {
                    // Keep track of which remark we are on.
                    remarknum++;
                    // String for holding remark name for debugging
                    String remstr = "?";
                    // The actual remark icon
                    Image icon = null;
                    // A table cell for the remark
                    PdfPCell remarkCell = new PdfPCell();

                    // Set default attributes for remark and value cells
                    remarkCell.setBorderWidthBottom(0);
                    remarkCell.setBorderWidthTop(0);
                    remarkCell.setBorderWidthLeft(0);
                    remarkCell.setBorderWidthRight(0);
                    remarkCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                    remarkCell.setPadding(0);
                    remarkCell.setUseBorderPadding(true);

                    // A table cell for the ring width value
                    PdfPCell valueCell = new PdfPCell();
                    valueCell = remarkCell;

                    // Get actual icon (either tridas or tellervo)
                    if (remark.isSetNormalTridas()) {
                        remstr = remark.getNormalTridas().toString();
                        icon = getTridasIcon(remark.getNormalTridas());
                        if (icon == null)
                            icon = Builder.getITextImageMissingIcon();
                    } else if (TELLERVO.equals(remark.getNormalStd())) {
                        remstr = remark.getNormal();
                        icon = getCorinaIcon(remark.getNormal());
                        if (icon == null)
                            icon = Builder.getITextImageMissingIcon();
                    } else {
                        if (remark.isSetValue()) {
                            remstr = remark.getValue();
                        } else if (remark.isSetNormal()) {
                            remstr = remark.getNormal();
                        } else {
                            remstr = "Unknown";
                        }
                        icon = Builder.getITextImageIcon("user.png");

                    }

                    // Print debug info for this remark
                    String errStr = "Getting icon for " + remstr + " for year " + year.toString()
                            + "(cell value = " + cellnum + ")";
                    System.out.print(errStr);

                    // Shrink the icon a bit
                    icon.scalePercent(20);

                    // Add icon to minitable
                    remarkCell.addElement(icon);
                    remarksMiniTable.addCell(remarkCell);
                    cellnum++;

                    if (cellnum == 1 && remarksList.size() < cellnum) {
                        // First cell and no remark so print blank
                        valueCell.setPhrase(new Phrase(""));
                        remarksMiniTable.addCell(valueCell);
                        cellnum++;
                    }
                    if (cellnum == 2 && remarksList.size() < cellnum) {
                        // Second cell and no remark so print blank
                        valueCell.setPhrase(new Phrase(""));
                        remarksMiniTable.addCell(valueCell);
                        cellnum++;
                    }
                    if (cellnum == 3) {
                        // In third cell so print value
                        valueCell.setPhrase(cellValuePhrase);
                        remarksMiniTable.addCell(valueCell);
                        cellnum++;
                    } else if (cellnum % 3 == 0) {
                        // In third column so print blank
                        valueCell.setPhrase(new Phrase(""));
                        remarksMiniTable.addCell(valueCell);
                        cellnum++;
                    }

                    if (remarknum == remarksList.size()) {
                        valueCell.setPhrase(new Phrase(""));
                        remarksMiniTable.addCell(valueCell);
                        remarksMiniTable.addCell(valueCell);
                    }

                    remarkCell = null;
                    valueCell = null;
                }
            } else {
                // No remarks so make mini table have blank, blank, value

                // Create blank and value cells
                PdfPCell blankCell = new PdfPCell();
                PdfPCell valueCell = new PdfPCell();

                // Set up style
                blankCell.setBorderWidthBottom(0);
                blankCell.setBorderWidthTop(0);
                blankCell.setBorderWidthLeft(0);
                blankCell.setBorderWidthRight(0);
                blankCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                blankCell.setPadding(0);
                blankCell.setUseBorderPadding(true);
                valueCell = blankCell;

                // Add cells to mini table
                remarksMiniTable.addCell(blankCell);
                remarksMiniTable.addCell(blankCell);
                valueCell.setPhrase(cellValuePhrase);
                remarksMiniTable.addCell(valueCell);
            }

            // Set border styles depending on where we are in the table

            // Defaults
            PdfPCell mainTableCell = new PdfPCell();
            mainTableCell.setBorderWidthBottom(lineWidth);
            mainTableCell.setBorderWidthTop(lineWidth);
            mainTableCell.setBorderWidthLeft(lineWidth);
            mainTableCell.setBorderWidthRight(lineWidth);
            mainTableCell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            // Row headers
            if (col == 0) {
                mainTableCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                mainTableCell.setBorderWidthLeft(headerLineWidth);
                mainTableCell.setBorderWidthRight(headerLineWidth);
            }

            // First data column
            if (col == 1) {
                mainTableCell.setBorderWidthLeft(headerLineWidth);
            }

            // Last data column
            if (col == 10) {
                mainTableCell.setBorderWidthRight(headerLineWidth);
            }

            // Last row
            if (row == model.getRowCount() - 1) {
                mainTableCell.setBorderWidthBottom(headerLineWidth);
            }

            // Write mini table to cell       
            mainTableCell.addElement(remarksMiniTable);

            //mainTableCell.addElement(userRemarksMiniTable);

            // Write cell to main table
            mainTable.addCell(mainTableCell);

        }
    }

    // Add table to document
    document.add(mainTable);

    if (!wj && hasRemarks)
        getTableKey();
}

From source file:org.unitime.timetable.webutil.PdfWebTable.java

License:Open Source License

/**
 * Prints pdf table. By default does not split table across
 * page boundaries /*from   w  w  w.  j  ava 2 s.c  o  m*/
 * @param ordCol
 * @param keepTogether true does not split table across pages
 * @return
 */
public PdfPTable printPdfTable(int ordCol, boolean keepTogether) {
    PdfPTable table = new PdfPTable(getNrColumns());
    table.setWidthPercentage(100);
    table.getDefaultCell().setPadding(3);
    table.getDefaultCell().setBorderWidth(0);
    table.setSplitRows(false);
    table.setKeepTogether(keepTogether);

    boolean asc = (ordCol == 0 || iAsc == null || iAsc.length <= Math.abs(ordCol) - 1 ? true
            : iAsc[Math.abs(ordCol) - 1]);
    if (ordCol < 0)
        asc = !asc;

    widths = new float[iColumns];
    for (int i = 0; i < iColumns; i++)
        widths[i] = 0f;

    String lastLine[] = new String[Math.max(iColumns, (iHeaders == null ? 0 : iHeaders.length))];

    if (iHeaders != null) {
        for (int i = 0; i < iColumns; i++) {
            if (isFiltered(i))
                continue;
            PdfPCell c = createCell();
            c.setBorderWidthBottom(1);
            float width = addText(c, iHeaders[i] == null ? "" : iHeaders[i], true);
            widths[i] = Math.max(widths[i], width);
            String align = (iAlign != null ? iAlign[i] : "left");
            if ("left".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_LEFT);
            if ("right".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_RIGHT);
            if ("center".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c);
        }
        table.setHeaderRows(1);
    }
    if (ordCol != 0) {
        Collections.sort(iLines, new WebTableComparator(Math.abs(ordCol) - 1, asc));
    }
    for (int el = 0; el < iLines.size(); el++) {
        WebTableLine wtline = (WebTableLine) iLines.elementAt(el);
        String[] line = wtline.getLine();
        boolean blank = iBlankWhenSame;
        for (int i = 0; i < iColumns; i++) {
            if (isFiltered(i))
                continue;
            if (blank && line[i] != null && !line[i].equals(lastLine[i]))
                blank = false;
            PdfPCell c = createCell();
            float width = addText(c, blank || line[i] == null ? "" : line[i], false);
            widths[i] = Math.max(widths[i], width);
            String align = (iAlign != null ? iAlign[i] : "left");
            if ("left".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_LEFT);
            if ("right".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_RIGHT);
            if ("center".equals(align))
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
            applyPdfStyle(c, wtline, (el + 1 < iLines.size() ? (WebTableLine) iLines.elementAt(el + 1) : null),
                    ordCol);
            table.addCell(c);
            lastLine[i] = line[i];
        }
    }

    try {
        if (getNrFilteredColumns() < 0) {
            table.setWidths(widths);
        } else {
            float[] x = new float[getNrColumns()];
            int idx = 0;
            for (int i = 0; i < iColumns; i++) {
                if (isFiltered(i))
                    continue;
                x[idx++] = widths[i];
            }
            table.setWidths(x);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return table;
}

From source file:pruebareportes.rptTardC.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**/* w w  w .  j  a  v a 2  s  .c  om*/
     * 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 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);

    // 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.TableHeaderAlternateBackground.java

public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4.rotate());
    try {//w w  w .j  av  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();
}