Subversion Repositories SmartDukaan

Rev

Rev 22889 | Rev 23001 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.common.util;


import java.io.OutputStream;
import java.util.Locale;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.ibm.icu.text.RuleBasedNumberFormat;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.spice.profitmandi.common.model.CustomCustomer;
import com.spice.profitmandi.common.model.CustomOrderItem;
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.PdfModel;

public class PdfUtils {
        
        private static final Font FONT_TITLE = new Font(Font.FontFamily.HELVETICA  , 18, Font.BOLD);
        private static Font FONT_NORMAL = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
        private static Font FONT_BOLD = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
        //private static Font fontTableHeader = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
        private static final String INVOICE_TITLE = "INVOICE";
        
        private static float[] igstWidthsWithDiscount = new float[]{.3f, 2.6f, 0.7f, .4f, 0.7f, 0.5f, .7f, .6f, 0.6f, 0.9f};
        private static float[] stateWidthsWithDiscount = new float[]{.2f, 2.1f, 0.7f, .3f, 0.6f, 0.4f, .7f, .5f, .6f, .5f, .6f, .8f};
        
        private static final Locale indianLocale = Locale.getDefault();
        
        private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
        
        public static void generateAndWrite(PdfModel pdfModel, OutputStream outputStream){
                Document document = new Document();
                document.setMargins(0, 0, 25, 0);
        try {
                CustomCustomer customer = pdfModel.getCustomer();
                CustomRetailer retailer = pdfModel.getRetailer();
                boolean stateGst = false;
                String customerAddressStateCode = "", retailerAddressStateCode = "";
                if(customer.getAddress().getState().equals(retailer.getAddress().getState())){
                        stateGst = true;
                        customerAddressStateCode = Utils.getStateCode(customer.getAddress().getState());
                }else{
                        customerAddressStateCode = Utils.getStateCode(customer.getAddress().getState());
                        retailerAddressStateCode = Utils.getStateCode(retailer.getAddress().getState());
                }
                Set<CustomOrderItem> orderItems = pdfModel.getOrderItems();
                
            PdfWriter.getInstance(document,outputStream);

            document.open();
            document.addTitle(pdfModel.getTitle());
            document.addAuthor(pdfModel.getAuther());
            
            Paragraph paragraphTitle = new Paragraph(INVOICE_TITLE, FONT_TITLE);
            paragraphTitle.setAlignment(Element.ALIGN_CENTER);
            
            PdfPCell blankCell = new PdfPCell();
            blankCell.setBorder(Rectangle.NO_BORDER);
            PdfPTable tableCustomerRetailer = new PdfPTable(3);
            tableCustomerRetailer.setWidthPercentage(90);
            tableCustomerRetailer.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            PdfPCell columnCustomerInfo = new PdfPCell();
            columnCustomerInfo.addElement(new Paragraph("Customer Details", FONT_BOLD));
            columnCustomerInfo.addElement(new Paragraph(StringUtils.capitalize(customer.getFirstName() + " " + customer.getLastName()), FONT_NORMAL));
            columnCustomerInfo.addElement(new Paragraph(StringUtils.capitalize(customer.getAddress().getLine1()) + ", " + StringUtils.capitalize(customer.getAddress().getLine2()), FONT_NORMAL));
            columnCustomerInfo.addElement(new Paragraph(StringUtils.capitalize(customer.getAddress().getCity()) + ", " + StringUtils.capitalize(customer.getAddress().getState()) + "(" + customerAddressStateCode + ")" + "\n" + customer.getAddress().getPinCode(), FONT_NORMAL));
            columnCustomerInfo.addElement(new Paragraph("Mobile - " + customer.getMobileNumber(), FONT_NORMAL));
            columnCustomerInfo.setBorder(Rectangle.NO_BORDER);
            PdfPCell columnRetailerInfo = new PdfPCell();
            columnRetailerInfo.addElement(new Paragraph(StringUtils.capitalize(retailer.getBusinessName()), FONT_BOLD));
            columnRetailerInfo.addElement(new Paragraph(StringUtils.capitalize(retailer.getAddress().getLine1()) + ", " + StringUtils.capitalize(retailer.getAddress().getLine2()) + ", " + StringUtils.capitalize(retailer.getAddress().getCity()) + "-" + retailer.getAddress().getPinCode() + ", " + retailer.getAddress().getState() + "(" + (stateGst? customerAddressStateCode : retailerAddressStateCode) + ")", FONT_BOLD));
            columnRetailerInfo.addElement(new Paragraph("Contact No.- "+retailer.getMobileNumber(), FONT_BOLD));
            columnRetailerInfo.addElement(new Paragraph("GST NO. " + retailer.getGstNumber(), FONT_BOLD));
            columnRetailerInfo.setBorder(Rectangle.NO_BORDER);
            
            PdfPTable tableInvoiceDateRetailer = new PdfPTable(1);
            tableInvoiceDateRetailer.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            
            PdfPTable tableInvoiceDate = new PdfPTable(2);
            tableInvoiceDate.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            
            PdfPCell invoiceNumberKey = new PdfPCell(new Paragraph("Invoice No:", FONT_NORMAL));
            invoiceNumberKey.setBorder(Rectangle.NO_BORDER);
            
            PdfPCell invoiceNumberValue = new PdfPCell(new Paragraph(pdfModel.getInvoiceNumber(), FONT_NORMAL));
            invoiceNumberValue.setBorder(Rectangle.NO_BORDER);
            
            PdfPCell dateKey = new PdfPCell(new Paragraph("Date:", FONT_NORMAL));
            dateKey.setBorder(Rectangle.NO_BORDER);

            PdfPCell dateValue = new PdfPCell(new Paragraph(pdfModel.getInvoiceDate(), FONT_NORMAL));
            dateValue.setBorder(Rectangle.NO_BORDER);
            tableInvoiceDate.addCell(invoiceNumberKey);
            //tableInvoiceDate.addCell(blankCell);
            tableInvoiceDate.addCell(invoiceNumberValue);
            tableInvoiceDate.addCell(dateKey);
            //tableInvoiceDate.addCell(blankCell);
            tableInvoiceDate.addCell(dateValue);
            tableInvoiceDateRetailer.addCell(tableInvoiceDate);
            tableInvoiceDateRetailer.addCell(columnRetailerInfo);
            
            tableCustomerRetailer.addCell(columnCustomerInfo);
            tableCustomerRetailer.addCell(blankCell);
            tableCustomerRetailer.addCell(tableInvoiceDateRetailer);
            
            PdfPTable orders = null;
            if(stateGst){
                orders = new PdfPTable(stateWidthsWithDiscount.length);
                orders.setWidths(stateWidthsWithDiscount);
            }else{
                orders = new PdfPTable(igstWidthsWithDiscount.length);
                orders.setWidths(igstWidthsWithDiscount);
            }
            orders.setWidthPercentage(90);
            orders.addCell(new Paragraph("Sl", FONT_BOLD));
            orders.addCell(new Paragraph("Description", FONT_BOLD));
            orders.addCell(new Paragraph("HSN", FONT_BOLD));
            orders.addCell(new Paragraph("Qty", FONT_BOLD));
            orders.addCell(new Paragraph("Rate\n(Per pc)", FONT_BOLD));
            orders.addCell(new Paragraph("Disc.", FONT_BOLD));
            orders.addCell(new Paragraph("Total\nTaxable", FONT_BOLD));
            if(!stateGst){
                orders.addCell(new Paragraph("IGST\n%", FONT_BOLD));
                orders.addCell(new Paragraph("IGST", FONT_BOLD));
                //orders.setWidths(new float[]{1, 3, 1, 1, 1, 1, 1, 1});
                //total 8f
            }else{
                orders.addCell(new Paragraph("CGST %", FONT_BOLD));
                orders.addCell(new Paragraph("CGST", FONT_BOLD));
                orders.addCell(new Paragraph("SGST %", FONT_BOLD));
                orders.addCell(new Paragraph("SGST", FONT_BOLD));
                //orders.setWidths(new float[]{1, 3, 1, 1, 1, 1, 1, 1, 1, 1});
                //total 8f
            }
            orders.addCell(new Paragraph("Total", FONT_BOLD));
            
            //orders.addCell(new Paragraph("Item Total (Rs)", FONT_BOLD));
            
            orders.setHeaderRows(1);
            //orders.setSkipFirstHeader(true);
            
            float igstTotalAmount = 0, cgstTotalAmount = 0, sgstTotalAmount = 0;
            int index = 1;
                for(CustomOrderItem orderItem : orderItems){
                orders.addCell(new Paragraph(String.valueOf(index++), FONT_NORMAL));
                orders.addCell(new Paragraph(orderItem.getDescription(), FONT_NORMAL));
                orders.addCell(new Paragraph(orderItem.getHsnCode(), FONT_NORMAL));
                orders.addCell(new Paragraph(String.valueOf(orderItem.getQuantity()), FONT_NORMAL));
                orders.addCell(new Paragraph(String.format("%.2f", orderItem.getRate()), FONT_NORMAL));
                orders.addCell(new Paragraph(String.format("%.2f", orderItem.getDiscount()), FONT_NORMAL));
                orders.addCell(new Paragraph(String.format("%.2f", orderItem.getAmount()), FONT_NORMAL));
                if(!stateGst){
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getIgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getIgstAmount()), FONT_NORMAL));
                        igstTotalAmount = igstTotalAmount + orderItem.getIgstAmount();
                }else{
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getCgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getCgstAmount()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getSgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", orderItem.getSgstAmount()), FONT_NORMAL));
                        cgstTotalAmount = cgstTotalAmount + orderItem.getCgstAmount();
                        sgstTotalAmount = sgstTotalAmount + orderItem.getSgstAmount();
                }
                orders.addCell(new Paragraph(String.format("%.0f", orderItem.getNetAmount()), FONT_NORMAL));
                //orders.addCell(new Paragraph(String.format("%.2f", orderItem.getItemTotal()), FONT_NORMAL));
            }
                
                for(CustomInsurancePolicy insurancePolicy : pdfModel.getInsurancePolicies()){
                        orders.addCell(new Paragraph(String.valueOf(index++), FONT_NORMAL));
                orders.addCell(new Paragraph(insurancePolicy.getDescription(), FONT_NORMAL));
                orders.addCell(new Paragraph(insurancePolicy.getHsnCode(), FONT_NORMAL));
                orders.addCell(new Paragraph("1", FONT_NORMAL));
                orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getRate()), FONT_NORMAL));
                orders.addCell(new Paragraph("-", FONT_NORMAL));
                orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getRate()), FONT_NORMAL));
                if(!stateGst){
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getIgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getIgstAmount()), FONT_NORMAL));
                        igstTotalAmount = igstTotalAmount + insurancePolicy.getIgstAmount();
                }else{
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getCgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getCgstAmount()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getSgstRate()), FONT_NORMAL));
                        orders.addCell(new Paragraph(String.format("%.2f", insurancePolicy.getSgstAmount()), FONT_NORMAL));
                        cgstTotalAmount = cgstTotalAmount + insurancePolicy.getCgstAmount();
                        sgstTotalAmount = sgstTotalAmount + insurancePolicy.getSgstAmount();
                }
                orders.addCell(new Paragraph(String.format("%.0f", insurancePolicy.getNetAmount()), FONT_NORMAL));
                }

                document.add(paragraphTitle);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(tableCustomerRetailer);
            
            document.add(Chunk.NEWLINE);
            document.add(orders);
            
            PdfPTable grandTotalTable = new PdfPTable(3);
            if(stateGst){
                grandTotalTable.setWidths(new float[]{6.6f, .6f, .8f});
            }else{
                grandTotalTable.setWidths(new float[]{6.5f, .6f, .9f});
            }
            grandTotalTable.setWidthPercentage(90);
            
            Paragraph grandTotalParagraph = new Paragraph("Grand total", FONT_BOLD);
            grandTotalParagraph.setIndentationRight(20);
            grandTotalTable.addCell(grandTotalParagraph);
            Paragraph rsParagraph = new Paragraph("Rs.", FONT_BOLD);
            grandTotalTable.addCell(rsParagraph);
            Paragraph amountParagraph = new Paragraph(String.format("%.2f", pdfModel.getTotalAmount()), FONT_BOLD);
            grandTotalTable.addCell(amountParagraph);
            
            
            document.add(grandTotalTable);
            
            PdfPTable amountInWordsTable = new PdfPTable(3);
            if(!stateGst){
                amountInWordsTable.setWidths(new float[]{2, 5.1f, 0.9f});
            }else{
                amountInWordsTable.setWidths(new float[]{2, 5.2f, 0.8f});
            }
            amountInWordsTable.setWidthPercentage(90);
            amountInWordsTable.addCell(new Paragraph("Amount in Words:", FONT_BOLD));
            
            String amountInWords = toAmountInWords(pdfModel.getTotalAmount());
                amountInWordsTable.addCell(new Paragraph(amountInWords.toString(), FONT_BOLD));
            amountInWordsTable.addCell(new Paragraph("E & O.E", FONT_NORMAL));
            document.add(amountInWordsTable);            
            
            StringBuffer sb = new StringBuffer();
            sb.append("I agree that goods received are in good working condition");
            sb.append("\nGoods once sold cannot be exchanged or taken back");
            sb.append("\nWarranty for the goods received by me is the responsibility of the manufacturer only.");
            if(pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
                sb.append("\nDamage protection provided is the responisibility of Protection Provider only");
            }
            Paragraph warningParagraph = new Paragraph(sb.toString(), FONT_NORMAL);
            warningParagraph.setIndentationLeft(40);
            document.add(Chunk.NEWLINE);
            document.add(warningParagraph);
            
            document.close(); // no need to close PDFwriter?

        } catch (DocumentException e) {
            LOGGER.error("Unable to write data to pdf file : ", e);
        } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        
        private static String toAmountInWords(float amount){
                RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
        StringBuilder amountInWords = new StringBuilder("Rs. ");
        amountInWords.append(StringUtils.capitalize(amountInWordsFormat.format((int)amount)));
        amountInWords.append(" and ");
        amountInWords.append(StringUtils.capitalize(amountInWordsFormat.format((int)(amount*100)%100)));
        amountInWords.append(" paise");
        return amountInWords.toString();
        }
}