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

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

Introduction

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

Prototype

public void setHorizontalAlignment(int horizontalAlignment) 

Source Link

Document

Sets the horizontal alignment of the table relative to the page.

Usage

From source file:org.kuali.ole.module.purap.pdf.PurchaseOrderQuotePdf.java

License:Educational Community License

/**
 * Create a PDF using the given input parameters.
 *
 * @param po                        The PurchaseOrderDocument to be used to create the pdf.
 * @param poqv                      The PurchaseOrderVendorQuote to be used to generate the pdf.
 * @param campusName                The campus name to be used to generate the pdf.
 * @param contractManagerCampusCode The contract manager campus code to be used to generate the pdf.
 * @param logoImage                 The logo image file name to be used to generate the pdf.
 * @param document                  The pdf document whose margins have already been set.
 * @param writer                    The PdfWriter to write the pdf document into.
 * @param environment               The current environment used (e.g. DEV if it is a development environment).
 * @throws DocumentException//from   w ww. j  a va 2  s . c o  m
 */
private void createPOQuotePdf(PurchaseOrderDocument po, PurchaseOrderVendorQuote poqv, String campusName,
        String contractManagerCampusCode, String logoImage, Document document, PdfWriter writer,
        String environment) throws DocumentException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("createQuotePdf() started for po number " + po.getPurapDocumentIdentifier());
    }

    // These have to be set because they are used by the onOpenDocument() and onStartPage() methods.
    this.campusName = campusName;
    this.po = po;
    this.logoImage = logoImage;
    this.environment = environment;

    NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
    // Date format pattern: MM-dd-yyyy
    SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE, Locale.getDefault());

    CampusParameter campusParameter = getCampusParameter(contractManagerCampusCode);
    String purchasingAddressFull = getPurchasingAddressFull(campusParameter);

    // Turn on the page events that handle the header and page numbers.
    PurchaseOrderQuotePdf events = new PurchaseOrderQuotePdf().getPageEvents();
    writer.setPageEvent(this); // Passing in "this" lets it know about the po, campusName, etc.

    document.open();

    PdfPCell cell;
    Paragraph p = new Paragraph();

    // ***** Info table (address, vendor, other info) *****
    LOG.debug("createQuotePdf() info table started.");
    float[] infoWidths = { 0.45f, 0.55f };
    PdfPTable infoTable = new PdfPTable(infoWidths);
    infoTable.setWidthPercentage(100);
    infoTable.setHorizontalAlignment(Element.ALIGN_CENTER);
    infoTable.setSplitLate(false);

    p = new Paragraph();
    ContractManager contractManager = po.getContractManager();
    p.add(new Chunk("\n Return this form to:\n", ver_8_bold));
    p.add(new Chunk(purchasingAddressFull + "\n", cour_10_normal));
    p.add(new Chunk("\n", cour_10_normal));
    p.add(new Chunk(" Fax #: ", ver_6_normal));
    p.add(new Chunk(contractManager.getContractManagerFaxNumber() + "\n", cour_10_normal));
    p.add(new Chunk(" Contract Manager: ", ver_6_normal));
    p.add(new Chunk(contractManager.getContractManagerName() + " "
            + contractManager.getContractManagerPhoneNumber() + "\n", cour_10_normal));
    p.add(new Chunk("\n", cour_10_normal));
    p.add(new Chunk(" To:\n", ver_6_normal));
    StringBuffer vendorInfo = new StringBuffer();
    if (StringUtils.isNotBlank(poqv.getVendorAttentionName())) {
        vendorInfo.append("     ATTN: " + poqv.getVendorAttentionName().trim() + "\n");
    }
    vendorInfo.append("     " + poqv.getVendorName() + "\n");
    if (StringUtils.isNotBlank(poqv.getVendorLine1Address())) {
        vendorInfo.append("     " + poqv.getVendorLine1Address() + "\n");
    }
    if (StringUtils.isNotBlank(poqv.getVendorLine2Address())) {
        vendorInfo.append("     " + poqv.getVendorLine2Address() + "\n");
    }
    if (StringUtils.isNotBlank(poqv.getVendorCityName())) {
        vendorInfo.append("     " + poqv.getVendorCityName());
    }
    if ((StringUtils.isNotBlank(poqv.getVendorStateCode())) && (!poqv.getVendorStateCode().equals("--"))) {
        vendorInfo.append(", " + poqv.getVendorStateCode());
    }
    if (StringUtils.isNotBlank(poqv.getVendorAddressInternationalProvinceName())) {
        vendorInfo.append(", " + poqv.getVendorAddressInternationalProvinceName());
    }
    if (StringUtils.isNotBlank(poqv.getVendorPostalCode())) {
        vendorInfo.append(" " + poqv.getVendorPostalCode() + "\n");
    } else {
        vendorInfo.append("\n");
    }

    if (!OLEConstants.COUNTRY_CODE_UNITED_STATES.equalsIgnoreCase(poqv.getVendorCountryCode())
            && poqv.getVendorCountryCode() != null) {
        vendorInfo.append("     " + poqv.getVendorCountry().getName() + "\n\n");
    } else {
        vendorInfo.append("     \n\n");
    }

    p.add(new Chunk(vendorInfo.toString(), cour_10_normal));
    cell = new PdfPCell(p);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    infoTable.addCell(cell);

    p = new Paragraph();
    p.add(new Chunk("\n     R.Q. Number: ", ver_8_bold));
    p.add(new Chunk(po.getPurapDocumentIdentifier() + "\n", cour_10_normal));
    java.sql.Date requestDate = getDateTimeService().getCurrentSqlDate();
    if (poqv.getPurchaseOrderQuoteTransmitTimestamp() != null) {
        try {
            requestDate = getDateTimeService().convertToSqlDate(poqv.getPurchaseOrderQuoteTransmitTimestamp());
        } catch (ParseException e) {
            throw new RuntimeException(
                    "ParseException thrown when trying to convert from Timestamp to SqlDate.", e);
        }
    }
    p.add(new Chunk("     R.Q. Date: ", ver_8_bold));
    p.add(new Chunk(sdf.format(requestDate) + "\n", cour_10_normal));
    p.add(new Chunk("     RESPONSE MUST BE RECEIVED BY: ", ver_8_bold));
    if (po.getPurchaseOrderQuoteDueDate() != null) {
        p.add(new Chunk(sdf.format(po.getPurchaseOrderQuoteDueDate()) + "\n\n", cour_10_normal));
    } else {
        p.add(new Chunk("N/A\n\n", cour_10_normal));
    }

    // retrieve the quote stipulations
    StringBuffer quoteStipulations = getPoQuoteLanguage();

    p.add(new Chunk(quoteStipulations.toString(), ver_6_normal));
    p.add(new Chunk("\n ALL QUOTES MUST BE TOTALED", ver_12_normal));
    cell = new PdfPCell(p);
    infoTable.addCell(cell);

    document.add(infoTable);

    // ***** Notes and Stipulations table *****
    // The notes and stipulations table is type Table instead of PdfPTable
    // because Table has the method setCellsFitPage and I can't find an equivalent
    // in PdfPTable. Long notes or stipulations would break to the next page, leaving
    // a large white space on the previous page.
    PdfPTable notesStipulationsTable = new PdfPTable(1);
    notesStipulationsTable.setWidthPercentage(100);
    notesStipulationsTable.setSplitLate(false);

    p = new Paragraph();
    p.add(new Chunk("  Vendor Stipulations and Information\n\n", ver_6_normal));
    if ((po.getPurchaseOrderBeginDate() != null) && (po.getPurchaseOrderEndDate() != null)) {
        p.add(new Chunk("     Order in effect from " + sdf.format(po.getPurchaseOrderBeginDate()) + " to "
                + sdf.format(po.getPurchaseOrderEndDate()) + ".\n", cour_10_normal));
    }
    Collection<PurchaseOrderVendorStipulation> vendorStipulationsList = po.getPurchaseOrderVendorStipulations();
    if (vendorStipulationsList.size() > 0) {
        StringBuffer vendorStipulations = new StringBuffer();
        for (PurchaseOrderVendorStipulation povs : vendorStipulationsList) {
            vendorStipulations.append("     " + povs.getVendorStipulationDescription() + "\n");
        }
        p.add(new Chunk("     " + vendorStipulations.toString(), cour_10_normal));
    }

    PdfPCell tableCell = new PdfPCell(p);
    tableCell.setHorizontalAlignment(Element.ALIGN_LEFT);
    tableCell.setVerticalAlignment(Element.ALIGN_TOP);
    notesStipulationsTable.addCell(tableCell);
    document.add(notesStipulationsTable);

    // ***** Items table *****
    LOG.debug("createQuotePdf() items table started.");
    float[] itemsWidths = { 0.07f, 0.1f, 0.07f, 0.50f, 0.13f, 0.13f };
    PdfPTable itemsTable = new PdfPTable(6);
    // itemsTable.setCellsFitPage(false); With this set to true a large cell will
    // skip to the next page. The default Table behaviour seems to be what we want:
    // start the large cell on the same page and continue it to the next.
    itemsTable.setWidthPercentage(100);
    itemsTable.setWidths(itemsWidths);
    itemsTable.setSplitLate(false);

    tableCell = createCell("Item\nNo.", false, false, false, false, Element.ALIGN_CENTER, ver_6_normal);
    itemsTable.addCell(tableCell);
    tableCell = createCell("Quantity", false, false, false, false, Element.ALIGN_CENTER, ver_6_normal);
    itemsTable.addCell(tableCell);
    tableCell = createCell("UOM", false, false, false, false, Element.ALIGN_CENTER, ver_6_normal);
    itemsTable.addCell(tableCell);
    tableCell = createCell("Description", false, false, false, false, Element.ALIGN_CENTER, ver_6_normal);
    itemsTable.addCell(tableCell);
    tableCell = createCell("Unit Cost\n(Required)", false, false, false, false, Element.ALIGN_CENTER,
            ver_6_normal);
    itemsTable.addCell(tableCell);
    tableCell = createCell("Extended Cost\n(Required)", false, false, false, false, Element.ALIGN_CENTER,
            ver_6_normal);
    itemsTable.addCell(tableCell);

    if (StringUtils.isNotBlank(po.getPurchaseOrderQuoteVendorNoteText())) {
        // Vendor notes line.
        itemsTable.addCell(" ");
        itemsTable.addCell(" ");
        itemsTable.addCell(" ");
        tableCell = createCell(po.getPurchaseOrderQuoteVendorNoteText(), false, false, false, false,
                Element.ALIGN_LEFT, cour_10_normal);
        itemsTable.addCell(tableCell);
        itemsTable.addCell(" ");
        itemsTable.addCell(" ");
    }

    for (PurchaseOrderItem poi : (List<PurchaseOrderItem>) po.getItems()) {
        if ((poi.getItemType() != null) && (StringUtils.isNotBlank(poi.getItemDescription())) && (poi
                .getItemType().isLineItemIndicator()
                || poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_SHIP_AND_HAND_CODE)
                || poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_FREIGHT_CODE)
                || poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ORDER_DISCOUNT_CODE)
                || poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE))) {
            // "ITEM"s display the line number; other types don't.
            String description = "";
            description = (StringUtils.isNotBlank(poi.getItemCatalogNumber()))
                    ? poi.getItemCatalogNumber().trim() + " - "
                    : "";
            description = description
                    + ((StringUtils.isNotBlank(poi.getItemDescription())) ? poi.getItemDescription().trim()
                            : "");

            // If this is a full order discount item or trade in item, we add the
            // itemType description and a dash to the purchase order item description.
            if (StringUtils.isNotBlank(poi.getItemDescription())) {
                if (poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ORDER_DISCOUNT_CODE)
                        || poi.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_TRADE_IN_CODE)) {
                    description = poi.getItemType().getItemTypeDescription() + " - " + description;
                }
            }

            // We can do the normal table now because description is not too long.
            String itemLineNumber = new String();
            if (poi.getItemType().isLineItemIndicator()) {
                itemLineNumber = poi.getItemLineNumber().toString();
            } else {
                itemLineNumber = "";
            }
            tableCell = createCell(itemLineNumber, false, false, false, false, Element.ALIGN_CENTER,
                    cour_10_normal);
            itemsTable.addCell(tableCell);
            String quantity = (poi.getItemQuantity() != null) ? poi.getItemQuantity().toString() : " ";
            tableCell = createCell(quantity, false, false, false, false, Element.ALIGN_CENTER, cour_10_normal);
            itemsTable.addCell(tableCell);
            tableCell = createCell(poi.getItemUnitOfMeasureCode(), false, false, false, false,
                    Element.ALIGN_CENTER, cour_10_normal);
            itemsTable.addCell(tableCell);

            tableCell = createCell(description, false, false, false, false, Element.ALIGN_LEFT, cour_10_normal);
            itemsTable.addCell(tableCell);
            itemsTable.addCell(" ");
            itemsTable.addCell(" ");

        }
    }

    // Blank line before totals
    createBlankRowInItemsTable(itemsTable);

    // Totals line.
    itemsTable.addCell(" ");
    itemsTable.addCell(" ");
    itemsTable.addCell(" ");
    tableCell = createCell("Total: ", false, false, false, false, Element.ALIGN_RIGHT, ver_10_normal);
    itemsTable.addCell(tableCell);
    itemsTable.addCell(" ");
    itemsTable.addCell(" ");
    // Blank line after totals
    createBlankRowInItemsTable(itemsTable);

    document.add(itemsTable);

    LOG.debug("createQuotePdf() vendorFillsIn table started.");
    float[] vendorFillsInWidths = { 0.50f, 0.50f };
    PdfPTable vendorFillsInTable = new PdfPTable(vendorFillsInWidths);
    vendorFillsInTable.setWidthPercentage(100);
    vendorFillsInTable.setHorizontalAlignment(Element.ALIGN_CENTER);
    vendorFillsInTable.setSplitLate(false);
    vendorFillsInTable.getDefaultCell().setBorderWidth(0);
    vendorFillsInTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    vendorFillsInTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);

    // New row
    String important = new String(
            "\nIMPORTANT: The information and signature below MUST BE COMPLETED or your offer may be rejected.\n");
    cell = createCell(important, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    cell.setColspan(2);
    vendorFillsInTable.addCell(cell);
    // New row
    String cashDiscount = new String(
            "Terms of Payment:  Cash discount_________%_________Days-Net________Days\n");
    cell = createCell(cashDiscount, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    cell.setColspan(2);
    vendorFillsInTable.addCell(cell);
    // New row
    String fob = new String(" FOB: __ Destination (Title)\n");
    cell = createCell(fob, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    String freightVendor = new String(" __ Freight Vendor Paid (Allowed)\n");
    cell = createCell(freightVendor, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    // New row
    String shipping = new String("          __ Shipping Point (Title)\n");
    cell = createCell(shipping, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    String freightPrepaid = new String(" __ Freight Prepaid & Added Amount $_________\n");
    cell = createCell(freightPrepaid, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    // New row
    String commonCarrier = new String(
            "      If material will ship common carrier, please provide the following:\n");
    cell = createCell(commonCarrier, true, false, false, false, Element.ALIGN_LEFT, ver_8_bold);
    cell.setColspan(2);
    vendorFillsInTable.addCell(cell);
    // New row
    String origin = new String(
            "      Point of origin and zip code: ______________________ Weight: _________ Class: _________\n");
    cell = createCell(origin, true, false, false, false, Element.ALIGN_LEFT, ver_8_bold);
    cell.setColspan(2);
    vendorFillsInTable.addCell(cell);
    // New row
    p = new Paragraph();
    p.add(new Chunk(" Unless otherwise stated, all material to be shipped to ", ver_8_normal));
    String purchasingAddressPartial;
    if (po.getAddressToVendorIndicator()) // use receiving address
        purchasingAddressPartial = po.getReceivingCityName() + ", " + po.getReceivingStateCode() + " "
                + po.getReceivingPostalCode();
    else // use final delivery address
        purchasingAddressPartial = po.getDeliveryCityName() + ", " + po.getDeliveryStateCode() + " "
                + po.getDeliveryPostalCode();
    p.add(new Chunk(purchasingAddressPartial + "\n", cour_10_normal));
    cell = new PdfPCell(p);
    cell.setColspan(2);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    vendorFillsInTable.addCell(cell);
    // New row
    String offerEffective = new String(" Offer effective until (Date):_____________\n");
    cell = createCell(offerEffective, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    String deliverBy = new String(" Delivery can be made by (Date):_____________\n");
    cell = createCell(deliverBy, true, false, false, false, Element.ALIGN_LEFT, ver_8_normal);
    vendorFillsInTable.addCell(cell);
    // New row
    String sign = new String(" SIGN HERE:____________________________\n");
    cell = createCell(sign, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);
    String date = new String(" DATE:____________________________\n");
    cell = createCell(date, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);
    // New row
    String name = new String(" PRINT NAME:____________________________\n");
    cell = createCell(name, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);
    String phone = new String(" PHONE:____________________________\n");
    cell = createCell(phone, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);
    // New row
    String company = new String(" COMPANY:____________________________\n");
    cell = createCell(company, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);
    String fax = new String(" FAX:____________________________\n");
    cell = createCell(fax, true, false, false, false, Element.ALIGN_RIGHT, ver_10_bold);
    vendorFillsInTable.addCell(cell);

    document.add(vendorFillsInTable);
    document.close();
    LOG.debug("createQuotePdf()pdf document closed.");
}

From source file:org.kuali.ole.module.purap.pdf.PurchaseOrderQuoteRequestsPdf.java

License:Educational Community License

/**
 * Creates the pdf using given input parameters.
 *
 * @param po       The PurchaseOrderDocument to be used to create the pdf.
 * @param document The pdf document whose margins have already been set.
 * @param writer   The PdfWriter to write the pdf document into.
 * @param instName The purchasing institution name
 * @throws DocumentException//from www.ja v  a 2 s  .  c om
 */
private void createPOQuoteRequestsListPdf(PurchaseOrderDocument po, Document document, PdfWriter writer,
        String instName) throws DocumentException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("createPOQuoteRequestsListPdf() started for po number " + po.getPurapDocumentIdentifier());
    }

    // These have to be set because they are used by the onOpenDocument() method.
    this.po = po;

    // Turn on the page events that handle the header and page numbers.
    PurchaseOrderPdf events = new PurchaseOrderPdf().getPageEvents();
    writer.setPageEvent(this); // Passing in "this" lets it know about the po, campusName, etc.

    document.open();

    PdfPCell cell;
    Paragraph p = new Paragraph();

    float[] headerWidths = { 0.25f, 0.25f, 0.25f, 0.25f };
    headerTable = new PdfPTable(headerWidths);
    headerTable.setWidthPercentage(100);
    headerTable.setHorizontalAlignment(Element.ALIGN_CENTER);

    headerTable.getDefaultCell().setBorderWidth(0);
    headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);

    // New row
    cell = new PdfPCell(new Paragraph(instName + "\nRequest for Quotation Vendor List\n\n", titleFont));
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setColspan(4);
    headerTable.addCell(cell);

    // New row
    cell = new PdfPCell(new Paragraph("PO Number: " + po.getPurapDocumentIdentifier(), cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBorderWidth(0);
    headerTable.addCell(cell);

    cell = new PdfPCell(new Paragraph("Req. Number: " + po.getRequisitionIdentifier(), cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBorderWidth(0);
    headerTable.addCell(cell);

    // Date format pattern: MM-dd-yyyy
    SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE, Locale.getDefault());
    Date today = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate();
    cell = new PdfPCell(new Paragraph("Printed: " + sdf.format(today), cellTextFont));
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    headerTable.addCell(cell);

    if (po.getPurchaseOrderQuoteDueDate() != null) {
        Date dueDate = po.getPurchaseOrderQuoteDueDate();
        cell = new PdfPCell(new Paragraph("Due: " + sdf.format(dueDate) + "\n\n", cellTextFont));
    } else {
        cell = new PdfPCell(new Paragraph("Due: N/A\n\n", cellTextFont));
    }
    cell.setBorderWidth(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    headerTable.addCell(cell);

    document.add(headerTable);

    // ***** List table *****
    LOG.debug("createPOQuoteRequestsListPdf() list table started.");
    float[] listWidths = { 0.20f, 0.20f, 0.20f, 0.20f, 0.20f };
    PdfPTable listTable = new PdfPTable(listWidths);
    listTable.setWidthPercentage(100);
    listTable.setHorizontalAlignment(Element.ALIGN_CENTER);

    cell = new PdfPCell(new Paragraph("Vendor Name", cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    listTable.addCell(cell);
    cell = new PdfPCell(new Paragraph("City", cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    listTable.addCell(cell);
    cell = new PdfPCell(new Paragraph("Attention", cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    listTable.addCell(cell);
    cell = new PdfPCell(new Paragraph("Fax #", cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    listTable.addCell(cell);
    cell = new PdfPCell(new Paragraph("Received", cellTextFont));
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setBorderWidth(0);
    listTable.addCell(cell);

    // The line under the headings.
    cell = new PdfPCell(new Paragraph(" ", cellTitleFont));
    cell.setFixedHeight(1);
    cell.setColspan(5);
    listTable.addCell(cell);

    for (PurchaseOrderVendorQuote poqv : po.getPurchaseOrderVendorQuotes()) {
        cell = new PdfPCell(new Paragraph(poqv.getVendorName(), cellTextFont));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorderWidth(0);
        listTable.addCell(cell);
        if (poqv.getVendorStateCode() != null) {
            cell = new PdfPCell(
                    new Paragraph(poqv.getVendorCityName() + ", " + poqv.getVendorStateCode(), cellTextFont));
        } else if (poqv.getVendorCountryCode() != null) {
            cell = new PdfPCell(
                    new Paragraph(poqv.getVendorCityName() + ", " + poqv.getVendorCountryCode(), cellTextFont));
        } else {
            cell = new PdfPCell(new Paragraph(poqv.getVendorCityName(), cellTextFont));
        }
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorderWidth(0);
        listTable.addCell(cell);
        cell = new PdfPCell(new Paragraph(poqv.getVendorAttentionName(), cellTextFont));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorderWidth(0);
        listTable.addCell(cell);
        cell = new PdfPCell(new Paragraph(poqv.getVendorFaxNumber(), cellTextFont));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorderWidth(0);
        listTable.addCell(cell);
        cell = new PdfPCell(new Paragraph("__________", cellTextFont));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorderWidth(0);
        listTable.addCell(cell);
    }

    document.add(listTable);

    document.close();
    LOG.debug("createPOQuoteRequestsListPdf()pdf document closed.");
}

From source file:org.mapfish.print.PDFUtils.java

License:Open Source License

/**
 * When we have to do some custom drawing in a block that is layed out by
 * iText, we first give an empty table with the good dimensions to iText,
 * then iText will call a callback with the actual position. When that
 * happens, we use the given drawer to do the actual drawing.
 *//*w  w w  . j  a va 2  s . c o  m*/
public static PdfPTable createPlaceholderTable(double width, double height, double spacingAfter,
        ChunkDrawer drawer, HorizontalAlign align, PDFCustomBlocks customBlocks) {
    PdfPTable placeHolderTable = new PdfPTable(1);
    placeHolderTable.setLockedWidth(true);
    placeHolderTable.setTotalWidth((float) width);
    final PdfPCell placeHolderCell = new PdfPCell();
    placeHolderCell.setMinimumHeight((float) height);
    placeHolderCell.setPadding(0f);
    placeHolderCell.setBorder(PdfPCell.NO_BORDER);
    placeHolderTable.addCell(placeHolderCell);
    customBlocks.addChunkDrawer(drawer);
    placeHolderTable.setTableEvent(drawer);
    placeHolderTable.setComplete(true);

    final PdfPCell surroundingCell = new PdfPCell(placeHolderTable);
    surroundingCell.setPadding(0f);
    surroundingCell.setBorder(PdfPCell.NO_BORDER);
    if (align != null) {
        placeHolderTable.setHorizontalAlignment(align.getCode());
        surroundingCell.setHorizontalAlignment(align.getCode());
    }

    PdfPTable surroundingTable = new PdfPTable(1);
    surroundingTable.setSpacingAfter((float) spacingAfter);
    surroundingTable.addCell(surroundingCell);
    surroundingTable.setComplete(true);

    return surroundingTable;
}

From source file:org.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public void printSpecsHistory(List<EyeformSpecsHistory> specsHistory) throws DocumentException {
    ProviderDao providerDao = (ProviderDao) SpringUtils.getBean("providerDao");

    /*/*from  w w  w .  j a v a  2  s.  c  o  m*/
         if( getNewPage() )
    getDocument().newPage();
           else
    setNewPage(true);
    */

    Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);

    Paragraph p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_LEFT);
    Phrase phrase = new Phrase(LEADING, "\n", getFont());
    p.add(phrase);
    phrase = new Phrase(LEADING, "Specs History", obsfont);
    p.add(phrase);
    getDocument().add(p);

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.setSpacingBefore(10f);
    table.setSpacingAfter(10f);
    table.setTotalWidth(new float[] { 10f, 60f });
    table.setTotalWidth(5f);
    table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);

    for (EyeformSpecsHistory specs : specsHistory) {
        PdfPCell cell1 = new PdfPCell(new Phrase(getFormatter().format(specs.getDate()), getFont()));
        cell1.setBorder(PdfPCell.NO_BORDER);
        cell1.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase(specs.toString2(), getFont()));
        cell2.setBorder(PdfPCell.NO_BORDER);
        cell2.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        table.addCell(cell2);
    }

    getDocument().add(table);
}

From source file:org.oscarehr.web.reports.ocan.NeedRatingOverTimeReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);//from  w  ww  .  jav  a  2s .  co  m
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Needs Over Time (Consumer and Staff)", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "The purpose of this report is to show change over time in a specific Need Rating for an individual Consumer. It adds up the number of needs across all Domains grouped by Need Rating (e.g. Unmet Needs, Met Needs, No Needs, Unknown) for all selected OCANs that were conducted with the Consumer and displays the results in an individual need rating line graph. Each line graph that is displayed compares the Consumer and the Staff's perspective. The staff may share this report with their Consumer as well.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(
            makeCell(createFieldNameAndValuePhrase("Consumer Name:", getConsumerName()), Element.ALIGN_LEFT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", getStaffName()), Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    //loop here...groups of 3
    int loopNo = 1;
    List<OcanNeedRatingOverTimeSummaryOfNeedsBean> summaryBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
    summaryBeanList.addAll(this.summaryOfNeedsBeanList);

    while (true) {
        if (summaryBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeSummaryOfNeedsBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
        for (int x = 0; x < 3; x++) {
            if (summaryBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(summaryBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            summaryOfNeedsTable = new PdfPTable(3);
            summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 2) {
            summaryOfNeedsTable = new PdfPTable(6);
            summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 3) {
            summaryOfNeedsTable = new PdfPTable(9);
            summaryOfNeedsTable.setWidthPercentage(100f);
            summaryOfNeedsTable
                    .setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);
        summaryOfNeedsTable.setHeaderRows(3);

        addSummaryOfNeedsHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unmet Needs", "unmet", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Met Needs", "met", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "No Needs", "no", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unknown Needs", "unknown", currentBeanList);

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (summaryBeanList.size() == 0) {
            break;
        }
        loopNo++;
    }

    //BREAKDOWN OF SUMMARY OF NEEDS

    //loop here...groups of 3
    loopNo = 1;
    List<OcanNeedRatingOverTimeNeedBreakdownBean> breakdownBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
    breakdownBeanList.addAll(this.needBreakdownListByOCAN);
    OcanNeedRatingOverTimeNeedBreakdownBean lastBreakDownBean = null;
    while (true) {
        if (breakdownBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeNeedBreakdownBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
        for (int x = 0; x < 3; x++) {
            if (breakdownBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(breakdownBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(3);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(4);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 2) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(6);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(7);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable
                        .setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 3) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(9);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(
                        new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(10);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f,
                        0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);

        addSummaryOfNeedsDomainHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        for (int x = 0; x < domains.size(); x++) {
            addSummaryOfNeedsDomainRow(summaryOfNeedsTable, x, getDomains(), currentBeanList,
                    lastBreakDownBean);
        }

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (breakdownBeanList.size() == 0) {
            break;
        }
        if (currentBeanList.size() == 3) {
            lastBreakDownBean = currentBeanList.get(2);
        }
        loopNo++;
    }

    JFreeChart chart = generateNeedsOverTimeChart();
    BufferedImage image = chart.createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, 350);
    Image image2 = Image.getInstance(image, null);
    d.add(image2);

    d.close();
}

From source file:org.posterita.businesslogic.administration.CustomerManager.java

License:Open Source License

public static String fidelityCard(Properties ctx, ArrayList<CustomerBean> customerList)
        throws OperationException {
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    boolean shouldPrintCard = false;

    for (CustomerBean b : customerList) {
        if (b.getIsActive()) {
            shouldPrintCard = true;/*from w  w w.  j a  va  2 s.co  m*/
            break;
        }
    }

    if (!shouldPrintCard) {
        throw new NoCustomerFoundException("Cannot print fidelity card. Cause no active customers were found.");
    }

    Document document = new Document(PageSize.A4, 3, 3, 2, 4);//l,r,t,b

    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();

        PdfPTable main = new PdfPTable(2);
        main.setWidthPercentage(71.0f);
        main.getDefaultCell().setBorderColor(Color.gray);

        PdfPCell cell = new PdfPCell();
        cell.setMinimumHeight(150.0f);

        Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.BOLD);
        //Font spaceFont = FontFactory.getFont(FontFactory.HELVETICA,6,Font.BOLD);
        //Font spaceFont2 = FontFactory.getFont(FontFactory.HELVETICA,15,Font.BOLD);

        //ResourceBundle rb = ResourceBundle.getBundle("MessageResources");

        for (CustomerBean bean : customerList) {
            if (bean.getIsActive()) {
                String name = bean.getPartnerName();
                String name1 = "";
                String add2 = "";
                String add1 = "";
                String city = "";

                if (bean.getAddress1() != null)
                    add1 = bean.getAddress1();

                if (bean.getAddress2() != null)
                    add2 = bean.getAddress2();

                if (bean.getCity() != null)
                    city = bean.getCity();

                String Address = "   " + add1;
                String Add2 = " " + add2;
                String Add3 = "   " + city;

                String BackPriv1Path = PathInfo.PROJECT_HOME + "/images/BackPriv1.jpg";
                String backPriv2Path = PathInfo.PROJECT_HOME + "/images/backPriv2.jpg";
                String frontImgPath = PathInfo.PROJECT_HOME + "/images/pc.png";

                float WIDTH = 205;
                float HEIGHT = 135;

                Image Back1 = Image.getInstance(BackPriv1Path);
                Back1.scaleAbsolute(WIDTH - 40, HEIGHT / 3);
                Image Back2 = Image.getInstance(backPriv2Path);
                Back2.scaleAbsolute(WIDTH, HEIGHT / 3);
                Image frontImg = Image.getInstance(frontImgPath);
                frontImg.scaleAbsolute(WIDTH, HEIGHT);

                if (bean.getSurname() != null && bean.getSurname().trim().length() > 0)
                    name1 = "   " + name + " " + name1 + bean.getSurname();

                byte[] barcode = BarcodeManager.getBarcodeAsByte(bean.getBpartnerId().toString());
                Image barcodeImg = Image.getInstance(barcode);
                barcodeImg.setRotation(1.57f);
                barcodeImg.scaleAbsolute(HEIGHT - 55f, WIDTH / 5);

                //document.add(barcodeImg);
                PdfPTable card = new PdfPTable(2);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c = null;
                card.setWidthPercentage(50.0f);

                PdfPTable t = new PdfPTable(1);
                PdfPTable nametable = new PdfPTable(1);

                c = new PdfPCell(Back1);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add2, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                //nametable.getDefaultCell();
                nametable.getDefaultCell().setBorderWidth(0.0f);
                nametable.setHorizontalAlignment(Element.ALIGN_CENTER);
                card.addCell(nametable);

                c = new PdfPCell(barcodeImg);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                c.setHorizontalAlignment(Element.ALIGN_RIGHT);
                c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                c.setPadding(5.0f);
                card.addCell(c);

                c = new PdfPCell(Back2);
                c.setBorderWidth(0.0f);
                c.setColspan(2);
                card.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                PdfPTable card1 = new PdfPTable(1);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c1 = null;
                card.setWidthPercentage(50.0f);

                c1 = new PdfPCell(frontImg);
                c1.setBorderWidth(0.0f);
                card1.addCell(c1);

                main.addCell(card);
                main.addCell(card1);
            }

        }
        document.add(main);

    }
    // TODO handle the following exception neatly
    catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

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

From source file:org.sakaiproject.tool.assessment.pdf.itext.HTMLWorker.java

License:Mozilla Public License

public void startElement(String tag, HashMap h) {
    if (!tagsSupported.containsKey(tag))
        return;/*from   www . j a va  2 s  .c o  m*/
    try {
        style.applyStyle(tag, h);
        String follow = (String) FactoryProperties.followTags.get(tag);
        if (follow != null) {
            HashMap prop = new HashMap();
            prop.put(follow, null);
            cprops.addToChain(follow, prop);
            return;
        }
        FactoryProperties.insertStyle(h);
        if (tag.equals("a")) {
            cprops.addToChain(tag, h);
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            stack.push(currentParagraph);
            currentParagraph = new Paragraph();
            return;
        }
        if (tag.equals("br")) {
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            currentParagraph.add(factoryProperties.createChunk("\n", cprops));
            return;
        }
        if (tag.equals("hr")) {

            PdfPTable hr = new PdfPTable(1);
            hr.setHorizontalAlignment(Element.ALIGN_CENTER);
            hr.setWidthPercentage(100f);
            hr.setSpacingAfter(0f);
            hr.setSpacingBefore(0f);
            PdfPCell cell = new PdfPCell();
            cell.setUseVariableBorders(true);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(PdfPCell.BOTTOM);
            cell.setBorderWidth(1f);
            cell.setPadding(0);
            cell.addElement(factoryProperties.createChunk("\n", cprops));

            hr.addCell(cell);
            // paragraphs can't have tables? really? without it hr's may be rendered a bit early..
            //if (currentParagraph != null)
            //    currentParagraph.add(hr);
            //else
            document.add(hr);
            return;

        }
        if (tag.equals("font") || tag.equals("span")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("img")) {
            String src = (String) h.get("src");
            if (src == null)
                return;
            cprops.addToChain(tag, h);
            Image img = null;
            if (interfaceProps != null) {
                HashMap images = (HashMap) interfaceProps.get("img_static");
                if (images != null) {
                    Image tim = (Image) images.get(src);
                    if (tim != null)
                        img = Image.getInstance(tim);
                } else {
                    if (!src.startsWith("http")) { // relative src references only
                        String baseurl = (String) interfaceProps.get("img_baseurl");
                        if (baseurl != null) {
                            src = baseurl + src;
                            img = Image.getInstance(src);
                        }
                    }
                }
            }
            if (img == null) {
                if (!src.startsWith("http")) {
                    String path = cprops.getProperty("image_path");
                    if (path == null)
                        path = "";
                    src = new File(path, src).getPath();
                    img = Image.getInstance(src);
                } else {
                    byte[] buffer;
                    String srcResource = src.substring(src.indexOf("/content", 0)).replaceAll("/content", "");
                    buffer = getImageStream(URLDecoder.decode(srcResource));
                    img = Image.getInstance(buffer);
                }
            }

            String align = (String) h.get("align");
            String width = (String) h.get("width");
            String height = (String) h.get("height");
            String border = (String) h.get("border");
            String hspace = (String) h.get("hspace");
            String vspace = (String) h.get("vspace");
            String before = cprops.getProperty("before");
            String after = cprops.getProperty("after");
            float wp = 0.0f;
            float lp = 0.0f;
            if (maxWidth > 0 && ((width != null && Integer.parseInt(width) > maxWidth)
                    || (width == null && (int) img.getWidth() > maxWidth))) {
                wp = lengthParse(String.valueOf(maxWidth), (int) img.getWidth());
                lp = wp;
            } else {
                wp = lengthParse(width, (int) img.getWidth());
                lp = lengthParse(height, (int) img.getHeight());
            }
            if (wp > 0 && lp > 0)
                img.scalePercent(wp, lp);
            else if (wp > 0)
                img.scalePercent(wp);
            else if (lp > 0)
                img.scalePercent(lp);
            img.setWidthPercentage(0);
            // border
            if (border != null && !"".equals(border)) {
                try {
                    img.setBorderWidth(Integer.parseInt(border));
                    img.setBorder(Image.BOX);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // horizonatal space
            if (hspace != null && !"".equals(hspace)) {
                try {
                    img.setSpacingAfter(Float.parseFloat(hspace));
                    img.setSpacingBefore(Float.parseFloat(hspace));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // horizontal alignment
            if (align != null && (align.equalsIgnoreCase("left") || align.equalsIgnoreCase("right"))) {
                endElement("p");
                int ralign = Image.LEFT;
                if (align.equalsIgnoreCase("right"))
                    ralign = Image.RIGHT;
                img.setAlignment(ralign | Image.TEXTWRAP);
                Img i = null;
                boolean skip = false;
                if (interfaceProps != null) {
                    i = (Img) interfaceProps.get("img_interface");
                    if (i != null)
                        skip = i.process(img, h, cprops, document);
                }
                if (!skip)
                    document.add(img);
                cprops.removeChain(tag);
            }
            // vertical alignment (or none)
            else {
                img.setAlignment(Image.TEXTWRAP);

                float bottom = 0.0f;
                float top = img.getTop();
                float prevHeight = 0.0f;
                float prevRise = 0.0f;

                if (currentParagraph != null) {
                    ArrayList chunks = currentParagraph.getChunks();
                    Chunk sibling = null;

                    for (int k = chunks.size() - 1; k >= 0; k--) {
                        if (chunks.get(k) != null)
                            sibling = (Chunk) chunks.get(k);
                    }

                    if (sibling != null) {
                        if (sibling.hasAttributes())
                            prevRise = sibling.getTextRise();
                        prevHeight = 0.0f;
                        if (sibling.getFont() != null) {
                            prevHeight = sibling.getFont().getCalculatedSize();
                        }
                    }
                }

                if ("absMiddle".equalsIgnoreCase(align)) {
                    if (prevHeight > 0)
                        bottom += (img.getScaledHeight() / 2.0f) - (prevHeight / 2.0f);
                    else if (img.getScaledHeight() > 0)
                        bottom += img.getScaledHeight() / 2.0f;
                } else if ("middle".equalsIgnoreCase(align)) {
                    if (img.getScaledHeight() > 0)
                        bottom += (img.getScaledHeight() / 2.0f);
                } else if ("bottom".equalsIgnoreCase(align) || "baseline".equalsIgnoreCase(align)
                        || "absbottom".equalsIgnoreCase(align)) {
                    //baseline and absbottom should have some slight tweeking from bottom, but not sure what??
                } else if ("top".equalsIgnoreCase(align)) {
                    bottom += img.getScaledHeight() - prevHeight;
                } else if ("texttop".equalsIgnoreCase(align)) {
                    bottom += img.getScaledHeight() - (prevHeight - prevRise);
                }

                cprops.removeChain(tag);
                if (currentParagraph == null) {
                    currentParagraph = FactoryProperties.createParagraph(cprops);
                    bottom = 0f;
                } else if (currentParagraph.isEmpty()) {
                    bottom = 0f;
                }

                currentParagraph.setLeading(2f + bottom, 1.00f);
                currentParagraph.add(new Chunk(img, 0, 0 - bottom));
            }
            return;
        }
        if (tag.equals("blockquote")) {
            cprops.addToChain(tag, h);
            inBLOCK = true;
            if (currentParagraph != null)
                endElement("p");
            currentParagraph = FactoryProperties.createParagraph(cprops);
            currentParagraph.add(factoryProperties.createChunk("\n", cprops));
            return;
        }
        endElement("p");
        if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5")
                || tag.equals("h6")) {
            if (!h.containsKey("size")) {
                int v = 8 - Integer.parseInt(tag.substring(1));
                h.put("size", Integer.toString(v));
            }
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("ul")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(false, 10);
            list.setListSymbol("\u2022");
            stack.push(list);
            return;
        }
        if (tag.equals("ol")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(true, 10);
            stack.push(list);
            return;
        }
        if (tag.equals("li")) {
            if (pendingLI)
                endElement("li");
            skipText = false;
            pendingLI = true;
            cprops.addToChain(tag, h);
            stack.push(FactoryProperties.createListItem(cprops));
            return;
        }
        if (tag.equals("div") || tag.equals("body")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("pre")) {
            if (!h.containsKey("face")) {
                h.put("face", "Courier");
            }
            cprops.addToChain(tag, h);
            isPRE = true;
            return;
        }
        if (tag.equals("p")) {
            cprops.addToChain(tag, h);
            currentParagraph = FactoryProperties.createParagraph(cprops);
            if (inBLOCK) {
                currentParagraph.setIndentationLeft(currentParagraph.getIndentationLeft() + 40.0F);
            }
            return;
        }
        if (tag.equals("tr")) {
            if (pendingTR)
                endElement("tr");
            skipText = true;
            pendingTR = true;
            cprops.addToChain("tr", h);
            return;
        }
        if (tag.equals("td") || tag.equals("th")) {
            if (pendingTD)
                endElement(tag);
            skipText = false;
            pendingTD = true;
            cprops.addToChain("td", h);
            stack.push(new IncCell(tag, cprops));
            return;
        }
        if (tag.equals("table")) {
            cprops.addToChain("table", h);
            IncTable table = new IncTable(h);
            stack.push(table);
            tableState.push(new boolean[] { pendingTR, pendingTD });
            pendingTR = pendingTD = false;
            skipText = true;
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
        //throw new ExceptionConverter(e);
    }
}

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

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

    try {//from  w w w . j av a 2s .  c om
        //            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();
    }
}

From source file:sg.edu.nus.util.ReportWriter.java

public static String writeDataArrayToPdf(String userName, ArrayList<String[]> data, String title) {

    String rawFileName = userName + "_report.pdf";

    String fileName = ServerPeer.getReportFolderPath() + "/" + rawFileName;

    int ncol = data.get(0).length;

    Document document = new Document();
    try {/*  w  ww.j  a v a  2s  . co  m*/

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        /* Create the font. The font name must exactly match the font name on the client system. */
        Paragraph para = null;

        //         RtfFont embossedFont = new RtfFont("Times New Roman", 12,
        //               RtfFont.STYLE_EMBOSSED);

        // We add one empty line
        para = new Paragraph();
        addEmptyLine(para, 1);
        // Lets write a big header
        para.add(new Paragraph(title, catFont));

        addEmptyLine(para, 1);
        // Will create: Report generated by: _name, _date
        para.add(new Paragraph("Report generated by: " + userName + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));
        addEmptyLine(para, 3);

        document.add(para);

        //add header and table content

        Font font8 = FontFactory.getFont(FontFactory.HELVETICA, 12);
        PdfPTable table = null;

        float columnPercentage = (float) (100.0 / ncol);
        float[] columnDefinitionSize = new float[ncol];
        for (int c = 0; c < ncol; c++) {
            columnDefinitionSize[c] = columnPercentage;
        }

        table = new PdfPTable(columnDefinitionSize);
        // table.getDefaultCell().setBorder(0);
        table.setHorizontalAlignment(0);
        float width = document.getPageSize().getWidth();
        table.setTotalWidth(width - 72);
        table.setLockedWidth(true);

        //write header
        String[] arr = data.get(0);
        for (int j = 0; j < ncol; j++) {
            table.addCell(new Phrase(arr[j], subFont));
        }

        //write data
        for (int i = 1; i < data.size(); i++) {
            arr = data.get(i);
            for (int j = 0; j < ncol; j++) {
                table.addCell(new Phrase(arr[j], font8));
            }
        }

        document.add(table);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();

    return ServerPeer.getWebDownloadAddress() + "/" + rawFileName;
}

From source file:sg.edu.nus.util.ReportWriter.java

public static String writeDataArrayToRtf(String userName, ArrayList<String[]> data, String title) {

    String rawFileName = userName + "_report.rtf";

    String fileName = ServerPeer.getReportFolderPath() + "/" + rawFileName;

    int ncol = data.get(0).length;

    Document document = new Document();
    try {//from  w  w w. j  a v  a2s.c  o  m

        RtfWriter2.getInstance(document, new FileOutputStream(fileName));
        document.open();

        Paragraph para = null;

        // We add one empty line
        para = new Paragraph();
        addEmptyLine(para, 1);
        // Lets write a big header
        para.add(new Paragraph(title, catFont));

        addEmptyLine(para, 1);
        // Will create: Report generated by: _name, _date
        para.add(new Paragraph("Report generated by: " + userName + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                smallBold));
        addEmptyLine(para, 3);

        document.add(para);
        //add header and table content

        Font font8 = FontFactory.getFont(FontFactory.HELVETICA, 12);
        PdfPTable table = null;

        float columnPercentage = (float) (100.0 / ncol);
        float[] columnDefinitionSize = new float[ncol];
        for (int c = 0; c < ncol; c++) {
            columnDefinitionSize[c] = columnPercentage;
        }

        table = new PdfPTable(columnDefinitionSize);
        // table.getDefaultCell().setBorder(0);
        table.setHorizontalAlignment(0);
        float width = document.getPageSize().getWidth();
        table.setTotalWidth(width - 72);
        table.setLockedWidth(true);

        //write header
        String[] arr = data.get(0);
        for (int j = 0; j < ncol; j++) {
            table.addCell(new Phrase(arr[j], subFont));
        }

        //write data
        for (int i = 1; i < data.size(); i++) {
            arr = data.get(i);
            for (int j = 0; j < ncol; j++) {
                table.addCell(new Phrase(arr[j], font8));
            }
        }

        document.add(table);

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();

    return ServerPeer.getWebDownloadAddress() + "/" + rawFileName;
}