Subversion Repositories SmartDukaan

Rev

Rev 29461 | 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.BluedartAttributes;
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.CatalogServiceException;
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.FlipkartOrder;
import in.shop2020.model.v1.order.HsOrder;
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.ProductCondition;
import in.shop2020.model.v1.order.SellerInfo;
import in.shop2020.model.v1.order.ShipmentLogisticsCostDetail;
import in.shop2020.model.v1.order.SnapdealOrder;
import in.shop2020.model.v1.order.TransactionService;
import in.shop2020.model.v1.order.WarehouseAddress;
import in.shop2020.model.v1.user.Address;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.thrift.clients.config.ConfigClient;

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.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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.Font.FontFamily;
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.pdf.BaseFont;
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);
        private static long july2017Timestamp;
        static {
                Calendar july2017 = Calendar.getInstance();
                july2017.set(2017, Calendar.JULY, 1);
                july2017Timestamp = july2017.getTimeInMillis();
        }
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                long orderId = Long.parseLong(request.getParameter("id"));
                String logisticsTxnId  = request.getParameter("logisticsTxnId");
                Order o = null;
                try {
                        in.shop2020.model.v1.order.TransactionService.Client tclient = new TransactionClient().getClient();
                        o = tclient.getOrder(orderId);
                } catch (Exception e) {
                        logger.warn("Seems problem with transaction service", e);
                        return;
                }
                
                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);
                }

                if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
                        logger.info("Printing invoice for master order id: " + logisticsTxnId);
                }else{
                        logger.info("Printing invoice for order id: " + orderId);
                }
                
                ByteArrayOutputStream baos = null;
                //For invoices older than july 17
                if(o.getBilling_timestamp() < july2017Timestamp) {
                        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
                        baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);
                } else { //For GST
                        GSTInvoiceGenerationService invoiceGenerationService = new GSTInvoiceGenerationService();
                        baos = invoiceGenerationService.generateInvoice(orderId, printAll, warehouseId);
                        
                }
                response.setContentType("application/pdf");
                if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
                        response.setHeader("Content-disposition", "inline; filename=invoice-"+logisticsTxnId+".pdf" );
                } else {
                        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 UserClient usc = null;

        private static Locale indianLocale = new Locale("en", "IN");
        private static String SORPL = "Spice Online Retail Pvt Ltd";
        private static String NEWCOMP = "Spice & Online Retail Pvt Ltd";
        private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
        private DecimalFormat weightFormat = new DecimalFormat("#0.000");

        //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";
        private static final String[] maharashtraPincodePrefix = {"40", "41", "42", "43", "44"};
        private static final String[] karnatakaPincodePrefix = {"56", "57", "58", "59"};
        private static final String[] telanganaPincodes = {"500001","500002","500003","500004","500005","500006","500007","500008","500009","500010","500011","500012","500013","500014","500015","500016","500017","500018","500019","500020","500021","500022","500023","500024","500025","500026","500027","500028","500029","500030","500031","500032","500033","500034","500035","500036","500037","500038","500039","500040","500041","500042","500043","500044","500045","500046","500047","500048","500049","500050","500051","500052","500053","500054","500055","500056","500057","500058","500059","500060","500061","500062","500063","500064","500065","500066","500067","500068","500069","500070","500071","500072","500073","500074","500075","500076","500077","500078","500079","500080","500081","500082","500083","500084","500085","500086","500087","500088","500089","500090","500091","500092","500093","500094","500095","500096","500097","500098","500178","500409","501218","501301","501401","501510","501511","501512","502307","502319","517501","517502","517503","517505","517507","520001","520002","520003","520004","520005","520006","520007","520008","520009","520010","520011","520012","520013","520014","520015","521108","521225","522001","522002","522003","522004","522005","522006","522007","522019","522509","530001","530002","530003","530004","530005","530007","530008","530009","530010","530010","530011","530012","530013","530014","530015","530016","530017","530018","530020","530021","530022","530023","530024","530026","530027","530028","530029","530032","530035","530040","530041","530043","530044","530045","530046","531001","533101","533103","533104","533105"};
        static final Map<Long,SellerInfo> sellerInfoMap = new HashMap<Long, SellerInfo>();
        static final Map<Long,WarehouseAddress> whAddressInfoMap = new HashMap<Long, WarehouseAddress>();
        private Address billingAddress;
        private SellerInfo sellerInfo;
        private WarehouseAddress addressInfo;

        public InvoiceGenerationService() {
                try {
                        tsc = new TransactionClient();
                        csc = new InventoryClient();
                        lsc = new LogisticsClient();
                        ctsc = new CatalogClient();
                        usc = new UserClient();
                } 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();
                
                //Sort out all variables related to company date here
                
                try {
                        baosPDF = new ByteArrayOutputStream();

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

                        List<Order> orders = new ArrayList<Order>();
                        Map<String, List<Order>> logisticsTxnIdOrdersMap = new HashMap<String, List<Order>>();
                        if(printAll){
                                try {
                                        List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                                        statuses.add(OrderStatus.ACCEPTED);
                                        if(!tclient.isAlive()){
                                                tclient = tsc.getClient();
                                        }
                                        orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
                                        for(Order o:orders){
                                                if(o.isSetLogisticsTransactionId()){
                                                        if(logisticsTxnIdOrdersMap.containsKey(o.getLogisticsTransactionId())){
                                                                List<Order> groupOrdersList = logisticsTxnIdOrdersMap.get(o.getLogisticsTransactionId());
                                                                groupOrdersList.add(o);
                                                                logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
                                                        }else {
                                                                List<Order> groupOrdersList = new ArrayList<Order>();
                                                                groupOrdersList.add(o);
                                                                logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
                                                        }
                                                }
                                        }
                                } catch (Exception e) {
                                        logger.error("Error while getting order information", e);
                                        return baosPDF; 
                                }
                        } else{
                                if(!tclient.isAlive()){
                                        tclient = tsc.getClient();
                                }
                                orders.add(tclient.getOrder(orderId));
                                Order o = orders.get(0);
                                try {
                                        sellerInfo = getSellerInfo(o.getSeller_id(), tclient);
                                        addressInfo = getWarehouseAddress(o.getWarehouse_address_id(), tclient);
                                } catch (Exception e) {
                                        logger.info("Error occurred while getting address/seller info", e);
                                        return baosPDF;
                                }
                                if(o.isSetLogisticsTransactionId()){
                                        List<Order> groupOrdersList = tclient.getGroupOrdersByLogisticsTxnId(o.getLogisticsTransactionId());
                                        logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
                                }
                        }
                        boolean isFirst = true;
                        if(logisticsTxnIdOrdersMap!=null && logisticsTxnIdOrdersMap.size()>0){
                                for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
                                        List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
                                        Order singleOrder = ordersList.get(0);
                                        Warehouse warehouse = null;
                                        Provider provider = null;
                                        String destCode = null;
                                        int barcodeFontSize = 0;
                                        String invoiceFormat = null;
                                        try {
                                                warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
                                                long providerId = singleOrder.getLogistics_provider_id();
                                                provider = logisticsClient.getProvider(providerId);
                                                if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
                                                        destCode = provider.getPickup().toString();
                                                else if (providerId==1L){
                                                        BluedartAttributes bluedartAttr = logisticsClient.getBluedartAttributesForLogisticsTxnId(singleOrder.getLogisticsTransactionId(), "destCode");
                                                        destCode = bluedartAttr.getValue();
                                                }
                                                else
                                                        destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());

                                                barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get("bluedart_barcode_fontsize"));
                                                
                                                invoiceFormat = tclient.getInvoiceFormatLogisticsTxnId(singleOrder.getTransactionId(), Long.parseLong(logisticsTxnId.split("-")[1])); 
                                        } 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){
                                                for(Order order : ordersList){
                                                        if(isFirst){
                                                                document.add(getFixedTextTable(16, sellerInfo.getOrganisationName()));
                                                                isFirst = false;
                                                        }
                                                        document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
                                                        continue;
                                                }
                                        }
                                        PdfPTable dispatchAdviceTable = null;
                                        Order order = ordersList.get(0);
                                        if(ordersList.size()==1){                                       
                                                if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
                                                        dispatchAdviceTable = new PdfPTable(1);
                                                }  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
                                                        dispatchAdviceTable = new PdfPTable(1);
                                                }  else if(new Long(order.getSource()).intValue() == OrderSource.HOMESHOP18.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(ordersList, provider, barcodeFontSize, destCode, withBill, invoiceFormat);
                                                }
                                        } else {
                                                dispatchAdviceTable = getDispatchAdviceTable(ordersList, provider, barcodeFontSize, destCode, withBill, invoiceFormat);
                                        }
                                        
                                        dispatchAdviceTable.setSpacingAfter(10.0f);
                                        dispatchAdviceTable.setWidthPercentage(90.0f);
                                        document.add(dispatchAdviceTable);
                                        if("Bulk".equalsIgnoreCase(invoiceFormat)){
                                                if(ordersList.size()>3 || (order.getLogistics_provider_id()==7 && (order.isLogisticsCod() || (!order.isLogisticsCod() && ordersList.size()>1))) 
                                                                || (order.getLogistics_provider_id()==46 && (order.isLogisticsCod() || (!order.isLogisticsCod() && ordersList.size()>1)))){
                                                        document.newPage();
                                                }
                                        }
                                        
                                        if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
                                                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(ordersList, provider, sellerInfo.getOrganisationName() + "\n"+ addressInfo.getAddress() + "-" + addressInfo.getPin() , sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                                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() &&(ordersList.size()==1)) {
                                                if(withBill){
                                                        PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, sellerInfo.getOrganisationName() + "\n" + addressInfo.getAddress() + "-" + addressInfo.getPin() , sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                        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(ordersList, provider, sellerInfo.getOrganisationName() + "\n" + addressInfo.getAddress() + "-" + addressInfo.getPin() , this.sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                taxTable.setSpacingBefore(5.0f);
                                                taxTable.setWidthPercentage(90.0f);
                                                document.add(new DottedLineSeparator());
                                                document.add(taxTable);
                                                if(order.getSource() == OrderSource.FLIPKART.getValue()) {
                                                        //document.add(new DottedLineSeparator());
                                                        document.add(getFlipkartBarCodes(order));
                                                }

                                        }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("Bulk".equalsIgnoreCase(invoiceFormat)){
                                                PdfPTable orderItemsDetailTable = new PdfPTable(1);
                                                orderItemsDetailTable.setWidthPercentage(90.0f);
                                                orderItemsDetailTable.setSpacingBefore(5.0f);
                                                orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
                                                StringBuffer sbOrders = new StringBuffer();

                                                for(Order o1 : ordersList){
                                                        sbOrders.append(o1.getId()+",");
                                                }

                                                
                                                String orderIds = sbOrders.toString();
                                                orderIds = orderIds.substring(0, orderIds.length()-1);
                                                
                                                StringBuffer sbImeis = new StringBuffer();

                                                for(Order o1 : ordersList){
                                                        if(o1.getLineitems().get(0).getSerial_number()!=null){
                                                                sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
                                                        }
                                                }

                                                orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
                                                
                                                if(sbImeis.length()>0){
                                                        orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
                                                        logger.info("Imeis List:- " + sbImeis);
                                                        String imeis = sbImeis.toString();
                                                        if(imeis.endsWith(","))
                                                                imeis = imeis.substring(0, imeis.length()-1);
                                                        logger.info("Final Imeis List:- " + sbImeis);
        
                                                        orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
                                                }
                                                
                                                document.add(orderItemsDetailTable);
                                        }
                                        PdfPTable billingAddressTable = getCustomerAddressTable(order, null, true, helvetica8, true, true);
                                        if(billingAddress!=null){
                                                billingAddressTable.setWidthPercentage(90.0f);
                                                billingAddressTable.setSpacingBefore(5.0f);
                                                billingAddressTable.addCell(new Phrase("Billing Address :", helveticaBold8));
                                                billingAddressTable.addCell(new Phrase(billingAddress.getName() +" "+billingAddress.getLine1()
                                                                +billingAddress.getLine2() +" "+billingAddress.getCity() + "," + billingAddress.getState()
                                                                +" -"+billingAddress.getPin(), helvetica8));
                                                document.add(billingAddressTable);
                                        }
                                        
                                        document.newPage();
                                }
                        } else {
                                for(Order singleOrder : orders){
                                        List<Order> ordersList = new ArrayList<Order>();
                                        ordersList.add(singleOrder);
                                        Warehouse warehouse = null;
                                        Provider provider = null;
                                        String destCode = null;
                                        Warehouse shippingLocation = null;
                                        int barcodeFontSize = 0;
                                        String invoiceFormat = "Individual";
                                        try {
                                                warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
                                                long providerId = singleOrder.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, singleOrder.getCustomer_pincode());

                                                barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get("bluedart_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){
                                                for(Order order : ordersList){
                                                        if(isFirst){
                                                                document.add(getFixedTextTable(16, sellerInfo.getOrganisationName()));
                                                                isFirst = false;
                                                        }
                                                        document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
                                                        continue;
                                                }
                                        }
                                        PdfPTable dispatchAdviceTable = null;
                                        Order order = ordersList.get(0);
                                        if(ordersList.size()==1){                                       
                                                if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
                                                        dispatchAdviceTable = new PdfPTable(1);
                                                }  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
                                                        dispatchAdviceTable = new PdfPTable(1);
                                                }  else if(new Long(order.getSource()).intValue() == OrderSource.HOMESHOP18.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(ordersList, provider, barcodeFontSize, destCode, withBill, invoiceFormat);
                                                }
                                        } else {
                                                dispatchAdviceTable = getDispatchAdviceTable(ordersList, provider, barcodeFontSize, destCode, withBill, invoiceFormat);
                                        }
                                        
                                        dispatchAdviceTable.setSpacingAfter(10.0f);
                                        dispatchAdviceTable.setWidthPercentage(90.0f);
                                        document.add(dispatchAdviceTable);
                                        if("Bulk".equalsIgnoreCase(invoiceFormat)){
                                                if(ordersList.size()>1){
                                                        document.newPage();
                                                }
                                        }
                                        
                                        if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
                                                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(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , this.sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                                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() &&(ordersList.size()==1)) {
                                                if(withBill){
                                                        PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , this.sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                        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(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , this.sellerInfo.getTin(), invoiceFormat, addressInfo.getContact_number());
                                                taxTable.setSpacingBefore(5.0f);
                                                taxTable.setWidthPercentage(90.0f);
                                                document.add(new DottedLineSeparator());
                                                document.add(taxTable);
                                                if(order.getSource() == OrderSource.FLIPKART.getValue()) {
                                                        //document.add(new DottedLineSeparator());
                                                        document.add(getFlipkartBarCodes(order));
                                                }

                                        }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("Bulk".equalsIgnoreCase(invoiceFormat)){
                                                PdfPTable orderItemsDetailTable = new PdfPTable(1);
                                                orderItemsDetailTable.setWidthPercentage(90.0f);
                                                orderItemsDetailTable.setSpacingBefore(5.0f);
                                                orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
                                                StringBuffer sbOrders = new StringBuffer();

                                                for(Order o1 : orders){
                                                        sbOrders.append(o1.getId()+",");
                                                }

                                                
                                                String orderIds = sbOrders.toString();
                                                orderIds = orderIds.substring(0, orderIds.length()-1);

                                                orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
                                                

                                                StringBuffer sbImeis = new StringBuffer();

                                                for(Order o1 : orders){
                                                        if(o1.getLineitems().get(0).getSerial_number()!=null){
                                                                sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
                                                        }
                                                }
                                                
                                                if(sbImeis.length()>0){
                                                        orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
        
                                                        logger.info("Imeis List:- " + sbImeis);
                                                        String imeis = sbImeis.toString();
                                                        imeis = imeis.substring(0, imeis.length()-2);
                                                        logger.info("Final Imeis List:- " + sbImeis);
        
                                                        orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
                                                }
                                                
                                                document.add(orderItemsDetailTable);
                                        }
                                        PdfPTable billingAddressTable = getCustomerAddressTable(order, null, true, helvetica8, true, true);
                                        if(billingAddress!=null){
                                                billingAddressTable.setWidthPercentage(90.0f);
                                                billingAddressTable.setSpacingBefore(5.0f);
                                                billingAddressTable.addCell(new Phrase("Billing Address :", helveticaBold8));
                                                billingAddressTable.addCell(new Phrase(billingAddress.getName() +" "+billingAddress.getLine1()
                                                                +billingAddress.getLine2() +" "+billingAddress.getCity() + "," + billingAddress.getState()
                                                                +" -"+billingAddress.getPin(), helvetica8));
                                                document.add(billingAddressTable);
                                        }
                                        
                                        document.newPage();
                                }
                        }
                        
                        
                        if(logisticsTxnIdOrdersMap!=null && logisticsTxnIdOrdersMap.size()>0){
                for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
                        document.newPage();
                        List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
                                        PdfPTable headerTable = new PdfPTable(1);
                                        headerTable.setWidthPercentage(90.0f);
                                        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                        headerTable.addCell(getInvoiceTableHeader(0,ordersList.get(0).getLogisticsTransactionId()));
                                        PdfPTable packagingTable = getPackagingInfoTable(ordersList);
                                        PdfPTable signTable = new PdfPTable(new float[]{0.1f, 0.8f, 0.1f});
                                        signTable.setWidthPercentage(90.0f);
                                        signTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                                        signTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                                        signTable.setSplitLate(false);
                                        signTable.setSpacingBefore(10.0f);
                                        signTable.addCell(new Phrase("Biller",helveticaBold8));
                                        signTable.addCell(new Phrase("",helveticaBold8));
                                        signTable.addCell(new Phrase("Packer",helveticaBold8));
                                        document.add(headerTable);
                                        document.add(packagingTable);
                                        document.add(signTable);
                                }
                                
                        }
                        
                        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;
        }
        //Handle this case when tClient is null
        private static WarehouseAddress getWarehouseAddress(long addressId, in.shop2020.model.v1.order.TransactionService.Client tClient) throws Exception{
                if (!whAddressInfoMap.containsKey(addressId)){
                        whAddressInfoMap.put(addressId, tClient.getWarehouseAddress(addressId));
                }
                return whAddressInfoMap.get(addressId);
        }
        //Handle this case when tClient is null
        
        private static SellerInfo getSellerInfo(long sellerId, in.shop2020.model.v1.order.TransactionService.Client tClient) throws Exception{
                if (!sellerInfoMap.containsKey(sellerId)){
                        SellerInfo si = tClient.getSellerInfo(sellerId);
                        if(si == null){
                                throw new Exception("Could not found seller");
                        }
                        sellerInfoMap.put(sellerId, si);
                }
                return sellerInfoMap.get(sellerId);
        }
        
        
        private PdfPTable getPackagingInfoTable(List<Order> orderList) throws CatalogServiceException, TException{
                PdfPTable finalTable = new PdfPTable(1);
                finalTable.setWidthPercentage(90.0f);
                finalTable.setSpacingBefore(5.0f);
                finalTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                finalTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                finalTable.setSplitLate(false);
                PdfPTable customerAddresTable = new PdfPTable(1);
                customerAddresTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                customerAddresTable.addCell(new Phrase("Customer Details: "+orderList.get(0).getCustomer_name() +" "+orderList.get(0).getCustomer_address1()
                                +orderList.get(0).getCustomer_address2() +" "+orderList.get(0).getCustomer_city() + "," + orderList.get(0).getCustomer_state()
                                +" -"+orderList.get(0).getCustomer_pincode(), helvetica8));
                PdfPTable packagingTable = new PdfPTable(new float[]{0.1f, 0.1f, 0.1f, 0.2f, 0.2f, 0.1f, 0.07f, 0.08f, 0.1f});
                packagingTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                packagingTable.addCell(new Phrase("ItemId", helveticaBold8));
                packagingTable.addCell(new Phrase("BIN Id", helveticaBold8));
                packagingTable.addCell(new Phrase("SubOrder Id", helveticaBold8));
                packagingTable.addCell(new Phrase("Item Desc", helveticaBold8));
                packagingTable.addCell(new Phrase("Sr Nos", helveticaBold8));
                packagingTable.addCell(new Phrase("Rate", helveticaBold8));
                packagingTable.addCell(new Phrase("Pack\nSize", helveticaBold8));
                packagingTable.addCell(new Phrase("Qty", helveticaBold8));
                packagingTable.addCell(new Phrase("Total Pcs.", helveticaBold8));
                packagingTable.setHeaderRows(1);
                
                Map<Long, Item> itemMap = new HashMap<Long, Item>();
                
                CatalogService.Client catalogClient = ctsc.getClient();
                for(Order order:orderList){
                        if(!itemMap.containsKey(order.getLineitems().get(0).getItem_id())){
                                itemMap.put(order.getLineitems().get(0).getItem_id(), catalogClient.getItem(order.getLineitems().get(0).getItem_id()));
                        }
                }
                
                double grandTotalPieces = 0;
                
                for(Order order:orderList){
                        packagingTable.addCell(new Phrase(order.getLineitems().get(0).getItem_id()+"", helvetica8));
                        packagingTable.addCell(new Phrase("", helveticaBold8));
                        packagingTable.addCell(new Phrase(order.getId()+"", helvetica8));
                        packagingTable.addCell(new Phrase(getItemDisplayName(order.getLineitems().get(0), false), helvetica8));
                        if(order.getLineitems().get(0).isSetSerial_number()){
                                String[] serialNumbers = order.getLineitems().get(0).getSerial_number().split(",");
                                String serialNoString = "";
                                for(String serialNo : serialNumbers){
                                        serialNoString += serialNo + "\n";
                                }
                                packagingTable.addCell(new Phrase(serialNoString, helvetica8));
                        }else{
                                packagingTable.addCell(new Phrase("", helvetica8));
                        }
                        packagingTable.addCell(new Phrase(order.getLineitems().get(0).getUnit_price()+"", helvetica8));
                        packagingTable.addCell(new Phrase(itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity()+"", helvetica8));
                        packagingTable.addCell(new Phrase(order.getLineitems().get(0).getQuantity()+"", helvetica8));
                        packagingTable.addCell(new Phrase((order.getLineitems().get(0).getQuantity()*itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity())+"", helvetica8));
                        grandTotalPieces += order.getLineitems().get(0).getQuantity()*itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity();
                }
                packagingTable.addCell(getTotalCell(8));
                packagingTable.addCell(new Phrase(grandTotalPieces+"", helveticaBold8));
                finalTable.addCell(customerAddresTable);
                finalTable.addCell(packagingTable);
                return finalTable;
        }
        
        private double getTotalAmountToCollect(List<Order> orderList){
                Order order = orderList.get(0);
                double totalAmount = 0.0;
                if(order.isSetNet_payable_amount()){
                        for (Order o: orderList){
                                totalAmount = totalAmount + o.getNet_payable_amount();
                        }
                }
                else{
                        for (Order o: orderList){
                                totalAmount = totalAmount + o.getTotal_amount() +o.getShippingCost()-o.getGvAmount()-o.getAdvanceAmount() -o.getWallet_amount();
                        }
                }
                return totalAmount;
        }
        
        private boolean isCod(List<Order> orderList){
                Order order = orderList.get(0);
                double totalAmount = 0.0;
                if (order.isCod()){
                        if(order.isSetNet_payable_amount()){
                                for (Order o: orderList){
                                        totalAmount = totalAmount + o.getNet_payable_amount();
                                }
                                if (totalAmount == 0){
                                        return false;
                                }
                        }
                        return true;
                }
                else{
                        return false;
                }
        }

        private PdfPTable getDispatchAdviceTable(List<Order> orderList, Provider provider, float barcodeFontSize, String destCode, boolean withBill, String invoiceFormat) throws TException{
                Order order = orderList.get(0);
                Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
                
                double totalAmount = getTotalAmountToCollect(orderList);
                double totalWeight = 0.0;
                boolean cashOnDelivery = isCod(orderList);
                
                for (Order o: orderList){
                        totalWeight = totalWeight + o.getTotal_weight();
                }

                PdfPTable table = new PdfPTable(1);
                table.setSplitLate(false);
                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, false);
                PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont, totalWeight, cashOnDelivery);

                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(orderList, this.sellerInfo.getTin(), invoiceFormat);
                PdfPTable addressTable = new PdfPTable(1);
                addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                
                PdfPCell addressCell = getAddressCell(sellerInfo.getOrganisationName() + "\n" + addressInfo.getAddress() +
                                " - " + addressInfo.getPin() + "\nContact No.- +91-"+addressInfo.getContact_number() + "\n\n");

                PdfPTable chargesTable = new PdfPTable(1);
                chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                if(cashOnDelivery){
                        chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (totalAmount), 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 || order.getLogistics_provider_id()==46L){
                                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 || order.getLogistics_provider_id()==46L){
                        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;
                
                logoCell = new PdfPCell(new Phrase(""));
                /*if(order.getSource() == OrderSource.STORE.getValue()){
                        
                }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, double totalWeight, boolean cashOnDelivery) throws TException {
                PdfPTable providerInfoTable = new PdfPTable(1);
                providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                
                if (provider.getId() ==1L){
                        PdfPCell spnCell = new PdfPCell(new Phrase("SPN : 09650099008S", helvetica12));
                        spnCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                        spnCell.setBorder(Rectangle.NO_BORDER);
                        providerInfoTable.addCell(spnCell);
                }
                
                if(cashOnDelivery){
                        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 || order.getLogistics_provider_id()==46L){
                        if(cashOnDelivery){
                                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 && order.getLogistics_provider_id()!=46L){
                        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 || order.getLogistics_provider_id()==46L){
                        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 (cashOnDelivery) {
            dt = DeliveryType.COD;
        }
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
        if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
                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{
                if(order.getLogistics_provider_id()==7L){
                        providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
                }else{
                        providerInfoTable.addCell(new Phrase("FEDEX EXPRESS SAVER ", 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 && order.getLogistics_provider_id()!=46L){
                        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
                }
                providerInfoTable.addCell(new Phrase("Weight         : " + weightFormat.format(totalWeight) + " Kg", helvetica8));
                if (order.getLogistics_provider_id()==1L){
                        ShipmentLogisticsCostDetail shipmentCostDetail = tsc.getClient().getCostDetailForLogisticsTxnId(order.getLogisticsTransactionId());
                        providerInfoTable.addCell(new Phrase("Dimensions(Cms)  : " +shipmentCostDetail.getPackageDimensions(), helvetica8));
                        providerInfoTable.addCell(new Phrase("Pieces  : " + "1", 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 || order.getLogistics_provider_id()==46L){
                        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(List<Order> orderList, String tinNo, String invoiceFormat){
                PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
                invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                invoiceTable.addCell(getInvoiceTableHeader(5,orderList.get(0).getLogisticsTransactionId()));
                if("Bulk".equalsIgnoreCase(invoiceFormat)){
                        invoiceTable.addCell(new Phrase("Sr No", helvetica8));
                }else{
                        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));
                invoiceTable.setHeaderRows(2);
                double totalAmount = 0.0;
                double totalShippingCost = 0.0;
                double insuranceAmount = 0.0;
                double advanceAmount = 0.0;
                double totalGvAmount = 0.0;
                double totalWalletAmount = 0.0;
                
                
                if("Bulk".equalsIgnoreCase(invoiceFormat)){
                        Map<Long, String> itemNamesMap= new HashMap<Long, String>();
                        Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
                        for(Order order : orderList){
                                LineItem lineitem = order.getLineitems().get(0);
                                totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount()-order.getWallet_amount();
                                totalShippingCost = totalShippingCost + order.getShippingCost();
                                totalGvAmount = totalGvAmount + order.getGvAmount();
                                totalWalletAmount = totalWalletAmount + order.getWallet_amount(); 
                                if(order.getInsurer() > 0) {
                                        insuranceAmount =insuranceAmount + order.getInsuranceAmount();
                                }
                                if(order.getSource() == OrderSource.STORE.getValue()) {
                                        advanceAmount = advanceAmount + order.getAdvanceAmount();
                                }
                                if(!itemNamesMap.containsKey(lineitem.getItem_id())){
                                        itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
                                }
                                if(!itemRateMap.containsKey(lineitem.getItem_id())){
                                        itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
                                }
                                if(itemQuantityMap.containsKey(lineitem.getItem_id())){
                                        double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
                                        itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
                                }else{
                                        itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
                                }
                                
                                if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
                                        double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount());
                                        itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
                                }else{
                                        itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount()));
                                }
//                              if(paymentMode==null || paymentMode.isEmpty()){
//                                      if(order.getPickupStoreId() > 0 && order.isCod() == true)
//                                              paymentMode = "In-Store";
//                                      else if (order.isCod())
//                                              paymentMode = "COD";
//                                      else
//                                              paymentMode = "Prepaid";
//                              }               
                        }
                        
                        int serialNo = 0;
                        for(Long itemId : itemNamesMap.keySet()){
                                serialNo ++;
                                invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
                                //invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
                                invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
                                invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
                                invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
                                invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
                        }
                        
                }else{
                        for(Order order : orderList){
                                populateTopInvoiceTable(order, invoiceTable);
                                if(order.getInsurer() > 0) {
                                        invoiceTable.addCell(getInsuranceCell(3));
                                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                                        invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
                                }

                                if(order.getSource() == OrderSource.STORE.getValue()) {
                                        invoiceTable.addCell(getAdvanceAmountCell(3));
                                        invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
                                        invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
                                }
                                if(order.getInsurer() > 0) {
                                        insuranceAmount =insuranceAmount + order.getInsuranceAmount();
                                }
                                if(order.getSource() == OrderSource.STORE.getValue()) {
                                        advanceAmount = advanceAmount + order.getAdvanceAmount();
                                }
                                totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount()-order.getWallet_amount();
                                totalShippingCost = totalShippingCost + order.getShippingCost();
                                totalGvAmount = totalGvAmount + order.getGvAmount();
                                totalWalletAmount = totalWalletAmount + order.getWallet_amount();
                        }
                }
                if(insuranceAmount>0){
                        invoiceTable.addCell(getInsuranceCell(3));
                        invoiceTable.addCell(getPriceCell(insuranceAmount));
                        invoiceTable.addCell(getPriceCell(insuranceAmount));
                }
                if(advanceAmount>0){
                        invoiceTable.addCell(getAdvanceAmountCell(3));
                        invoiceTable.addCell(getPriceCell(advanceAmount));
                        invoiceTable.addCell(getPriceCell(advanceAmount));
                }
                if(totalShippingCost>0){
                        invoiceTable.addCell(getShippingCostCell(3));      
                        invoiceTable.addCell(getRupeesCell(false));
                        invoiceTable.addCell(getPriceCell(totalShippingCost));
                }
                if(totalGvAmount>0){
                        totalGvAmount = 0-totalGvAmount;
                        invoiceTable.addCell(getGvAmountCell(3));      
                        invoiceTable.addCell(getRupeesCell(false));
                        invoiceTable.addCell(getPriceCell(totalGvAmount));
                }
                if(totalWalletAmount>0){
                        totalWalletAmount = 0-totalWalletAmount;
                        invoiceTable.addCell(getWalletAmountCell(3));      
                        invoiceTable.addCell(getRupeesCell(false));
                        invoiceTable.addCell(getPriceCell(totalWalletAmount));
                }
                
                invoiceTable.addCell(getTotalCell(3));      
                invoiceTable.addCell(getRupeesCell(true));
                invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
                

                PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
                tinCell.setColspan(5);
                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()));

                        invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
                }
        }

        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(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat, String contact_number){
                Order order = orderList.get(0);
                PdfPTable taxTable = new PdfPTable(1);
                Phrase phrase = null;
                taxTable.setSplitLate(false);
                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); 
                

                Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- +91-"+contact_number + "\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, false);
                if (order.getOrderType().equals(OrderType.B2B)) {
                        if(billingAddress!=null){
                                if(order.getCustomer_state().trim().equalsIgnoreCase(billingAddress.getState())){
                                        phrase = new Phrase("TAX INVOICE", helveticaBold12);
                                }else{
                                        phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
                                }
                        }else{
                                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);
                
                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 = isVatApplicable(order);
                PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);

                PdfPTable regAddAndDisCellTable = new PdfPTable(2);
                
                PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Haryana Jurisdiction.\nThis is a Computer generated Invoice.", helvetica8));
                disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                disclaimerCell.setBorder(Rectangle.NO_BORDER);
                PdfPCell regAddressCell = new PdfPCell(new Phrase(sellerInfo.getOrganisationName() + "\n" +
                                                                                "Regd. Add. " +  sellerInfo.getRegisteredAddress() + "\n" + 
                                                                                (StringUtils.isEmpty(sellerInfo.getCinNumber())? "" :"CIN: " + sellerInfo.getCinNumber() + "\n") +  
                                                                                "Tel. No. +91-"+contact_number+" E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
                regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                regAddressCell.setBorder(Rectangle.NO_BORDER);
                /*SPICE ONLINE RETAIL PRIVATE LIMITED
                Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
                CIN: U74140DL2008PTC183856
                Tel. No. 0120-2479977
                E-mail. help@saholic.com
                Website. www.saholic.com*/
                PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
                powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                powerTextCell.setBorder(Rectangle.NO_BORDER);
                powerTextCell.setPaddingBottom(30.0f);
                
                logoTitleAndOurAddressTable.addCell(logoTable);
                logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
                logoTitleAndOurAddressTable.addCell(sorlAddress);
                
                regAddAndDisCellTable.addCell(disclaimerCell);
                regAddAndDisCellTable.addCell(regAddressCell);
                
                taxTable.addCell(logoTitleAndOurAddressTable);
                taxTable.addCell(addrAndOrderDetailsTable);
                taxTable.addCell(invoiceTable);
                taxTable.addCell(regAddAndDisCellTable);
                if(order.getSource() == OrderSource.FLIPKART.getValue()) {
                        taxTable.addCell(powerTextCell);
                        
                }
                if(order.getProductCondition().equals(ProductCondition.BAD)){
                        PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
                                        "may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
                                        "are not returnable, exchangeable or refundable under any circumstances. No " +
                                        "warranty is assured on these items." ,
                                        new Font(FontFamily.TIMES_ROMAN, 8f)));
                        badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                        badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
                        taxTable.addCell(badSaleDisclaimerCell);
                }
                return taxTable;
        }
        
        private boolean isVatApplicable(Order order) {
                if(order.getWarehouse_id() == 7) {
                        if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
                                return true;
                        } else {
                                return false;
                        }
                } else if(order.getWarehouse_id() == 3298){
                        for(int i=0; i< telanganaPincodes.length; i++) {
                                if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
                                        return true;
                                }
                        }
                        return false;
                } else if(order.getWarehouse_id() == 1765 || order.getWarehouse_id() == 1768){
                        for(int i=0; i< karnatakaPincodePrefix.length; i++) {
                                if(order.getCustomer_pincode().startsWith(karnatakaPincodePrefix[i])) {
                                        return true;
                                }
                        }
                        return false;
                }
                else {
                        for(int i=0; i< maharashtraPincodePrefix.length; i++) {
                                if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
                                        return true;
                                }
                        }
                        return false;
                }
        }

        private PdfPTable getFlipkartBarCodes(Order order) {
                PdfPTable flipkartTable = new PdfPTable(3);
                
                PdfPCell spacerCell = new PdfPCell();
                spacerCell.setBorder(Rectangle.NO_BORDER);
                spacerCell.setColspan(3);
                spacerCell.setPaddingTop(330.0f);
                
                String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
                FontFactoryImp ttfFontFactory = new FontFactoryImp();
                ttfFontFactory.register(flipkartCodeFontPath, "barcode");
                Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
                
                String serialNumber = "0000000000";
                if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
                        serialNumber = order.getLineitems().get(0).getSerial_number();
                } else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
                        serialNumber = order.getLineitems().get(0).getItem_number();
                }
                
                PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
                serialNumberBarCodeCell.setBorder(Rectangle.TOP);
                serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                serialNumberBarCodeCell.setPaddingTop(11.0f);
                
                
                PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
                invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
                invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                invoiceNumberBarCodeCell.setPaddingTop(11.0f);
                
                double rate = order.getLineitems().get(0).getVatRate();
                double salesTax = (rate * order.getTotal_amount())/(100 + rate);
                PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
                vatAmtBarCodeCell.setBorder(Rectangle.TOP);
                vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                vatAmtBarCodeCell.setPaddingTop(11.0f);
                
                flipkartTable.addCell(spacerCell);
                flipkartTable.addCell(serialNumberBarCodeCell);
                flipkartTable.addCell(invoiceNumberBarCodeCell);
                flipkartTable.addCell(vatAmtBarCodeCell);
                
                return flipkartTable;
                
        }
        
        private void setBillingAddress(long userId, in.shop2020.model.v1.user.UserContextService.Client userClient) throws TException{
                billingAddress = userClient.getBillingAddressForUser(userId);
        }

        private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce, boolean billingAdd){
                PdfPTable customerTable = new PdfPTable(1);
                //customerTable.addCell(new Phrase("Deliver To :",font));
                if(forInvoce || order.getPickupStoreId() == 0){
                        in.shop2020.model.v1.user.UserContextService.Client userClient = usc.getClient();
                        try {
                                if(billingAdd && userClient.isPrivateDealUser(order.getCustomer_id())){
                                        setBillingAddress(order.getCustomer_id(), userClient);
                                        if(billingAddress!=null){
                                                return customerTable;
                                                /*
                                                customerTable.addCell(new Phrase(billingAddress.getName(), font));
                                                customerTable.addCell(new Phrase(billingAddress.getLine1(), font));
                                                customerTable.addCell(new Phrase(billingAddress.getLine2(), font));
                                                customerTable.addCell(new Phrase(billingAddress.getCity() + "," + billingAddress.getState(), font));
                                                customerTable.addCell(new Phrase(billingAddress.getPin(), font));
                                                customerTable.addCell(new Phrase("Phone : " + (billingAddress.getPhone()== null ? "" : billingAddress.getPhone()), font));
                                                */
                                        }else{
                                                if (!forInvoce)
                                                        customerTable.addCell(new Phrase("Deliver To:", font));
                                                customerTable.addCell(new Phrase(order.getCustomer_name(), font));
                                                if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
                                                        HsOrder hsOrder = null;
                                                        try {
                                                                hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
                                                        }catch (TException e) {
                                                                logger.error("Error while getting homeshop18 order", e);
                                                        }
                                                        String hsShippingName = hsOrder.getShippingName();
                                                        if(hsShippingName!=null && !hsShippingName.isEmpty()){
                                                                customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, 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  && order.getLogistics_provider_id()!=46L){
                                                        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
                                                if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
                                                        customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
                                                }
                                        }
                                }else{
                                        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                                        if(!forInvoce)
                                                customerTable.addCell(new Phrase("Deliver To:", font));
                                        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
                                        if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
                                                HsOrder hsOrder = null;
                                                try {
                                                        hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
                                                }catch (TException e) {
                                                        logger.error("Error while getting homeshop18 order", e);
                                                }
                                                String hsShippingName = hsOrder.getShippingName();
                                                if(hsShippingName!=null && !hsShippingName.isEmpty()){
                                                        customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, 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  && order.getLogistics_provider_id()!=46L){
                                                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
                                        if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
                                                customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
                                        }
                                }
                        } catch (TException e2) {
                                e2.printStackTrace();
                        }
                        
                }else{
                        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        try {
                                in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
                                PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
                                if(!forInvoce)
                                        customerTable.addCell(new Phrase("Deliver To:", font));
                                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));

                String hsCourierName = "";
                if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
                        AmazonOrder aorder = null;
                        try {
                                aorder = tsc.getClient().getAmazonOrder(order.getId());
                        } catch (TException e) {
                                logger.error("Error while getting amazon order", e);
                        }
                        if(order.getSource() == OrderSource.JUNGLEE.getValue()){
                                orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
                        }else {
                                orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
                        }
                        orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
                } else if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
                        HsOrder hsOrder = null;
                        try {
                                hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
                        }catch (TException e) {
                                logger.error("Error while getting homeshop18 order", e);
                        }
                        hsCourierName = hsOrder.getCourierName();
                        orderTable.addCell(new Phrase("HomeShop18 Order No:", helvetica8));
                        orderTable.addCell(new Phrase(hsOrder.getHsOrderNo(), helvetica8));
                        orderTable.addCell(new Phrase("HomeShop18 Sub Order No:", helvetica8));
                        orderTable.addCell(new Phrase(hsOrder.getHsSubOrderNo(), 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, null).get(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));
                        
                        String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
                        FontFactoryImp ttfFontFactory = new FontFactoryImp();
                        ttfFontFactory.register(refernceCodeFontPath, "barcode");
                        Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);

                        PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
                        snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
                        snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
                        snapdealReferenceBarCodeCell.setColspan(2);
                        snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        //orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
                        orderTable.addCell(snapdealReferenceBarCodeCell);
                        //orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
                }
                else if(order.getSource() == OrderSource.FLIPKART.getValue()){
                        FlipkartOrder flipkartOrder = null;
                        try {
                                flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
                        } catch (TException e) {
                                logger.error("Error while getting flipkart order", e);
                        }
                        orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
                        orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
                        
                        //orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
                        String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
                        FontFactoryImp ttfFontFactory = new FontFactoryImp();
                        ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
                        Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
                        
                        orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
                        PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
                        flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
                        flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
                        //flipkartOrderItemIdBarCodeCell.setColspan(2);
                        //flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        orderTable.addCell(flipkartOrderItemIdBarCodeCell);
                        //orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
                        //orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
                }


                orderTable.addCell(new Phrase("Order Date:", helvetica8));
                orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
                
                if(OrderType.B2B==order.getOrderType()){
                        try {
                                String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
                                if(poRefVal!=null && poRefVal.length()>0){
                                        orderTable.addCell(new Phrase("PO Ref:", helvetica8));
                                        orderTable.addCell(new Phrase(poRefVal, helvetica8));
                                }
                                
                        } catch (TException e) {
                                logger.error("Error while getting amazon order", e);
                        }
                }

                orderTable.addCell(new Phrase("Courier:", helvetica8));
                if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
                        orderTable.addCell(new Phrase(hsCourierName, helvetica8));
                } else{
                        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
                }

                if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
                        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(List<Order> orderList,boolean isVAT, String invoiceFormat){
                PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
                invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

                invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));

                if("Bulk".equalsIgnoreCase(invoiceFormat)){
                        invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
                }else{
                        invoiceTable.addCell(new Phrase("Order 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));
                invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
                invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
                invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));
                invoiceTable.setHeaderRows(2);
                double totalAmount = 0.0;
                double insuranceAmount = 0.0;
                double totalShippingCost = 0.0;
                int i=1;
                if("Bulk".equalsIgnoreCase(invoiceFormat)){
                        Map<Long, String> itemNamesMap= new HashMap<Long, String>();
                        Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
                        Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
                        
                        for(Order order : orderList){
                                LineItem lineitem = order.getLineitems().get(0);
                                
                                double orderAmount = order.getTotal_amount();
                                double rate = lineitem.getVatRate();
                                double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
                                totalAmount = totalAmount + orderAmount;
                                totalShippingCost = totalShippingCost + order.getShippingCost();
                                double itemPrice = lineitem.getUnit_price();
                                double showPrice = (100 * itemPrice)/(100 + rate);
                                double totalPrice = lineitem.getTotal_price();
                                double showTotalPrice = (100 * totalPrice)/(100 + rate);
                                
                                if(order.getInsurer() > 0) {
                                        insuranceAmount =insuranceAmount + order.getInsuranceAmount();
                                }
                                
                                if(!itemNamesMap.containsKey(lineitem.getItem_id())){
                                        itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
                                }
                                if(itemQuantityMap.containsKey(lineitem.getItem_id())){
                                        double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
                                        itemQuantityMap.put(lineitem.getItem_id(), quantity);
                                } else {
                                        itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
                                }
                                if(!itemRateMap.containsKey(lineitem.getItem_id())){
                                        itemRateMap.put(lineitem.getItem_id(), showPrice);
                                }
                                if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
                                        itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
                                }
                                if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
                                        double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
                                        itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
                                }else{
                                        itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
                                }
                                if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
                                        double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
                                        itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
                                }else{
                                        itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
                                }
                        }
                        
                        for(Long itemId : itemNamesMap.keySet()){
                                invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
                                invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
                                invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
                                invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
                                invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
                                invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
                                invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
                                invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
                                i++;
                        }
                }
                else{
                
                        for(Order order :orderList){
                                LineItem lineItem = order.getLineitems().get(0);
                                double orderAmount = order.getTotal_amount();
                                double rate = lineItem.getVatRate();
                                double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
        
                                invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
                                invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
                                invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
        
        
                                //populateBottomInvoiceTable(order, invoiceTable, rate);
        
                                double itemPrice = lineItem.getUnit_price();
                                double showPrice = (100 * itemPrice)/(100 + rate);
                                invoiceTable.addCell(getPriceCell(showPrice));
        
                                double totalPrice = lineItem.getTotal_price();
                                showPrice = (100 * totalPrice)/(100 + rate);
                                invoiceTable.addCell(getPriceCell(showPrice));
        
                                PdfPCell salesTaxCell = getPriceCell(salesTax);
        
        
                                invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
                                invoiceTable.addCell(salesTaxCell);
                                invoiceTable.addCell(getTotalAmountCell(orderAmount));
        
                                if(order.getInsurer() > 0) {
                                        insuranceAmount =insuranceAmount + order.getInsuranceAmount();
                                }
                                totalAmount = totalAmount+ orderAmount;
                                totalShippingCost = totalShippingCost + order.getShippingCost();
                                i++;
                        }
                }

                if(insuranceAmount>0){
                        invoiceTable.addCell(getInsuranceCell(7));
                        invoiceTable.addCell(getPriceCell(insuranceAmount));
                }
                if(totalShippingCost>0){
                        invoiceTable.addCell(getShippingCostCell(6));      
                        invoiceTable.addCell(getRupeesCell(false));
                        invoiceTable.addCell(getPriceCell(totalShippingCost));
                }
                invoiceTable.addCell(getTotalCell(6));
                invoiceTable.addCell(getRupeesCell(true));
                invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));

                invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
                invoiceTable.addCell(getAmountInWordsCell(totalAmount+totalShippingCost));

                invoiceTable.addCell(getEOECell(8));

                return invoiceTable;
        }

        private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
                PdfPTable invoiceHeaderTable = new PdfPTable(2);
                PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
                if(masterOrderId!=null && !masterOrderId.isEmpty()){
                        masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
                        masterOrderIdCell.setPaddingTop(1);
                }
                PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
                invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
                invoiceTableHeader.setPaddingTop(1);
                invoiceHeaderTable.addCell(invoiceTableHeader);
                if(masterOrderId!=null && !masterOrderId.isEmpty()){
                        invoiceHeaderTable.addCell(masterOrderIdCell);
                }else{
                        masterOrderIdCell = new PdfPCell(new Phrase(" ", helvetica10));
                        invoiceHeaderTable.addCell(masterOrderIdCell);
                }
                PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
                headerCell.setColspan(colspan);
                return headerCell;
        }

        /*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
                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 getCFORMLabelCell() {
                PdfPCell cFormCell = null;
                cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
                cFormCell.setColspan(3);
                cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return cFormCell;
        }
        
        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. T&C Apply", 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 getShippingCostCell(int colspan) {
                PdfPCell shippingCostCell = new PdfPCell(new Phrase("Shipping Charges", helvetica8));
                shippingCostCell.setColspan(colspan);
                shippingCostCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                return shippingCostCell;
        }
        
        private PdfPCell getCodChargesCell(int colspan) {
                PdfPCell codChargesCell = new PdfPCell(new Phrase("COD Charges", helvetica8));
                codChargesCell.setColspan(colspan);
                return codChargesCell;
        }
        
        private PdfPCell getGvAmountCell(int colspan) {
                PdfPCell codChargesCell = new PdfPCell(new Phrase("GV Amount", helvetica8));
                codChargesCell.setColspan(colspan);
                return codChargesCell;
        }
        
        private PdfPCell getWalletAmountCell(int colspan) {
                PdfPCell codChargesCell = new PdfPCell(new Phrase("Wallet Amount", helvetica8));
                codChargesCell.setColspan(colspan);
                return codChargesCell;
        }

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

        private PdfPCell getRupeesCell(boolean useBold) {
                PdfPCell rupeesCell;
                if(useBold)
                        rupeesCell= new PdfPCell(new Phrase("Rs.", helveticaBold8));
                else
                        rupeesCell= new PdfPCell(new Phrase("Rs.", helvetica8));
                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() && !lineitem.getSerial_number().isEmpty()){
                        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.");
        }
}