Subversion Repositories SmartDukaan

Rev

Rev 8488 | Rev 8721 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.hotspot.dashbaord.server;

import in.shop2020.config.ConfigException;
import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsServiceException;
import in.shop2020.logistics.PickUpType;
import in.shop2020.logistics.PickupStore;
import in.shop2020.logistics.Provider;
import in.shop2020.logistics.ProviderDetails;
import in.shop2020.model.v1.catalog.CatalogService;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.inventory.BillingType;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.order.AmazonOrder;
import in.shop2020.model.v1.order.Attribute;
import in.shop2020.model.v1.order.EbayOrder;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.SnapdealOrder;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.config.ConfigClient;
import in.shop2020.thrift.clients.InventoryClient;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.thrift.TException;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.icu.text.RuleBasedNumberFormat;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.FontFactoryImp;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.Barcode128;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;

@SuppressWarnings("serial")
public class InvoiceServlet extends HttpServlet {

        private static Logger logger = LoggerFactory.getLogger(InvoiceServlet.class);

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                long orderId = Long.parseLong(request.getParameter("id"));
                long warehouseId = Long.parseLong(request.getParameter("warehouse"));
                boolean withBill = false;
                boolean printAll = false;
                try {
                        withBill = Boolean.parseBoolean(request.getParameter("withBill"));
                } catch(Exception e){
                        logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
                }
                try {
                        printAll = Boolean.parseBoolean(request.getParameter("printAll"));
                } catch(Exception e){
                        logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
                }

                logger.info("Printing invoice for order id: " + orderId);
                
                ByteArrayOutputStream baos = null;
        
                InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
                baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);

                response.setContentType("application/pdf");
                response.setHeader("Content-disposition", "inline; filename=invoice-"+orderId+".pdf" );

                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        baos.writeTo(sos);
                        sos.flush();
                } catch (IOException e) {
                        logger.error("Encountered error while sending invoice response: ", e);
                }
        }
}

class InvoiceGenerationService {

        private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);

        private TransactionClient tsc = null;
        private InventoryClient csc = null;
        private LogisticsClient lsc = null;
        private CatalogClient ctsc = null;

        private static Locale indianLocale = new Locale("en", "IN");
        private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");

        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
        private static final Font helvetica6 = FontFactory.getFont(FontFactory.HELVETICA, 6);
        //End:-Added By Manish Sharma for FedEx Integration  - Shipment Creation on 21-Aug-2013
        private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
        private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
        private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
        private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
        private static final Font helvetica22 = FontFactory.getFont(FontFactory.HELVETICA, 22);

        private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
        private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);

        private static final String delhiPincodePrefix = "11";

        public InvoiceGenerationService() {
                try {
                        tsc = new TransactionClient();
                        csc = new InventoryClient();
                        lsc = new LogisticsClient();
                        ctsc = new CatalogClient();
                } catch (Exception e) {
                        logger.error("Error while instantiating thrift clients.", e);
                }
        }

        public ByteArrayOutputStream generateInvoice(long orderId, boolean withBill, boolean printAll, long warehouseId) {
                ByteArrayOutputStream baosPDF = null;
                in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                in.shop2020.model.v1.inventory.InventoryService.Client iclient = csc.getClient();
                in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();


                try {
                        baosPDF = new ByteArrayOutputStream();

                        Document document = new Document();
                        PdfWriter.getInstance(document, baosPDF);
                        document.addAuthor("shop2020");
                        //document.addTitle("Invoice No: " + order.getInvoice_number());
                        document.open();

                        List<Order> orders = new ArrayList<Order>();
                        if(printAll){
                                try {
                                        List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                                        statuses.add(OrderStatus.ACCEPTED);
                                        orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
                                } catch (Exception e) {
                                        logger.error("Error while getting order information", e);
                                        return baosPDF; 
                                }
                        }else{
                                orders.add(tclient.getOrder(orderId));  
                        }
                        boolean isFirst = true;

                        for(Order order: orders){
                                Warehouse warehouse = null;
                                Provider provider = null;
                                String destCode = null;
                                Warehouse shippingLocation = null;
                                int barcodeFontSize = 0;
                                try {
                                        warehouse = iclient.getWarehouse(order.getWarehouse_id());
                                        long providerId = order.getLogistics_provider_id();
                                        provider = logisticsClient.getProvider(providerId);
                                        if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
                                                destCode = provider.getPickup().toString();
                                        else
                                                destCode = logisticsClient.getDestinationCode(providerId, order.getCustomer_pincode());

                                        barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
                                        shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId());
                                } catch (InventoryServiceException ise) {
                                        logger.error("Error while getting the warehouse information.", ise);
                                        return baosPDF;
                                } catch (LogisticsServiceException lse) {
                                        logger.error("Error while getting the provider information.", lse);
                                        return baosPDF;
                                } catch (ConfigException ce) {
                                        logger.error("Error while getting the fontsize for the given provider", ce);
                                        return baosPDF;
                                } catch (TException te) {
                                        logger.error("Error while getting some essential information from the services", te);
                                        return baosPDF;
                                }

                                if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
                                        if(isFirst){
                                                document.add(getFixedTextTable(16, "Spice Online Retail Pvt Ltd"));
                                                isFirst = false;
                                        }
                                        document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
                                        continue;
                                }
                                
                                PdfPTable dispatchAdviceTable = null;
                                
                                if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
                                        dispatchAdviceTable = new PdfPTable(1);
                                } else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
                                        if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
                                                dispatchAdviceTable = new PdfPTable(1);
                                        } else { 
                                                if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
                                                        dispatchAdviceTable = new PdfPTable(1);
                                                } else {
                                                        EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
                                                        dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
                                                }
                                        }
                                } else {
                                        dispatchAdviceTable = getDispatchAdviceTable(order, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation);
                                }
                                dispatchAdviceTable.setSpacingAfter(10.0f);
                                dispatchAdviceTable.setWidthPercentage(90.0f);
                                document.add(dispatchAdviceTable);
                                //TODO fix this logic
                                if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
                                        if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
                                                        || order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
                                                if(withBill){
                                                        PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber());
                                                        taxTable.setSpacingBefore(5.0f);
                                                        taxTable.setWidthPercentage(90.0f);
                                                        document.add(new DottedLineSeparator());
                                                        document.add(taxTable);
                                                }else{
                                                        PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
                                                        extraInfoTable.setSpacingBefore(5.0f);
                                                        extraInfoTable.setWidthPercentage(90.0f);
                                                        document.add(new DottedLineSeparator());
                                                        document.add(extraInfoTable);
                                                }
                                        } else {
                                                document.newPage();
                                        }
                                } else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
                                        if(withBill){
                                                PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber());
                                                taxTable.setSpacingBefore(5.0f);
                                                taxTable.setWidthPercentage(90.0f);
                                                document.add(new DottedLineSeparator());
                                                document.add(taxTable);
                                        }else{
                                                PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
                                                extraInfoTable.setSpacingBefore(5.0f);
                                                extraInfoTable.setWidthPercentage(90.0f);
                                                document.add(new DottedLineSeparator());
                                                document.add(extraInfoTable);
                                        }
                                }
                                if(withBill){
                                        PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber());
                                        taxTable.setSpacingBefore(5.0f);
                                        taxTable.setWidthPercentage(90.0f);
                                        document.add(new DottedLineSeparator());
                                        document.add(taxTable);
                                }else{
                                        PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
                                        extraInfoTable.setSpacingBefore(5.0f);
                                        extraInfoTable.setWidthPercentage(90.0f);
                                        document.add(new DottedLineSeparator());
                                        document.add(extraInfoTable);
                                }
                                document.newPage();
                        }
                        document.close();
                        baosPDF.close();
                        // Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
                        if(withBill && !printAll){
                                String strOrderId = StringUtils.repeat("0", 10-String.valueOf(orderId).length()) + orderId;  
                                String dirPath = "/SaholicInvoices" + File.separator + strOrderId.substring(0, 2) + File.separator + strOrderId.substring(2, 4) + File.separator + strOrderId.substring(4, 6);
                                String filename = dirPath + File.separator + orderId + ".pdf";
                                File dirFile = new File(dirPath);
                                if(!dirFile.exists()){
                                        dirFile.mkdirs();
                                }
                                File f = new File(filename);
                                FileOutputStream fos = new FileOutputStream(f);
                                baosPDF.writeTo(fos);
                        }
                } catch (Exception e) {
                        logger.error("Error while generating Invoice: ", e);
                }
                return baosPDF;
        }

        private PdfPTable getDispatchAdviceTable(Order order, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill, Warehouse shippingLocation){
                Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);

                PdfPTable table = new PdfPTable(1);
                table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                
                PdfPTable titleBarTable = new PdfPTable(new float[]{0.4f, 0.4f, 0.2f});
                titleBarTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                
                PdfPTable logoTable = new PdfPTable(2);
                addLogoTable(logoTable,order); 
                
                PdfPCell titleCell = getTitleCell();
                PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
                PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);

                PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
                dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                dispatchTable.addCell(customerTable);
                dispatchTable.addCell(new Phrase(" "));
                dispatchTable.addCell(providerInfoTable);

                PdfPTable invoiceTable = getTopInvoiceTable(order, shippingLocation.getTinNumber());
                PdfPTable addressTable = new PdfPTable(1);
                addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                
                PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
                                " - " + shippingLocation.getPincode() + "\nContact No.- 0120-2479977" + "\n\n");

                PdfPTable chargesTable = new PdfPTable(1);
                chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                if(order.isLogisticsCod()){
                        chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()), helveticaBold12));
                        chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
                        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                        if(order.getLogistics_provider_id()==7L){
                                in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                                String fedexCodReturnBarcode = "";
                                String fedexCodReturnTrackingId = "";
                                try {
                                        fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
                                        fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
                                } catch (TException e1) {
                                        logger.error("Error while getting the provider information.", e1);
                                }
                                PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
                                formIdCell.setPaddingTop(2.0f);
                                formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                                formIdCell.setBorder(Rectangle.NO_BORDER);
                                chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
                                chargesTable.addCell(formIdCell);
                                
                                generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
                                
                                Image barcodeImage=null;
                                try {
                                        barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
                                } catch (Exception e) {
                                        logger.error("Exception during getting Barcode Image for Fedex : ", e);
                                }
                                
                                PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
                                codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                                codReturnTable.addCell(barcodeImage);
                                codReturnTable.addCell(new Phrase(" "));
                                chargesTable.addCell(codReturnTable);
                                
                        }
                        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                } else {
                        chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
                }
                
                if(order.getLogistics_provider_id()==7L){
                        chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
                                        "limits the liability of FedEx for loss, delay or damage to the consignment." +
                                        " Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
                                        new Font(FontFamily.TIMES_ROMAN, 8f)));
                }

                addressTable.addCell(new Phrase("If undelivered, return to:", helvetica10));
                addressTable.addCell(addressCell);
                
                PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
                addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                addressAndNoteTable.addCell(addressTable);
                addressAndNoteTable.addCell(chargesTable);

                titleBarTable.addCell(logoTable);
                titleBarTable.addCell(titleCell);
                titleBarTable.addCell(" ");
                
                table.addCell(titleBarTable);
                table.addCell(dispatchTable);
                table.addCell(invoiceTable);
                table.addCell(addressAndNoteTable);
                return table;
        }

        private void addLogoTable(PdfPTable logoTable,Order order) {
                logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
                                
                PdfPCell logoCell;
                String logoPath;
                
                if(order.getSource() == OrderSource.STORE.getValue()){
                        logoCell = new PdfPCell(new Phrase(""));
                        
                }else{
                        logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
                        
                        try {
                                logoCell = new PdfPCell(Image.getInstance(logoPath), false);
                        } catch (Exception e) {
                                //Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
                                logger.warn("Couldn't load the Saholic logo: ", e);
                                logoCell = new PdfPCell(new Phrase("Saholic Logo"));
                        }
                
                }
                logoCell.setBorder(Rectangle.NO_BORDER);
                logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                logoTable.addCell(logoCell);
                logoTable.addCell(" ");
                
        }

        private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
                String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
                FontFactoryImp ttfFontFactory = new FontFactoryImp();
                ttfFontFactory.register(fontPath, "barcode");
                Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
                return barCodeFont;
        }

        private PdfPCell getTitleCell() {
                PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
                titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                titleCell.setBorder(Rectangle.NO_BORDER);
                return titleCell;
        }

        private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
                PdfPTable providerInfoTable = new PdfPTable(1);
                providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                if(order.isLogisticsCod()){
                        PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
                        deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                        deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
                        providerInfoTable.addCell(deliveryTypeCell);
                }
                
                
                PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
                providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                providerNameCell.setBorder(Rectangle.NO_BORDER);
                PdfPCell formIdCell= null;
                if(order.getLogistics_provider_id()==7L){
                        if(order.isCod()){
                                formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
                        }
                        else{
                                formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
                        }
                        formIdCell.setPaddingTop(1.0f);
                        formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        formIdCell.setBorder(Rectangle.NO_BORDER);
                }
                
        
                PdfPCell awbNumberCell= null;
                String fedexPackageBarcode = "";
                if(order.getLogistics_provider_id()!=7L){
                        awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
                        awbNumberCell.setPaddingTop(20.0f);
                }
                else{
                        in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                        try {
                                fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
                        } catch (TException e1) {
                                logger.error("Error while getting the provider information.", e1);
                        }
                        awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
                }
                awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                awbNumberCell.setBorder(Rectangle.NO_BORDER);

                providerInfoTable.addCell(providerNameCell);
                if(formIdCell != null){
                        providerInfoTable.addCell(formIdCell);
                }
                //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                if(order.getLogistics_provider_id()==7L){
                        generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
                        
                        Image barcodeImage=null;
                        try {
                                barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
                        } catch (Exception e) {
                                logger.error("Exception during getting Barcode Image for Fedex : ", e);
                        }
                        providerInfoTable.addCell(barcodeImage);
                }
                providerInfoTable.addCell(awbNumberCell);

                Warehouse warehouse = null;
                try{
                InventoryClient isc = new InventoryClient();
                warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
                } catch(Exception e) {
                    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
                    //TODO throw e;
                }
                DeliveryType dt =  DeliveryType.PREPAID;
        if (order.isLogisticsCod()) {
            dt = DeliveryType.COD;
        }
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
        if(order.getLogistics_provider_id()!=7L){
                for (ProviderDetails detail : provider.getDetails()) {
                    if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
                        providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
                    }
                }
        }
        else{
                providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
        }
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                Date awbDate;
                if(order.getBilling_timestamp() == 0){
                        awbDate = new Date();
                }else{
                        awbDate = new Date(order.getBilling_timestamp());
                }
                if(order.getLogistics_provider_id()!=7L){
                        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
                }
                providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
                if(order.getSource() == OrderSource.EBAY.getValue()){
                        EbayOrder ebayOrder = null;
                        try {
                                ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
                        } catch (TException e) {
                                logger.error("Error while getting ebay order", e);
                        }
                        providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
                        providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
                }
                //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                if(order.getLogistics_provider_id()==7L){
                        providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
                }
                //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                return providerInfoTable;
        }

        private PdfPTable getTopInvoiceTable(Order order, String tinNo){
                PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
                invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                invoiceTable.addCell(getInvoiceTableHeader(6));

                invoiceTable.addCell(new Phrase("Order No", helvetica8));
                invoiceTable.addCell(new Phrase("Paymode", helvetica8));
                invoiceTable.addCell(new Phrase("Product Name", helvetica8));
                invoiceTable.addCell(new Phrase("Quantity", helvetica8));
                invoiceTable.addCell(new Phrase("Rate", helvetica8));
                invoiceTable.addCell(new Phrase("Amount", helvetica8));
                populateTopInvoiceTable(order, invoiceTable);


                if(order.getInsurer() > 0) {
                        invoiceTable.addCell(getInsuranceCell(4));
                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                }

                if(order.getSource() == OrderSource.STORE.getValue()) {
                        invoiceTable.addCell(getAdvanceAmountCell(4));
                        invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
                        invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
                }
                
                invoiceTable.addCell(getTotalCell(4));      
                invoiceTable.addCell(getRupeesCell());
                invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));

                PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
                tinCell.setColspan(6);
                tinCell.setPadding(2);
                invoiceTable.addCell(tinCell);

                return invoiceTable;
        }

        private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
                List<LineItem> lineitems = order.getLineitems();
                for (LineItem lineitem : lineitems) {
                        invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
                        if(order.getPickupStoreId() > 0 && order.isCod() == true)
                                invoiceTable.addCell(new Phrase("In-Store", helvetica8));
                        else if (order.isCod())
                                invoiceTable.addCell(new Phrase("COD", helvetica8));
                        else
                                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
                        
                        invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));

                        invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));

                        invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));

                        invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
                }
        }

        private PdfPCell getAddressCell(String address) {
                Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
                PdfPCell addressCell = new PdfPCell();
                addressCell.addElement(addressParagraph);
                addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                addressCell.setBorder(Rectangle.NO_BORDER);
                return addressCell;
        }

        private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider, String ourAddress, String tinNo){
                PdfPTable taxTable = new PdfPTable(1);
                Phrase phrase = null;
                taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                
                PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
                logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                
                
                PdfPTable logoTable = new PdfPTable(2);
                addLogoTable(logoTable,order); 
                
                if (order.getOrderType().equals(OrderType.B2B)) {
                        phrase = new Phrase("TAX INVOICE", helveticaBold12);
                } else {
                        phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
                }
                PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
                retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);

                Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- 0120-2479977" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
                PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
                sorlAddressCell.addElement(sorlAddress);
                sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);

                PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
                PdfPTable orderDetails = getOrderDetails(order, provider);

                PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
                addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                addrAndOrderDetailsTable.addCell(customerAddress);
                addrAndOrderDetailsTable.addCell(new Phrase(" "));
                addrAndOrderDetailsTable.addCell(orderDetails);

                boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
                PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);

                PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Delhi Jurisdiction.\nThis is a Computer generated Invoice.", helvetica8));
                disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                disclaimerCell.setBorder(Rectangle.NO_BORDER);
                
                
                logoTitleAndOurAddressTable.addCell(logoTable);
                logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
                logoTitleAndOurAddressTable.addCell(sorlAddress);
                
                taxTable.addCell(logoTitleAndOurAddressTable);
                taxTable.addCell(addrAndOrderDetailsTable);
                taxTable.addCell(invoiceTable);
                taxTable.addCell(disclaimerCell);

                return taxTable;
        }

        private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
                PdfPTable customerTable = new PdfPTable(1);
                customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                if(forInvoce || order.getPickupStoreId() == 0){
                        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
                        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
                        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
                        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
                        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                        if(order.getLogistics_provider_id()!=7L){
                                if(destCode != null)
                                        customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
                                else
                                        customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
                                }
                        else{
                                in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                                String fedexLocationcode = "";
                                try {
                                        fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
                                } catch (TException e1) {
                                        logger.error("Error while getting the provider information.", e1);
                                }
                                customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
                        }
                        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
                        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
                }else{
                        try {
                                in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
                                PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
                                customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
                                customerTable.addCell(new Phrase(store.getLine1(), font));
                                customerTable.addCell(new Phrase(store.getLine2(), font));
                                customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
                                if(destCode != null)
                                        customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
                                else
                                        customerTable.addCell(new Phrase(store.getPin(), font));
                                customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
                        } catch (TException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }

                }

                if(order.getOrderType().equals(OrderType.B2B)) {
                        String tin = null;
                        in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
                        List<Attribute> attributes;
                        try {
                                attributes = tclient.getAllAttributesForOrderId(order.getId());

                                for(Attribute attribute : attributes) {
                                        if(attribute.getName().equals("tinNumber")) {
                                                tin = attribute.getValue();
                                        }
                                }
                                if (tin != null) {
                                        customerTable.addCell(new Phrase("TIN :" + tin, font));
                                }

                        } catch (Exception e) {
                                logger.error("Error while getting order attributes", e);
                        }
                }
                /*
        if(showPaymentMode){
            customerTable.addCell(new Phrase(" ", font));
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
        }*/
                return customerTable;
        }

        private PdfPTable getOrderDetails(Order order, Provider provider){
                PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
                orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

                orderTable.addCell(new Phrase("Invoice No:", helvetica8));
                orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));

                orderTable.addCell(new Phrase("Date:", helvetica8));
                orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));

                orderTable.addCell(new Phrase("Order ID:", helvetica8));
                orderTable.addCell(new Phrase("" + order.getId(), helvetica8));

                if(order.getSource() == OrderSource.AMAZON.getValue()){
                        AmazonOrder aorder = null;
                        try {
                                aorder = tsc.getClient().getAmazonOrder(order.getId());
                        } catch (TException e) {
                                logger.error("Error while getting amazon order", e);
                        }
                        orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
                        orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
                } else if(order.getSource() == OrderSource.EBAY.getValue()){
                        EbayOrder ebayOrder = null;
                        try {
                                ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
                        } catch (TException e) {
                                logger.error("Error while getting ebay order", e);
                        }
                        orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
                        orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
                        orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
                        orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
                } else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
                        SnapdealOrder snapdealOrder = null;
                        try {
                                snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, 0);
                        } catch (TException e) {
                                logger.error("Error while getting snapdeal order", e);
                        }
                        orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
                        orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
                }

                orderTable.addCell(new Phrase("Order Date:", helvetica8));
                orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));

                orderTable.addCell(new Phrase("Courier:", helvetica8));
                orderTable.addCell(new Phrase(provider.getName(), helvetica8));

                orderTable.addCell(new Phrase("AWB No:", helvetica8));
                orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));

                orderTable.addCell(new Phrase("AWB Date:", helvetica8));
                orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));

                return orderTable;
        }

        private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
                PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
                invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                invoiceTable.addCell(getInvoiceTableHeader(5));

                invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
                invoiceTable.addCell(new Phrase("Description", helveticaBold8));
                invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
                invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
                invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
                LineItem lineItem = order.getLineitems().get(0);
                double orderAmount = order.getTotal_amount();
                double rate = lineItem.getVatRate();
                double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);

                populateBottomInvoiceTable(order, invoiceTable, rate);

                PdfPCell salesTaxCell = getPriceCell(salesTax);

                invoiceTable.addCell(getVATLabelCell(isVAT));
                invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
                invoiceTable.addCell(salesTaxCell);

                if(order.getInsurer() > 0) {
                        invoiceTable.addCell(getInsuranceCell(3));
                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                }

                invoiceTable.addCell(getEmptyCell(5));

                invoiceTable.addCell(getTotalCell(3));
                invoiceTable.addCell(getRupeesCell());
                invoiceTable.addCell(getTotalAmountCell(orderAmount));

                invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
                invoiceTable.addCell(getAmountInWordsCell(orderAmount));

                invoiceTable.addCell(getEOECell(5));

                return invoiceTable;
        }

        private PdfPCell getInvoiceTableHeader(int colspan) {
                PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
                invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
                invoiceTableHeader.setColspan(colspan);
                invoiceTableHeader.setPaddingTop(1);
                return invoiceTableHeader;
        }

        private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
                for (LineItem lineitem : order.getLineitems()) {
                        invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));

                        invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));

                        invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));

                        double itemPrice = lineitem.getUnit_price();
                        double showPrice = (100 * itemPrice)/(100 + rate);
                        invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell

                        double totalPrice = lineitem.getTotal_price();
                        showPrice = (100 * totalPrice)/(100 + rate);
                        invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
                }
        }

        private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
                String itemName = getItemDisplayName(lineitem, appendIMEI);
                if(freebieItemId!=null && freebieItemId!=0){
                        try {
                                CatalogService.Client catalogClient = ctsc.getClient();
                                Item item = catalogClient.getItem(freebieItemId);
                                itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
                        } catch(Exception tex) {
                                logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
                        }
                }
                PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
                productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                return productNameCell;
        }

        private PdfPCell getPriceCell(double price) {
                PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
                totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return totalPriceCell;
        }

        private PdfPCell getVATLabelCell(boolean isVAT) {
                PdfPCell vatCell = null;
                if(isVAT){
                        vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
                } else {
                        vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
                }
                vatCell.setColspan(3);
                vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return vatCell;
        }

        private PdfPCell getAdvanceAmountCell(int colspan) {
                PdfPCell insuranceCell = null;
                insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
                insuranceCell.setColspan(colspan);
                insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return insuranceCell;
        }
        
        private PdfPCell getInsuranceCell(int colspan) {
                PdfPCell insuranceCell = null;
                insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance", helvetica8));
                insuranceCell.setColspan(colspan);
                insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return insuranceCell;
        }

        private PdfPCell getEmptyCell(int colspan) {
                PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
                emptyCell.setColspan(colspan);
                return emptyCell;
        }

        private PdfPCell getTotalCell(int colspan) {
                PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
                totalCell.setColspan(colspan);
                totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return totalCell;
        }

        private PdfPCell getRupeesCell() {
                PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
                rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return rupeesCell;
        }

        private PdfPCell getTotalAmountCell(double orderAmount) {
                PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
                totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return totalAmountCell;
        }

        /**
         * This method uses ICU4J libraries to convert the given amount into words
         * of Indian locale.
         * 
         * @param orderAmount
         *            The amount to convert.
         * @return the string representation of the given amount.
         */
        private PdfPCell getAmountInWordsCell(double orderAmount) {
                RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
                StringBuilder amountInWords = new StringBuilder("Rs. ");
                amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
                amountInWords.append(" and ");
                amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
                amountInWords.append(" paise");

                PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
                amountInWordsCell.setColspan(4);
                return amountInWordsCell;
        }

        /**
         * Returns the item name to be displayed in the invoice table.
         * 
         * @param lineitem
         *            The line item whose name has to be displayed
         * @param appendIMEI
         *            Whether to attach the IMEI No. to the item name
         * @return The name to be displayed for the given line item.
         */
        private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
                StringBuffer itemName = new StringBuffer();
                if(lineitem.getBrand()!= null)
                        itemName.append(lineitem.getBrand() + " ");
                if(lineitem.getModel_name() != null)
                        itemName.append(lineitem.getModel_name() + " ");
                if(lineitem.getModel_number() != null )
                        itemName.append(lineitem.getModel_number() + " ");
                if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
                        itemName.append("("+lineitem.getColor()+")");
                if(appendIMEI && lineitem.isSetSerial_number()){
                        itemName.append("\nIMEI No. " + lineitem.getSerial_number());
                }

                return itemName.toString();
        }

        /**
         * 
         * @param colspan
         * @return a PdfPCell containing the E&amp;OE text and spanning the given
         *         no. of columns
         */
        private PdfPCell getEOECell(int colspan) {
                PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
                eoeCell.setColspan(colspan);
                eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return eoeCell;
        }

        private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
                PdfPTable extraInfoTable = new PdfPTable(1);
                extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
                FontFactoryImp ttfFontFactory = new FontFactoryImp();
                ttfFontFactory.register(fontPath, "barcode");
                Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);

                PdfPCell extraInfoCell;
                if(billingType == BillingType.EXTERNAL){
                        extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
                }else{
                        extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));  
                }

                extraInfoCell.setPaddingTop(20.0f);
                extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                extraInfoCell.setBorder(Rectangle.NO_BORDER);

                extraInfoTable.addCell(extraInfoCell);


                return extraInfoTable;
        }

        private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
                PdfPTable extraInfoTable = new PdfPTable(1);
                extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
                FontFactoryImp ttfFontFactory = new FontFactoryImp();
                ttfFontFactory.register(fontPath, "barcode");
                Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);

                PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));

                extraInfoCell.setPaddingTop(20.0f);
                extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                extraInfoCell.setBorder(Rectangle.NO_BORDER);

                extraInfoTable.addCell(extraInfoCell);

                return extraInfoTable;
        }
        
        private void generateBarcode(String barcodeString, String fileName){
                Code128Bean bean = new Code128Bean();

                final int dpi = 60;

                //Configure the barcode generator
                bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
                                                                 //width exactly one pixel
                bean.setFontSize(bean.getFontSize()+1.0f);
                bean.doQuietZone(false);

                try {
                        File outputFile = new File("/tmp/"+fileName+".png");
                        OutputStream out = new FileOutputStream(outputFile);
                        
                    //Set up the canvas provider for monochrome PNG output 
                    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
                            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);

                    //Generate the barcode
                    bean.generateBarcode(canvas, barcodeString);

                    //Signal end of generation
                    canvas.finish();
                    out.close();
                    
                } 
                catch(Exception e){
                        logger.error("Exception during generating Barcode : ", e);
                }
        }

        public static void main(String[] args) throws IOException {
                InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
                long orderId = 356324;
                ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
                String userHome = System.getProperty("user.home");
                File f = new File(userHome + "/invoice-" + orderId + ".pdf");
                FileOutputStream fos = new FileOutputStream(f);
                baos.writeTo(fos);
                System.out.println("Invoice generated.");
        }
}