public void toWords_withTwentiesNumber_Return_Success()
        {
            var result = NumberToTextEN.toWords(21);

            Assert.NotEmpty(result);
            Assert.Equal("Twenty One  ", result);
        }
        public void toWords_withHundredNumber_Return_Success()
        {
            var result = NumberToTextEN.toWords(200);

            Assert.NotEmpty(result);
            Assert.Equal("Two  Hundred  ", result);
        }
        public void toWords_With_DozenNumber_Return_Success()
        {
            var result = NumberToTextEN.toWords(16);

            Assert.NotEmpty(result);
            Assert.Equal("Sixteen  ", result);
        }
        public MemoryStream GeneratePdfTemplate(SpinningSalesContractViewModel viewModel, int timeoffset)
        {
            Font normal_font_9  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            Font normal_font_10 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);
            Font bold_font_10   = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10, Font.BOLD);

            Document     document = new Document(PageSize.A4, 40, 40, 120, 40);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region customViewModel

            var    uom        = "";
            double convertion = 0;
            if (viewModel.UomUnit == "BALL")
            {
                uom        = "BALES";
                convertion = (viewModel.OrderQuantity) * (181.44);
            }

            var ppn = viewModel.IncomeTax;
            if (ppn == "Include PPn")
            {
                ppn = "Include PPn 10%";
            }

            string QuantityToText = NumberToTextEN.toWords(viewModel.OrderQuantity);
            double amount         = Convert.ToDouble((viewModel.Price * convertion).ToString("N2"));
            string AmountToText   = NumberToTextEN.toWords(amount);

            var tax = viewModel.IncomeTax == "Include PPn" ? "Include PPn 10%" : viewModel.IncomeTax;

            var detailprice = viewModel.AccountBank.Currency.Symbol + " " + string.Format("{0:n2}", viewModel.Price) + " / KG";

            var appx = "";
            var date = viewModel.DeliverySchedule.Value.Day;
            if (date >= 1 && date <= 10)
            {
                appx = "EARLY";
            }
            else if (date >= 11 && date <= 20)
            {
                appx = "MIDDLE";
            }
            else if (date >= 21 && date <= 31)
            {
                appx = "END";
            }

            #endregion

            #region Header

            string    codeNoString = "FM-PJ-00-03-004";
            Paragraph dateString   = new Paragraph($"{codeNoString}\nSukoharjo, {viewModel.CreatedUtc.AddHours(timeoffset).ToString("MMMM dd, yyyy", new CultureInfo("en-US"))}", normal_font_9)
            {
                Alignment = Element.ALIGN_RIGHT, Leading = 10
            };
            dateString.SpacingAfter = 5f;
            document.Add(dateString);

            #region Identity


            PdfPTable tableIdentityOpeningLetter = new PdfPTable(2);
            tableIdentityOpeningLetter.SetWidths(new float[] { 15f, 2f });
            PdfPCell cellIdentityContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_LEFT
            };
            cellIdentityContentLeft.SetLeading(1.5f, 1);
            PdfPCell cellIdentityContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            cellIdentityContentRight.SetLeading(1.5f, 1);

            cellIdentityContentLeft.Phrase = new Phrase($"MESSRS,\n{viewModel.Buyer.Name}\n{viewModel.Buyer.Address}\n{viewModel.Buyer.Country?.ToUpper()}\n{viewModel.Buyer.Contact}", normal_font_10);
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);

            PdfPCell cellIdentityOpeningLetter = new PdfPCell(tableIdentityOpeningLetter); // dont remove
            tableIdentityOpeningLetter.ExtendLastRow = false;
            tableIdentityOpeningLetter.SpacingAfter  = 10f;
            document.Add(tableIdentityOpeningLetter);

            #endregion

            string    titleString = "SALES CONTRACT";
            Paragraph title       = new Paragraph(titleString, bold_font_10)
            {
                Alignment = Element.ALIGN_CENTER
            };
            title.SpacingAfter = 10f;
            document.Add(title);
            #endregion

            string    HeaderParagraphString = "On behalf of :";
            Paragraph HeaderParagraph       = new Paragraph(HeaderParagraphString, normal_font_9)
            {
                Alignment = Element.ALIGN_LEFT, Leading = 11
            };
            document.Add(HeaderParagraph);

            string    firstParagraphString = "P.T. DAN LIRIS KELURAHAN BANARAN, KECAMATAN GROGOL SUKOHARJO - INDONESIA, we confrm the order under the following terms and conditions as mentioned below: ";
            Paragraph firstParagraph       = new Paragraph(firstParagraphString, normal_font_9)
            {
                Alignment = Element.ALIGN_LEFT, Leading = 11
            };
            firstParagraph.SpacingAfter = 10f;
            document.Add(firstParagraph);

            #region body
            PdfPTable tableBody = new PdfPTable(3);
            tableBody.SetWidths(new float[] { 0.3f, 0.05f, 1.1f });
            PdfPCell bodyContentCenter = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_CENTER
            };
            bodyContentCenter.SetLeading(1.5f, 1);
            PdfPCell bodyContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_LEFT
            };
            bodyContentLeft.SetLeading(1.5f, 1);
            PdfPCell bodyContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            bodyContentRight.SetLeading(1.5f, 1);
            PdfPCell bodyContentColon = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_LEFT
            };
            bodyContentColon.SetLeading(1.5f, 1);
            bodyContentColon.Phrase = new Phrase(":", normal_font_9);

            bodyContentLeft.Phrase = new Phrase("Contract Number", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(viewModel.SalesContractNo, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Comodity", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            string comodity = viewModel.Comodity.Name;
            if (!string.IsNullOrEmpty(viewModel.ComodityDescription) && !string.IsNullOrWhiteSpace(viewModel.ComodityDescription))
            {
                comodity = comodity + "\n" + viewModel.ComodityDescription;
            }
            bodyContentLeft.Phrase = new Phrase(comodity, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Quality", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(viewModel.Quality.Name, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Quantity", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase("ABOUT " + viewModel.OrderQuantity.ToString("N2") + " " + uom + " ( ABOUT : " + convertion.ToString("N2") + " KG) ", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Price & Payment", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(detailprice + "\n" + viewModel.TermOfShipment + "\n" + viewModel.TermOfPayment.Name, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Amount", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(viewModel.AccountBank.Currency.Symbol + " " + string.Format("{0:n2}", amount) + " ( " + AmountToText + " " + viewModel.AccountBank.Currency.Description?.ToUpper() + " ) (APPROXIMATELLY)", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Shipment", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(appx + " " + (viewModel.DeliverySchedule.Value.AddHours(timeoffset).ToString("MMMM yyyy", new CultureInfo("en-US")))?.ToUpper() + " " + viewModel.ShipmentDescription, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Destination", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(viewModel.DeliveredTo, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Packing", normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            tableBody.AddCell(bodyContentColon);
            bodyContentLeft.Phrase = new Phrase(viewModel.Packing, normal_font_9);
            tableBody.AddCell(bodyContentLeft);
            PdfPCell cellBody = new PdfPCell(tableBody); // dont remove
            tableBody.ExtendLastRow = false;
            document.Add(tableBody);

            PdfPTable conditionListBody = new PdfPTable(3);
            conditionListBody.SetWidths(new float[] { 0.3f, 0.05f, 1.1f });

            bodyContentLeft.Phrase = new Phrase("Condition", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentCenter.Phrase = new Phrase("-", normal_font_9);
            conditionListBody.AddCell(bodyContentCenter);
            bodyContentLeft.Phrase = new Phrase("THIS CONTRACT IS IRREVOCABLE UNLESS AGREED UPON BY THE TWO PARTIES, THE BUYER AND SELLER.", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentCenter.Phrase = new Phrase("-", normal_font_9);
            conditionListBody.AddCell(bodyContentCenter);
            bodyContentLeft.Phrase = new Phrase("+/- " + viewModel.ShippingQuantityTolerance + " % FROM QUANTITY ORDER SHOULD BE ACCEPTABLE.", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentCenter.Phrase = new Phrase("-", normal_font_9);
            conditionListBody.AddCell(bodyContentCenter);
            bodyContentLeft.Phrase = new Phrase("LOCAL CONTAINER DELIVERY CHARGES AT DESTINATION FOR BUYER'S ACCOUNT.", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentCenter.Phrase = new Phrase("- ", normal_font_9);
            conditionListBody.AddCell(bodyContentCenter);
            bodyContentLeft.Phrase = new Phrase(viewModel.Condition, normal_font_9);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentRight.Phrase = new Phrase("");
            conditionListBody.AddCell(bodyContentRight);
            PdfPCell cellConditionList = new PdfPCell(conditionListBody); // dont remove
            conditionListBody.ExtendLastRow = false;
            conditionListBody.SpacingAfter  = 10f;
            document.Add(conditionListBody);

            #endregion

            #region signature
            PdfPTable signature = new PdfPTable(2);
            signature.SetWidths(new float[] { 1f, 1f });
            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            signature.SetWidths(new float[] { 1f, 1f });
            cell_signature.Phrase = new Phrase("Accepted and confrmed :", normal_font_9);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("PT DANLIRIS", normal_font_9);
            signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("", normal_font_9);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font_9);
            signature.AddCell(cell_signature);

            string signatureArea = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                signatureArea += Environment.NewLine;
            }

            cell_signature.Phrase = new Phrase(signatureArea, normal_font_9);
            signature.AddCell(cell_signature);
            signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("(...........................)", normal_font_9);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("( SRI HENDRATNO )", normal_font_9);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Authorized signature", normal_font_9);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Marketing Textile", normal_font_9);
            signature.AddCell(cell_signature);
            cellIdentityContentRight.Phrase = new Phrase("");
            signature.AddCell(cellIdentityContentRight);

            PdfPCell signatureCell = new PdfPCell(signature); // dont remove
            signature.ExtendLastRow = false;
            document.Add(signature);
            #endregion

            #region ConditionPage

            string    ConditionString = "REMARK :";
            Paragraph ConditionName   = new Paragraph(ConditionString, normal_font_9)
            {
                Alignment = Element.ALIGN_LEFT
            };
            document.Add(ConditionName);

            string   bulletListSymbol   = "\u2022";
            PdfPCell bodyContentJustify = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Padding = 0, HorizontalAlignment = Element.ALIGN_JUSTIFIED
            };
            bodyContentJustify.SetLeading(1.5f, 1);

            PdfPTable conditionList = new PdfPTable(2);
            conditionList.SetWidths(new float[] { 0.02f, 1f });

            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("All instructions regarding sticker, shipping marks etc. to be received 1 (one) month prior to shipment.", normal_font_9);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("Benefciary :  P.T. DAN LIRIS KELURAHAN BANARAN, KECAMATAN GROGOL SUKOHARJO - INDONESIA  (Phone No. 0271 - 740888 / 714400). ", normal_font_9);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("Payment Transferred to: ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("PAYMENT TO BE TRANSFERRED TO BANK " + viewModel.AccountBank.BankName, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(viewModel.AccountBank.BankAddress, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("ACCOUNT NAME : " + viewModel.AccountBank.AccountName, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("ACCOUNT NO : " + viewModel.AccountBank.AccountNumber + " SWIFT CODE : " + viewModel.AccountBank.SwiftCode, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase(viewModel.TermOfPayment.Name + " to be negotiable with BANK " + viewModel.AccountBank.BankName, normal_font_9);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("Please find enclosed some Indonesia Banking Regulations.", normal_font_9);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font_9);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("If you find anything not order, please let us know immediately.", normal_font_9);
            conditionList.AddCell(bodyContentJustify);
            PdfPCell conditionListData = new PdfPCell(conditionList); // dont remove
            conditionList.ExtendLastRow = false;
            document.Add(conditionList);
            #endregion

            #region agentTemplate
            if (viewModel.Agent.Id != 0)
            {
                document.NewPage();

                #region Identity
                PdfPTable agentIdentity = new PdfPTable(3);
                agentIdentity.SetWidths(new float[] { 0.5f, 4.5f, 2.5f });
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase($"Sukoharjo, {viewModel.CreatedUtc.AddHours(timeoffset).ToString("MMMM dd, yyyy", new CultureInfo("en-US"))}", normal_font_9);
                agentIdentity.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font_9);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentity.AddCell(cellIdentityContentRight);
                PdfPCell agentCellIdentity = new PdfPCell(agentIdentity); // dont remove
                agentIdentity.ExtendLastRow = false;
                agentIdentity.SpacingAfter  = 10f;
                document.Add(agentIdentity);

                PdfPTable agentIdentityOpeningLetter = new PdfPTable(3);
                agentIdentityOpeningLetter.SetWidths(new float[] { 15f, 1f, 1f });
                cellIdentityContentLeft.Phrase = new Phrase("MESSRS,", normal_font_9);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Agent.Name, normal_font_9);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Agent.Address, normal_font_9);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                //if (!string.IsNullOrEmpty(viewModel.Agent.City))
                //{
                //    cellIdentityContentLeft.Phrase = new Phrase(viewModel.Agent.City, normal_font);
                //    agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                //    cellIdentityContentRight.Phrase = new Phrase("");
                //    agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                //    cellIdentityContentRight.Phrase = new Phrase("");
                //    agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                //}
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Agent.Country?.ToUpper(), normal_font_9);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Agent.Contact, normal_font_9);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                PdfPCell agentCellIdentityOpeningLetter = new PdfPCell(agentIdentityOpeningLetter); // dont remove
                agentIdentityOpeningLetter.ExtendLastRow = false;
                agentIdentityOpeningLetter.SpacingAfter  = 10f;
                document.Add(agentIdentityOpeningLetter);


                PdfPTable agentIdentityOpeningLetterHeader = new PdfPTable(1);
                bodyContentCenter.Phrase = new Phrase("COMMISSION AGREEMENT NO: " + viewModel.DispositionNumber, bold_font_10);
                agentIdentityOpeningLetterHeader.AddCell(bodyContentCenter);
                bodyContentCenter.Phrase = new Phrase("FOR SALES CONTRACT NO: " + viewModel.SalesContractNo, bold_font_10);
                agentIdentityOpeningLetterHeader.AddCell(bodyContentCenter);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetterHeader.AddCell(cellIdentityContentRight);
                PdfPCell agentIdentityOpeningLetterHeaderCell = new PdfPCell(agentIdentityOpeningLetterHeader); // dont remove
                agentIdentityOpeningLetterHeader.ExtendLastRow = false;
                agentIdentityOpeningLetterHeader.SpacingAfter  = 10f;
                document.Add(agentIdentityOpeningLetterHeader);

                #endregion

                #region agentBody
                string    agentFirstParagraphString = "This is to confirm that your order for " + viewModel.Buyer.Name + " concerning " + viewModel.OrderQuantity.ToString("N2") + " ( " + QuantityToText + ") " + uom + " ( ABOUT: " + convertion.ToString("N2") + " KG ) of ";
                Paragraph agentFirstParagraph       = new Paragraph(agentFirstParagraphString, normal_font_9)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                document.Add(agentFirstParagraph);
                string    agentFirstParagraphStringName = viewModel.Comodity.Name;
                Paragraph agentFirstParagraphName       = new Paragraph(agentFirstParagraphStringName, normal_font_9)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                document.Add(agentFirstParagraphName);
                string    agentFirstParagraphStringDescription = viewModel.ComodityDescription;
                Paragraph agentFirstParagraphDescription       = new Paragraph(agentFirstParagraphStringDescription, normal_font_9)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentFirstParagraphDescription.SpacingAfter = 10f;
                document.Add(agentFirstParagraphDescription);
                string    agentSecondParagraphString = "Placed with us, P.T. DAN LIRIS - SOLO INDONESIA, is inclusive of " + viewModel.Comission + " sales commission each KG on " + viewModel.TermOfShipment + " value, payable to you upon final negotiation and clearance of " + viewModel.TermOfPayment.Name + '.';
                Paragraph agentSecondParagraph       = new Paragraph(agentSecondParagraphString, normal_font_9)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentSecondParagraph.SpacingAfter = 10f;
                document.Add(agentSecondParagraph);
                string    agentThirdParagraphString = "Kindly acknowledge receipt by undersigning this Commission Agreement letter and returned one copy to us after having been confirmed and signed by you.";
                Paragraph agentThirdParagraph       = new Paragraph(agentThirdParagraphString, normal_font_9)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentThirdParagraph.SpacingAfter = 30f;
                document.Add(agentThirdParagraph);
                #endregion

                #region signature
                PdfPTable signatureAgent = new PdfPTable(2);
                signatureAgent.SetWidths(new float[] { 1f, 1f });
                signatureAgent.SetWidths(new float[] { 1f, 1f });
                cell_signature.Phrase = new Phrase("Accepted and confrmed :", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("PT DANLIRIS", normal_font_9);
                signatureAgent.AddCell(cell_signature);

                cell_signature.Phrase = new Phrase("", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("", normal_font_9);
                signatureAgent.AddCell(cell_signature);

                string signatureAreaAgent = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    signatureAreaAgent += Environment.NewLine;
                }

                cell_signature.Phrase = new Phrase(signatureArea, normal_font_9);
                signatureAgent.AddCell(cell_signature);
                signatureAgent.AddCell(cell_signature);

                cell_signature.Phrase = new Phrase("(...........................)", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("( SRI HENDRATNO )", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("Authorized signature", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("Marketing Textile", normal_font_9);
                signatureAgent.AddCell(cell_signature);
                cellIdentityContentRight.Phrase = new Phrase("");
                signatureAgent.AddCell(cellIdentityContentRight);

                PdfPCell signatureCellAgent = new PdfPCell(signatureAgent); // dont remove
                signatureAgent.ExtendLastRow = false;
                signatureAgent.SpacingAfter  = 10f;
                document.Add(signatureAgent);
            }
            #endregion

            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel, string fob, string cprice)
        {
            //int maxSizesCount = viewModel.Items.Max(i => i.Details.Max(d => d.Sizes.GroupBy(g => g.Size.Id).Count()));
            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newItems2  = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items)
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Index).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Description         = a.Description,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            foreach (var item in newItems)
            {
                if (newItems2.Count == 0)
                {
                    newItems2.Add(item);
                }
                else
                {
                    if (newItems2.Last().OrderNo == item.OrderNo && newItems2.Last().Description == item.Description)
                    {
                        foreach (var d in item.Details)
                        {
                            newItems2.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Description         = a.Description,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == item.Id);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        foreach (var d in item.Details)
                        {
                            y.Details.Add(d);
                        }
                        newItems2.Add(y);
                    }
                }
            }

            var sizesCount = false;

            foreach (var item in newItems2)
            {
                var sizesMax = new Dictionary <int, string>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1).ThenBy(o => o.Carton2))
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizesMax[size.Size.Id] = size.Size.Size;
                    }
                }
                if (sizesMax.Count > 11)
                {
                    sizesCount = true;
                }
            }
            int SIZES_COUNT = sizesCount ? 20 : 11;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(sizesCount ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 170, 30);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentPackingListPDFTemplatePageEvent(_identityProvider, viewModel);

            document.Open();

            #region Description

            PdfPTable tableDescription = new PdfPTable(3);
            tableDescription.SetWidths(new float[] { 2f, 0.2f, 7.8f });
            PdfPCell cellDescription = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellDescription.Phrase = new Phrase(cprice, normal_font);
            tableDescription.AddCell(cellDescription);
            cellDescription.Phrase = new Phrase(":", normal_font);
            tableDescription.AddCell(cellDescription);
            cellDescription.Phrase = new Phrase(fob, normal_font);
            tableDescription.AddCell(cellDescription);
            if (viewModel.PaymentTerm == "LC")
            {
                cellDescription.Phrase = new Phrase("LC No.", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.LCNo, normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase("Tgl. LC", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(_identityProvider.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy"), normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase("ISSUED BY", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.IssuedBy, normal_font);
                tableDescription.AddCell(cellDescription);
            }
            else
            {
                cellDescription.Phrase = new Phrase("Payment Term", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.PaymentTerm, normal_font);
                tableDescription.AddCell(cellDescription);
            }

            new PdfPCell(tableDescription);
            tableDescription.ExtendLastRow = false;
            tableDescription.SpacingAfter  = 5f;
            document.Add(tableDescription);

            #endregion

            PdfPCell cellBorderBottomRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellBorderBottom = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            double        totalCtns       = 0;
            double        grandTotal      = 0;
            var           uom             = "";
            var           arrayGrandTotal = new Dictionary <String, double>();
            List <string> cartonNumbers   = new List <string>();

            foreach (var item in newItems2)
            {
                #region Item

                PdfPTable tableItem = new PdfPTable(3);
                tableItem.SetWidths(new float[] { 2f, 0.2f, 7.8f });
                PdfPCell cellItemContent = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };

                cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.Description, normal_font);
                tableItem.AddCell(cellItemContent);

                new PdfPCell(tableItem);
                tableItem.ExtendLastRow = false;
                document.Add(tableItem);

                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }
                PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 11 : 8));
                var       width       = new List <float> {
                    2f, 3.5f, 4f, 4f
                };
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    width.Add(1f);
                }
                if (viewModel.InvoiceType == "DL")
                {
                    width.AddRange(new List <float> {
                        1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f
                    });
                }
                else
                {
                    width.AddRange(new List <float> {
                        1.5f, 1f, 1.5f, 2f
                    });
                }
                tableDetail.SetWidths(width.ToArray());

                PdfPCell cellDetailLine = new PdfPCell()
                {
                    Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("")
                };
                tableDetail.AddCell(cellDetailLine);
                tableDetail.AddCell(cellDetailLine);

                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = SIZES_COUNT;
                cellBorderBottomRight.Rowspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SATUAN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                if (viewModel.InvoiceType == "DL")
                {
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f));
                    cellBorderBottomRight.Rowspan = 2;
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Rowspan = 1;
                }

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f));
                    cellBorderBottomRight.Rowspan = 1;
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                double subCtns       = 0;
                double subTotal      = 0;
                var    sizeSumQty    = new Dictionary <int, double>();
                var    arraySubTotal = new Dictionary <String, double>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1).ThenBy(o => o.Carton2))
                {
                    var ctnsQty = detail.CartonQuantity;
                    uom = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Uom.Unit;
                    var article = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Article;
                    if (cartonNumbers.Contains($"{detail.Index} - {detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Index} - {detail.Carton1}- {detail.Carton2}");
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                    subCtns += ctnsQty;
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;
                    if (!arraySubTotal.ContainsKey(uom))
                    {
                        arraySubTotal.Add(uom, totalQuantity);
                    }
                    else
                    {
                        arraySubTotal[uom] += totalQuantity;
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(uom, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    if (viewModel.InvoiceType == "DL")
                    {
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                    tableDetail.AddCell(cellBorderBottomRight);
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                if (viewModel.InvoiceType == "DL")
                {
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                totalCtns  += subCtns;
                grandTotal += subTotal;
                if (!arrayGrandTotal.ContainsKey(uom))
                {
                    arrayGrandTotal.Add(uom, subTotal);
                }
                else
                {
                    arrayGrandTotal[uom] += subTotal;
                }

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 6 : 3),
                    Padding = 5,
                    Phrase  = new Phrase("SUB TOTAL .............................................................................................................................................. ", normal_font)
                });
                var subTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
                cellBorderBottom.Phrase  = new Phrase(subTotalResult, normal_font);
                cellBorderBottom.Colspan = 2;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Phrase  = new Phrase("", normal_font);
                cellBorderBottom.Colspan = 3;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Colspan = 1;

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 11 : 8),
                    Phrase  = new Phrase($"      - Sub Ctns = {subCtns}           - Sub G.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalGrossWeight = d.CartonQuantity * d.GrossWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalGrossWeight).Sum())} Kgs           - Sub N.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalNetWeight = d.CartonQuantity * d.NetWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalNetWeight).Sum())} Kgs            - Sub N.N.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalNetNetWeight = d.CartonQuantity * d.NetNetWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalNetNetWeight).Sum())} Kgs", normal_font)
                });

                cellBorderBottom.Phrase = new Phrase("", normal_font);
                tableDetail.AddCell(cellBorderBottom);

                new PdfPCell(tableDetail);
                tableDetail.ExtendLastRow   = false;
                tableDetail.KeepTogether    = true;
                tableDetail.WidthPercentage = 95f;
                tableDetail.SpacingAfter    = 10f;
                document.Add(tableDetail);
            }

            #region GrandTotal

            PdfPTable tableGrandTotal = new PdfPTable(2);
            tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 3f });
            PdfPCell cellHeaderLine = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("")
            };

            tableGrandTotal.AddCell(cellHeaderLine);
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.BOTTOM_BORDER,
                Padding = 6,
                Phrase  = new Phrase("GRAND TOTAL ...................................................................................................................................................................................", normal_font)
            });
            var grandTotalResult = string.Join(" / ", arrayGrandTotal.Select(x => x.Value + " " + x.Key).ToArray());
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border              = Rectangle.BOTTOM_BORDER,
                Padding             = 4,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase              = new Phrase(grandTotalResult, normal_font)
            });
            tableGrandTotal.AddCell(cellHeaderLine);
            var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 2,
                Padding = 5,
                Phrase  = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", viewModel.OtherCommodity)}]", normal_font)
            });

            new PdfPCell(tableGrandTotal);
            tableGrandTotal.ExtendLastRow   = false;
            tableGrandTotal.WidthPercentage = 95f;
            tableGrandTotal.SpacingAfter    = 5f;
            document.Add(tableGrandTotal);

            #endregion

            #region Mark

            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 1f, 1f });

            PdfPCell cellShippingMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font);
            chunkShippingMark.SetUnderline(0.5f, -1);
            Phrase phraseShippingMark = new Phrase();
            phraseShippingMark.Add(chunkShippingMark);
            phraseShippingMark.Add(new Chunk("     :", normal_font));
            cellShippingMark.AddElement(phraseShippingMark);
            cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font));
            tableMark.AddCell(cellShippingMark);

            PdfPCell cellSideMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font);
            chunkSideMark.SetUnderline(0.5f, -1);
            Phrase phraseSideMark = new Phrase();
            phraseSideMark.Add(chunkSideMark);
            phraseSideMark.Add(new Chunk("     :", normal_font));
            cellSideMark.AddElement(phraseSideMark);
            cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font)
            {
            });
            tableMark.AddCell(cellSideMark);

            var    noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z";
            byte[] shippingMarkImage;
            if (String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                viewModel.ShippingMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
            {
                shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));
                Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);

                if (shipMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / shipMarkImage.Width;
                    shipMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
                shipMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark.AddCell(shipMarkImageCell);
            }

            byte[] sideMarkImage;

            if (String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                viewModel.SideMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
            {
                sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);

                if (_sideMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / _sideMarkImage.Width;
                    _sideMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
                _sideMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark.AddCell(_sideMarkImageCell);
            }

            new PdfPCell(tableMark);
            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 5f;
            document.Add(tableMark);

            #endregion

            #region Measurement

            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.GrossWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NettWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NetNetWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm         = 0;
            int     countMeasurement = 0;
            var     measurements     = new List <(double, double, double)>();
            foreach (var measurement in viewModel.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);


                if (measurements.Contains((measurement.Length, measurement.Width, measurement.Height)) == false)
                {
                    measurements.Add((measurement.Length, measurement.Width, measurement.Height));
                    countMeasurement++;
                }
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            if (countMeasurement > 1)
            {
                cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }


            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            var paddingRight = SIZES_COUNT > 11 ? 400 : 200;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = paddingRight
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase("REMARK :", normal_font_underlined)
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase(viewModel.Remark, normal_font)
            });

            byte[] remarkImage;

            if (String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                viewModel.RemarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
            {
                remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));
                Image images = Image.GetInstance(imgb: remarkImage);

                if (images.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / images.Width;
                    images.ScalePercent(percentage * 100);
                }

                PdfPCell imageCell = new PdfPCell(images);
                imageCell.Border  = Rectangle.NO_BORDER;
                imageCell.Colspan = 3;
                tableMeasurement.AddCell(imageCell);
            }

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);

            #endregion

            #region sign
            PdfPTable tableSign = new PdfPTable(3);
            tableSign.WidthPercentage = 100;
            tableSign.SetWidths(new float[] { 1f, 1f, 1f });

            PdfPCell cellBodySignNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };


            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);


            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("( MRS. ADRIYANA DAMAYANTI )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);

            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("AUTHORIZED SIGNATURE", normal_font_underlined);
            tableSign.AddCell(cellBodySignNoBorder);

            document.Add(tableSign);
            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#6
0
        public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel, int timeoffset)
        {
            int maxSizesCount = viewModel.Items == null || viewModel.Items.Count < 1 ? 0 : viewModel.Items.Max(i => i.Details == null || i.Details.Count < 1 ? 0 : i.Details.Max(d => d.Sizes == null || d.Sizes.Count < 1 ? 0 : d.Sizes.GroupBy(g => g.Size.Id).Count()));
            int SIZES_COUNT   = maxSizesCount > 11 ? 20 : 11;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(maxSizesCount > 11 ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 70, 30);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentPackingListDraftPdfByCartonMDTemplatePageEvent(_identityProvider, viewModel);

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            PdfPCell cellBorderBottomRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellBorderBottom = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            var           cartons       = new List <GarmentPackingListDetailViewModel>();
            double        grandTotal    = 0;
            var           arraySubTotal = new Dictionary <String, double>();
            List <string> cartonNumbers = new List <string>();

            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newItems2  = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items.OrderBy(a => a.RONo))
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Carton1).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.OrderBy(o => o.RONo).Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            foreach (var item in newItems)
            {
                if (newItems2.Count == 0)
                {
                    newItems2.Add(item);
                }
                else
                {
                    if (newItems2.Last().RONo == item.RONo && newItems2.Last().OrderNo == item.OrderNo)
                    {
                        foreach (var d in item.Details.OrderBy(a => a.Carton1))
                        {
                            newItems2.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        newItems2.Add(item);
                    }
                }
            }

            foreach (var item in newItems2)
            {
                #region Item

                PdfPTable tableItem = new PdfPTable(6);
                tableItem.SetWidths(new float[] { 2f, 0.2f, 2.8f, 2f, 0.2f, 2.8f });
                PdfPCell cellItemContent = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };

                cellItemContent.Phrase = new Phrase("Shipping Method", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.ShipmentMode, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("Fabric Composition", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.FabricComposition, normal_font);
                tableItem.AddCell(cellItemContent);

                cellItemContent.Phrase = new Phrase("Tgl Trucking", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.TruckingEstimationDate.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID")), normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("Negara Asal Fabric", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.FabricCountryOrigin, normal_font);
                tableItem.AddCell(cellItemContent);

                cellItemContent.Phrase = new Phrase("Negara Tujuan Akhir", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.FinalDestination, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("Remark Merhandiser", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.RemarkMd, normal_font);
                tableItem.AddCell(cellItemContent);
                //
                cellItemContent.Phrase = new Phrase("RO No", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.RONo, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("ARTICLE", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.Article, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("BUYER", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.BuyerAgent.Name, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.ComodityDescription, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);

                new PdfPCell(tableItem);
                tableItem.ExtendLastRow = false;
                document.Add(tableItem);

                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }

                PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + 11);
                var       width       = new List <float> {
                    2f, 3.5f, 4f, 4f
                };
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    width.Add(1f);
                }
                width.AddRange(new List <float> {
                    1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f
                });
                tableDetail.SetWidths(width.ToArray());

                PdfPCell cellDetailLine = new PdfPCell()
                {
                    Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("")
                };
                tableDetail.AddCell(cellDetailLine);
                tableDetail.AddCell(cellDetailLine);

                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = SIZES_COUNT;
                cellBorderBottomRight.Rowspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("SATUAN", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Rowspan = 1;

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f));
                    cellBorderBottomRight.Rowspan = 1;
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                var subCartons      = new List <GarmentPackingListDetailViewModel>();
                var subGrossWeight  = new List <GarmentPackingListDetailViewModel>();
                var subNetWeight    = new List <GarmentPackingListDetailViewModel>();
                var subNetNetWeight = new List <GarmentPackingListDetailViewModel>();

                double subTotal   = 0;
                var    sizeSumQty = new Dictionary <int, double>();
                foreach (var detail in item.Details)
                {
                    var ctnsQty      = detail.CartonQuantity;
                    var grossWeight  = detail.GrossWeight;
                    var netWeight    = detail.NetWeight;
                    var netNetWeight = detail.NetNetWeight;
                    if (cartonNumbers.Contains($"{detail.Index}-{detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty      = 0;
                        grossWeight  = 0;
                        netWeight    = 0;
                        netNetWeight = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Index}-{detail.Carton1}- {detail.Carton2}");
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.Uom.Unit, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);

                    if (cartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        cartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                    }
                    if (subCartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        subCartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                        subGrossWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, GrossWeight = grossWeight
                        });
                        subNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetWeight = netWeight
                        });
                        subNetNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetNetWeight = netNetWeight
                        });
                    }
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.5f));

                    tableDetail.AddCell(cellBorderBottomRight);
                }
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);


                grandTotal += subTotal;
                if (!arraySubTotal.ContainsKey(item.Uom.Unit))
                {
                    arraySubTotal.Add(item.Uom.Unit, subTotal);
                }
                else
                {
                    arraySubTotal[item.Uom.Unit] += subTotal;
                }

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 6,
                    Padding = 5,
                    Phrase  = new Phrase("SUB TOTAL ....................................................................................................................................................................... ", normal_font)
                });
                cellBorderBottom.Phrase  = new Phrase(subTotal.ToString() + " " + item.Uom.Unit, normal_font);
                cellBorderBottom.Colspan = 2;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Phrase  = new Phrase("", normal_font);
                cellBorderBottom.Colspan = 3;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Colspan = 1;

                var subCtns = subCartons.Sum(c => c.CartonQuantity);
                var subGw   = subGrossWeight.Sum(c => c.CartonQuantity * c.GrossWeight);
                var subNw   = subNetWeight.Sum(c => c.CartonQuantity * c.NetWeight);
                var subNnw  = subNetNetWeight.Sum(c => c.CartonQuantity * c.NetNetWeight);

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 11,
                    Phrase  = new Phrase($"      - Sub Ctns = {subCtns}           - Sub G.W. = {String.Format("{0:0.00}", subGw)} Kgs           - Sub N.W. = {String.Format("{0:0.00}", subNw)} Kgs            - Sub N.N.W. = {String.Format("{0:0.00}", subNnw)} Kgs", normal_font)
                });

                new PdfPCell(tableDetail);
                tableDetail.ExtendLastRow = false;
                //tableDetail.KeepTogether = true;
                tableDetail.WidthPercentage = 95f;
                //tableDetail.HeaderRows = 3;
                document.Add(tableDetail);
            }

            #region GrandTotal

            PdfPTable tableGrandTotal = new PdfPTable(2);
            tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 5f });
            PdfPCell cellHeaderLine = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("")
            };

            tableGrandTotal.AddCell(cellHeaderLine);
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.BOTTOM_BORDER,
                Padding = 5,
                Phrase  = new Phrase("GRAND TOTAL ...................................................................................................................................................................................", normal_font)
            });
            var grandTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border              = Rectangle.BOTTOM_BORDER,
                Padding             = 5,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase              = new Phrase(grandTotalResult, normal_font)
            });
            tableGrandTotal.AddCell(cellHeaderLine);
            var totalCtns  = cartons.Sum(c => c.CartonQuantity);
            var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 2,
                Padding = 5,
                Phrase  = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]", normal_font)
            });

            new PdfPCell(tableGrandTotal);
            tableGrandTotal.ExtendLastRow   = false;
            tableGrandTotal.WidthPercentage = 95f;
            tableGrandTotal.SpacingAfter    = 5f;
            document.Add(tableGrandTotal);

            #endregion

            #region Mark

            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 1f, 1f });

            PdfPCell cellShippingMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font);
            chunkShippingMark.SetUnderline(0.5f, -1);
            Phrase phraseShippingMark = new Phrase();
            phraseShippingMark.Add(chunkShippingMark);
            phraseShippingMark.Add(new Chunk("     :", normal_font));
            cellShippingMark.AddElement(phraseShippingMark);
            cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font));
            tableMark.AddCell(cellShippingMark);

            PdfPCell cellSideMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font);
            chunkSideMark.SetUnderline(0.5f, -1);
            Phrase phraseSideMark = new Phrase();
            phraseSideMark.Add(chunkSideMark);
            phraseSideMark.Add(new Chunk("     :", normal_font));
            cellSideMark.AddElement(phraseSideMark);
            cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font)
            {
            });
            tableMark.AddCell(cellSideMark);

            byte[] shippingMarkImage;

            if (!String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
                {
                    shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));

                    Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);
                    if (shipMarkImage.Width > 60)
                    {
                        float percentage = 0.0f;
                        percentage = 100 / shipMarkImage.Width;
                        shipMarkImage.ScalePercent(percentage * 100);
                        PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
                        shipMarkImageCell.Border = Rectangle.NO_BORDER;
                        tableMark.AddCell(shipMarkImageCell);
                    }
                }
            }

            byte[] sideMarkImage;

            if (!String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
                {
                    sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                    Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);
                    if (_sideMarkImage.Width > 60)
                    {
                        float percentage = 0.0f;
                        percentage = 100 / _sideMarkImage.Width;
                        _sideMarkImage.ScalePercent(percentage * 100);
                    }

                    PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
                    _sideMarkImageCell.Border = Rectangle.NO_BORDER;
                    tableMark.AddCell(_sideMarkImageCell);
                }
            }

            new PdfPCell(tableMark);
            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 5f;
            document.Add(tableMark);

            #endregion

            #region Measurement

            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.GrossWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.NettWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.NetNetWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm = 0;
            foreach (var measurement in viewModel.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);

            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            var paddingRight = SIZES_COUNT > 11 ? 400 : 200;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = paddingRight
            });

            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase("REMARK :", normal_font_underlined)
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase(viewModel.Remark, normal_font)
            });
            byte[] remarkImage;

            if (!String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
                {
                    remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));

                    Image images = Image.GetInstance(imgb: remarkImage);

                    if (images.Width > 60)
                    {
                        float percentage = 0.0f;
                        percentage = 100 / images.Width;
                        images.ScalePercent(percentage * 100);
                    }

                    PdfPCell imageCell = new PdfPCell(images);
                    imageCell.Border  = Rectangle.NO_BORDER;
                    imageCell.Colspan = 3;
                    tableMeasurement.AddCell(imageCell);
                }
            }

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);
            //document.Add(images);

            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#7
0
        public MemoryStream GeneratePdfTemplate(GarmentShippingInvoiceViewModel viewModel, Buyer buyer, BankAccount bank, GarmentPackingListViewModel pl, int timeoffset)
        {
            const int MARGIN = 20;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            //Font body_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(PageSize.A4, MARGIN, MARGIN, 290, 150);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentShippingInvoicePDFTemplatePageEvent(viewModel, timeoffset);

            document.Open();

            #region LC
            PdfPTable tableLC = new PdfPTable(3);
            tableLC.SetWidths(new float[] { 2f, 0.1f, 6f });

            if (pl.PaymentTerm == "LC")
            {
                PdfPCell cellLCContentLeft = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentLeft.AddElement(new Phrase("LETTER OF CREDIT NUMBER ", normal_font));
                cellLCContentLeft.AddElement(new Phrase("LC DATE ", normal_font));
                cellLCContentLeft.AddElement(new Phrase("ISSUED BY ", normal_font));
                tableLC.AddCell(cellLCContentLeft);

                PdfPCell cellLCContentCenter = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                tableLC.AddCell(cellLCContentCenter);

                PdfPCell cellLCContentRight = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentRight.AddElement(new Phrase(viewModel.LCNo, normal_font));
                cellLCContentRight.AddElement(new Phrase(pl.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font));
                cellLCContentRight.AddElement(new Phrase(viewModel.IssuedBy, normal_font));
                tableLC.AddCell(cellLCContentRight);
            }
            else
            {
                PdfPCell cellLCContentLeft = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentLeft.AddElement(new Phrase("PAYMENT TERM ", normal_font));
                tableLC.AddCell(cellLCContentLeft);

                PdfPCell cellLCContentCenter = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                tableLC.AddCell(cellLCContentCenter);

                PdfPCell cellLCContentRight = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentRight.AddElement(new Phrase("TT PAYMENT", normal_font));
                tableLC.AddCell(cellLCContentRight);
            }

            PdfPCell cellLC = new PdfPCell(tableLC);
            tableLC.ExtendLastRow = false;
            tableLC.SpacingAfter  = 4f;
            document.Add(tableLC);
            #endregion

            #region Body Table

            PdfPTable bodyTable       = new PdfPTable(8);
            float[]   bodyTableWidths = new float[] { 1.8f, 1.8f, 1.8f, 1.8f, 0.8f, 0.5f, 1f, 1.3f };
            bodyTable.SetWidths(bodyTableWidths);
            bodyTable.WidthPercentage = 100;

            #region Set Body Table Header
            PdfPCell bodyTableHeader = new PdfPCell();// { FixedHeight = 30 };
            //PdfPCell table1RightCellHeader = new PdfPCell() { FixedHeight = 20, Colspan = 4 };

            bodyTableHeader.Phrase = new Phrase("DESCRIPTION", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.SetLeading(0, 1.3f);
            bodyTableHeader.Rowspan = 2;
            bodyTableHeader.Colspan = 4;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("QUANTITY", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Colspan             = 2;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("UNIT PRICE\n" + viewModel.CPrice + " IN USD", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            //bodyTableHeader.Rowspan = 1;
            bodyTableHeader.Colspan = 1;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("TOTAL PRICE\n" + viewModel.CPrice + " IN USD", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableHeader);

            //bodyTableHeader.Phrase = new Phrase("", normal_font);
            //bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableHeader.VerticalAlignment = Element.ALIGN_CENTER;
            ////bodyTableHeader.Rowspan = 2;
            //bodyTableHeader.Colspan = 4;
            //bodyTable.AddCell(bodyTableHeader);

            //bodyTableHeader.Phrase = new Phrase("", normal_font);
            //bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableHeader.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableHeader.Colspan = 2;
            //bodyTable.AddCell(bodyTableHeader);

            //bodyTableHeader.Phrase = new Phrase(viewModel.CPrice + " IN USD", normal_font);
            //bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableHeader.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableHeader.Colspan = 2;
            //bodyTable.AddCell(bodyTableHeader);
            #endregion

            #region Set Body Table Value
            PdfPCell bodyTableCellRightBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.RIGHT_BORDER
            };
            PdfPCell bodyTableCellLeftBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.LEFT_BORDER
            };
            PdfPCell bodyTableCellCenterBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER
            };

            bodyTableCellLeftBorder.Phrase = new Phrase($"{viewModel.Description}", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.SetLeading(0, 1.3f);
            bodyTableCellLeftBorder.Colspan = 4;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 2;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.SetLeading(0, 1.3f);
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.SetLeading(0, 1.3f);
            bodyTable.AddCell(bodyTableCellRightBorder);

            ////SPACE
            //bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 4;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 2;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellCenterBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellCenterBorder);

            //bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellRightBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellRightBorder);

            ////

            //bodyTableCellLeftBorder.Phrase = new Phrase(".", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 4;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 2;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellCenterBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellCenterBorder);

            //bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellRightBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellRightBorder);

            //SPACE
            //bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 4;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellLeftBorder.Colspan = 2;
            //bodyTable.AddCell(bodyTableCellLeftBorder);

            //bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellCenterBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellCenterBorder);

            //bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            //bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            //bodyTableCellRightBorder.VerticalAlignment = Element.ALIGN_CENTER;
            //bodyTable.AddCell(bodyTableCellRightBorder);

            //
            bodyTableCellLeftBorder.Phrase = new Phrase($"{viewModel.Remark}", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 2;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);

            //SPACE
            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 2;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);


            decimal totalAmount   = 0;
            double  totalQuantity = 0;

            Dictionary <string, double> total = new Dictionary <string, double>();

            foreach (var item in viewModel.Items.OrderBy(o => o.ComodityDesc))
            {
                totalAmount   += item.Amount;
                totalQuantity += item.Quantity;

                bodyTableCellLeftBorder.Phrase = new Phrase($"{item.ComodityDesc}", body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.Colspan             = 1;
                bodyTableCellLeftBorder.Border = Rectangle.LEFT_BORDER;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellLeftBorder.Phrase = new Phrase($"{item.Desc2}", body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.Border  = Rectangle.NO_BORDER;
                bodyTableCellLeftBorder.Colspan = 1;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellLeftBorder.Phrase = new Phrase($"{item.Desc3}", body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.Border  = Rectangle.NO_BORDER;
                bodyTableCellLeftBorder.Colspan = 1;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellLeftBorder.Phrase = new Phrase($"{item.Desc4}", body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.Border  = Rectangle.RIGHT_BORDER;
                bodyTableCellLeftBorder.Colspan = 1;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellLeftBorder.Phrase = new Phrase(string.Format("{0:n0}", item.Quantity), body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.BorderColorRight    = BaseColor.White;
                bodyTableCellLeftBorder.Border = Rectangle.LEFT_BORDER;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Uom.Unit, body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellRightBorder.BorderColorLeft     = BaseColor.White;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Price != 0 ? string.Format("{0:n4}", item.Price) : "", body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Amount != 0 ? string.Format("{0:n2}", item.Amount) : "", body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                if (total.ContainsKey(item.Uom.Unit))
                {
                    total[item.Uom.Unit] += item.Quantity;
                }
                else
                {
                    total.Add(item.Uom.Unit, item.Quantity);
                }
            }


            PdfPCell bodyTableCellFooter = new PdfPCell()
            {
                FixedHeight = 20, Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER
            };

            bodyTableCellFooter.Phrase = new Phrase("TOTAL  ", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellFooter);

            var val1    = total.Select(x => String.Format("{0:n0}", x.Value));
            var result1 = String.Join("\n", val1);

            var key1    = total.Select(x => String.Format("{0}", x.Key));
            var result2 = String.Join("\n", key1);

            bodyTableCellFooter.Phrase = new Phrase($"{result1}", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Colspan             = 1;
            bodyTableCellFooter.Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);


            bodyTableCellFooter.Phrase = new Phrase($"{result2}", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Border = Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase("", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase(totalAmount != 0 ? string.Format("{0:n2}", totalAmount) : "", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Border = Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);

            #endregion
            bodyTable.HeaderRows = 1;
            document.Add(bodyTable);
            #endregion


            string amountToText = NumberToTextEN.toWords((double)totalAmount);
            document.Add(new Paragraph("SAY   : US DOLLARS " + amountToText.ToUpper() + " ONLY ///", normal_font));
            document.Add(new Paragraph("\n", normal_font));

            if (bank != null)
            {
                document.Add(new Paragraph("PLEASE TT THE ABOVE PAYMENT TO OUR CORRESPONDENCE BANK AS FOLLOW   : ", normal_font));

                document.Add(new Paragraph(bank.bankName, normal_font));
                document.Add(new Paragraph(bank.bankAddress, normal_font));
                document.Add(new Paragraph("ACC NO. " + bank.AccountNumber + $"({bank.Currency.Code})", normal_font));
                document.Add(new Paragraph("A/N. PT. DAN LIRIS", normal_font));
                document.Add(new Paragraph("SWIFT CODE : " + bank.swiftCode, normal_font));
                document.Add(new Paragraph("PURPOSE CODE : 1011", normal_font));
                document.Add(new Paragraph("\n", normal_font));
            }


            #region MARK
            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 2f, 4f });
            tableMark.WidthPercentage = 100;

            PdfPCell cellMarkContent = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellMarkContent.AddElement(new Phrase("SHIPPING MARKS :", normal_font_underlined));
            cellMarkContent.AddElement(new Phrase(pl.ShippingMark, normal_font));
            tableMark.AddCell(cellMarkContent);

            PdfPCell cellMarkContentR = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellMarkContentR.AddElement(new Phrase("SIDE MARKS :", normal_font_underlined));
            cellMarkContentR.AddElement(new Phrase(pl.SideMark, normal_font));
            tableMark.AddCell(cellMarkContentR);

            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 10f;
            document.Add(tableMark);

            //
            PdfPTable tableMark1 = new PdfPTable(2);
            tableMark1.SetWidths(new float[] { 2f, 4f });
            tableMark1.WidthPercentage = 100;

            var    noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z";
            byte[] shippingMarkImage;
            if (String.IsNullOrEmpty(pl.ShippingMarkImageFile))
            {
                pl.ShippingMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(pl.ShippingMarkImageFile)))
            {
                shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(pl.ShippingMarkImageFile));
                Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);

                if (shipMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / shipMarkImage.Width;
                    shipMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
                shipMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark1.AddCell(shipMarkImageCell);
            }

            byte[] sideMarkImage;

            if (String.IsNullOrEmpty(pl.SideMarkImageFile))
            {
                pl.SideMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(pl.SideMarkImageFile)))
            {
                sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(pl.SideMarkImageFile));
                Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);

                if (_sideMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / _sideMarkImage.Width;
                    _sideMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
                _sideMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark1.AddCell(_sideMarkImageCell);
            }

            new PdfPCell(tableMark1);
            tableMark1.ExtendLastRow = false;
            tableMark1.SpacingAfter  = 5f;
            document.Add(tableMark1);

            //

            #endregion

            #region Weight
            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(pl.GrossWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(pl.NettWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm = 0;
            foreach (var measurement in pl.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(pl.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);

            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            var paddingRight = 200;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = paddingRight
            });

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);
            #endregion

            //document.Add(new Paragraph("REMARK : ", normal_font_underlined));
            //document.Add(new Paragraph(pl.Remark, normal_font));

            //document.Add(new Paragraph("\n", normal_font));
            //document.Add(new Paragraph("\n", normal_font));
            //document.Add(new Paragraph("\n", normal_font));
            //document.Add(new Paragraph("\n", normal_font));
            //document.Add(new Paragraph("\n", normal_font));
            //
            #region REMARK
            PdfPTable tableRemark = new PdfPTable(1);
            tableRemark.SetWidths(new float[] { 6f });
            tableRemark.WidthPercentage = 100;

            PdfPCell cellRemarkContent = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellRemarkContent.AddElement(new Phrase("REMARK :", normal_font_underlined));
            cellRemarkContent.AddElement(new Phrase(pl.Remark, normal_font));
            tableRemark.AddCell(cellRemarkContent);

            tableRemark.ExtendLastRow = false;
            tableRemark.SpacingAfter  = 10f;
            document.Add(tableRemark);

            //
            PdfPTable tableRemark2 = new PdfPTable(1);
            tableRemark2.SetWidths(new float[] { 6f });
            tableRemark2.WidthPercentage = 100;

            byte[] shippingRemarkImage;

            if (String.IsNullOrEmpty(pl.RemarkImageFile))
            {
                pl.RemarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(pl.RemarkImageFile)))
            {
                shippingRemarkImage = Convert.FromBase64String(Base64.GetBase64File(pl.RemarkImageFile));
                Image shipRemarkImage = Image.GetInstance(imgb: shippingRemarkImage);

                if (shipRemarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / shipRemarkImage.Width;
                    shipRemarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell shipRemarkImageCell = new PdfPCell(shipRemarkImage);
                shipRemarkImageCell.Border  = Rectangle.NO_BORDER;
                shipRemarkImageCell.Colspan = 3;
                tableRemark2.AddCell(shipRemarkImageCell);
            }

            new PdfPCell(tableRemark2);
            tableRemark2.ExtendLastRow = false;
            tableRemark2.SpacingAfter  = 5f;
            document.Add(tableRemark2);
            //
            #endregion

            //
            //Paragraph sign = new Paragraph("( MRS. ADRIYANA DAMAYANTI )", normal_font_underlined);
            //sign.Alignment = Element.ALIGN_RIGHT;
            //Paragraph author = new Paragraph("AUTHORIZED SIGNATURE  ", normal_font);
            //author.Alignment = Element.ALIGN_RIGHT;

            //document.Add(sign);
            //document.Add(author);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        public MemoryStream GeneratePdfTemplate(FinishingPrintingSalesContractViewModel viewModel, int timeoffset)
        {
            Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18);
            Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);
            Font bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);

            Document     document = new Document(PageSize.A4, 40, 40, 140, 40);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();


            #region customViewModel

            var           uom        = "";
            var           uom1       = "";
            List <string> details    = new List <string>();
            double        convertion = 0;

            if (viewModel.UOM.Unit.ToLower() == "yds")
            {
                uom  = "YARDS";
                uom1 = "YARD";
            }
            else if (viewModel.UOM.Unit.ToLower() == "mtr")
            {
                uom  = "METRES";
                uom1 = "METRE";
            }
            else
            {
                uom  = viewModel.UOM.Unit;
                uom1 = viewModel.UOM.Unit;
            }


            string QuantityToText = NumberToTextEN.toWords(viewModel.OrderQuantity);
            double amount         = (viewModel.Amount);
            string AmountToText   = NumberToTextEN.toWords(amount);

            //var detailprice = viewModel.AccountBank.Currency.Symbol + " " + string.Format("{0:n2}", viewModel.Price) + " / KG";

            var appx = "";
            var date = viewModel.DeliverySchedule.Value.Day;
            if (date >= 1 && date <= 10)
            {
                appx = "EARLY";
            }
            else if (date >= 11 && date <= 20)
            {
                appx = "MIDDLE";
            }
            else if (date >= 21 && date <= 31)
            {
                appx = "END";
            }

            List <string> newDetail = new List <string>();

            foreach (var i in viewModel.Details)
            {
                var ppn = "";
                if (viewModel.UseIncomeTax)
                {
                    if (i.UseIncomeTax)
                    {
                        ppn = "INCLUDING PPN 10%";
                    }
                    else
                    {
                        ppn = "EXCLUDING PPN";
                    }
                }
                else
                {
                    ppn = "TANPA PPN";
                }
                var nominal = string.Format("{0:n2}", i.Price);

                if (i.Currency.Code.ToLower() == "usd")
                {
                    nominal = string.Format("{0:n2}", i.Price);
                }

                details.Add(i.Color + " " + i.Currency.Symbol + " " + nominal + " / " + uom1 + " ");
            }

            #endregion

            #region Header

            string    codeNoString = "FM-PJ-00-03-004";
            Paragraph codeNo       = new Paragraph(codeNoString, bold_font)
            {
                Alignment = Element.ALIGN_RIGHT
            };
            document.Add(codeNo);

            string    titleString = "SALES CONTRACT";
            Paragraph title       = new Paragraph(titleString, bold_font)
            {
                Alignment = Element.ALIGN_CENTER
            };
            title.SpacingAfter = 10f;
            document.Add(title);
            bold_font.SetStyle(Font.NORMAL);

            #endregion

            #region Identity

            PdfPTable tableIdentity = new PdfPTable(3);
            tableIdentity.SetWidths(new float[] { 0.5f, 4.5f, 2.5f });
            PdfPCell cellIdentityContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellIdentityContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase($"Sukoharjo, {viewModel.CreatedUtc.AddHours(timeoffset).ToString("dd MMMM yyyy", new CultureInfo("en-US"))}", normal_font);
            tableIdentity.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            tableIdentity.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentity.AddCell(cellIdentityContentRight);
            PdfPCell cellIdentity = new PdfPCell(tableIdentity); // dont remove
            tableIdentity.ExtendLastRow = false;
            tableIdentity.SpacingAfter  = 10f;
            document.Add(tableIdentity);

            PdfPTable tableIdentityOpeningLetter = new PdfPTable(3);
            cellIdentityContentLeft.Phrase = new Phrase("MESSRS,", normal_font);
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Name, normal_font);
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Address, normal_font);
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.City, normal_font);
            tableIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            cellIdentityContentRight.Phrase = new Phrase("");
            tableIdentityOpeningLetter.AddCell(cellIdentityContentRight);
            PdfPCell cellIdentityOpeningLetter = new PdfPCell(tableIdentityOpeningLetter); // dont remove
            tableIdentityOpeningLetter.ExtendLastRow = false;
            tableIdentityOpeningLetter.SpacingAfter  = 10f;
            document.Add(tableIdentityOpeningLetter);

            #endregion

            #region HeaderParagraphString
            string    HeaderParagraphString = "On behalf of :";
            Paragraph HeaderParagraph       = new Paragraph(HeaderParagraphString, normal_font)
            {
                Alignment = Element.ALIGN_LEFT
            };
            document.Add(HeaderParagraph);

            string    firstParagraphString = "P.T. DAN LIRIS KELURAHAN BANARAN, KECAMATAN GROGOL SUKOHARJO - INDONESIA, we confrm the order under the following terms and conditions as mentioned below: ";
            Paragraph firstParagraph       = new Paragraph(firstParagraphString, normal_font)
            {
                Alignment = Element.ALIGN_JUSTIFIED
            };
            firstParagraph.SpacingAfter = 10f;
            document.Add(firstParagraph);
            #endregion

            #region body
            PdfPTable tableBody = new PdfPTable(2);
            tableBody.SetWidths(new float[] { 0.75f, 2f });
            PdfPCell bodyContentCenter = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell bodyContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell bodyContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            bodyContentLeft.Phrase = new Phrase("Contract Number", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.SalesContractNo, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Comodity", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.Material.Name + " " + viewModel.MaterialConstruction.Name, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("  " + viewModel.YarnMaterial.Name + " WIDTH: " + viewModel.MaterialWidth, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("  " + viewModel.CommodityDescription, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Quality", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.Quality.Name, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Quantity", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.OrderQuantity + " ( " + QuantityToText + " ) " + uom, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Price & Payment", normal_font);
            tableBody.AddCell(bodyContentLeft);

            int index = 0;

            foreach (var detail in details)
            {
                index++;
                if (index == 1)
                {
                    bodyContentLeft.Phrase = new Phrase(": " + detail, normal_font);
                    tableBody.AddCell(bodyContentLeft);
                }
                else
                {
                    bodyContentLeft.Phrase = new Phrase(" ", normal_font);
                    tableBody.AddCell(bodyContentLeft);
                    bodyContentLeft.Phrase = new Phrase("  " + detail, normal_font);
                    tableBody.AddCell(bodyContentLeft);
                }
            }
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("  " + viewModel.TermOfShipment, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("  " + viewModel.TermOfPayment.Name, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Amount", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.AccountBank.AccountCurrencyCode + " " + string.Format("{0:n2}", amount) + " ( " + AmountToText + " " + viewModel.AccountBank.Currency.Description.ToUpper() + " ) (APPROXIMATELLY)", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Shipment", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + appx + " " + (viewModel.DeliverySchedule.Value.AddHours(timeoffset).ToString("MMMM yyyy", new CultureInfo("en-US"))).ToUpper(), normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("  " + viewModel.ShipmentDescription, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Destination", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.DeliveredTo, normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("Packing", normal_font);
            tableBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(": " + viewModel.Packing, normal_font);
            tableBody.AddCell(bodyContentLeft);
            PdfPCell cellBody = new PdfPCell(tableBody); // dont remove
            tableBody.ExtendLastRow = false;
            document.Add(tableBody);

            PdfPTable conditionListBody = new PdfPTable(3);
            conditionListBody.SetWidths(new float[] { 0.4f, 0.025f, 1f });

            bodyContentLeft.Phrase = new Phrase("Condition", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("-", normal_font);
            conditionListBody.AddCell(cellIdentityContentLeft);
            bodyContentLeft.Phrase = new Phrase("THIS CONTRACT IS IRREVOCABLE UNLESS AGREED UPON BY THE TWO PARTIES, THE BUYER AND SELLER.", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase("", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("-", normal_font);
            conditionListBody.AddCell(cellIdentityContentLeft);
            bodyContentLeft.Phrase = new Phrase("+/- " + viewModel.ShippingQuantityTolerance + " % FROM QUANTITY ORDER SHOULD BE ACCEPTABLE.", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("-", normal_font);
            conditionListBody.AddCell(cellIdentityContentLeft);
            bodyContentLeft.Phrase = new Phrase("LOCAL CONTAINER DELIVERY CHARGES AT DESTINATION FOR BUYER'S ACCOUNT.", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("- ", normal_font);
            conditionListBody.AddCell(cellIdentityContentLeft);
            bodyContentLeft.Phrase = new Phrase(viewModel.Condition, normal_font);
            conditionListBody.AddCell(bodyContentLeft);
            bodyContentRight.Phrase = new Phrase("");
            conditionListBody.AddCell(bodyContentRight);
            PdfPCell cellConditionList = new PdfPCell(conditionListBody); // dont remove
            conditionListBody.ExtendLastRow = false;
            conditionListBody.SpacingAfter  = 10f;
            document.Add(conditionListBody);

            #endregion

            #region signature
            PdfPTable signature = new PdfPTable(2);
            signature.SetWidths(new float[] { 1f, 1f });
            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            signature.SetWidths(new float[] { 1f, 1f });
            cell_signature.Phrase = new Phrase("Accepted and confrmed :", normal_font);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("PT DANLIRIS", normal_font);
            signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("", normal_font);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            signature.AddCell(cell_signature);

            string signatureArea = string.Empty;
            for (int i = 0; i < 5; i++)
            {
                signatureArea += Environment.NewLine;
            }

            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            signature.AddCell(cell_signature);
            signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("(...........................)", normal_font);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("( ROBBY SAPUTRO )", normal_font);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Authorized signature", normal_font);
            signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Marketing Textile", normal_font);
            signature.AddCell(cell_signature);
            cellIdentityContentRight.Phrase = new Phrase("");
            signature.AddCell(cellIdentityContentRight);

            PdfPCell signatureCell = new PdfPCell(signature); // dont remove
            signature.ExtendLastRow = false;
            signature.SpacingAfter  = 10f;
            document.Add(signature);
            #endregion

            #region ConditionPage
            document.NewPage();

            string    ConditionString = "Remark";
            Paragraph ConditionName   = new Paragraph(ConditionString, header_font)
            {
                Alignment = Element.ALIGN_LEFT
            };
            document.Add(ConditionName);

            string   bulletListSymbol   = "\u2022";
            PdfPCell bodyContentJustify = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_JUSTIFIED
            };

            PdfPTable conditionList = new PdfPTable(2);
            conditionList.SetWidths(new float[] { 0.01f, 1f });

            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("All instructions regarding sticker, shipping marks etc. to be received 1 (one) month prior to shipment.", normal_font);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("Benefciary :  P.T. DAN LIRIS KELURAHAN BANARAN, KECAMATAN GROGOL SUKOHARJO - INDONESIA  (Phone No. 0271 - 740888 / 714400). ", normal_font);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("Payment Transferred to: ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("PAYMENT TO BE TRANSFERRED TO BANK : " + viewModel.AccountBank.BankName, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(viewModel.AccountBank.BankAddress, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("ACCOUNT NAME : " + viewModel.AccountBank.AccountName, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("ACCOUNT NO : " + viewModel.AccountBank.AccountNumber, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase("SWIFT CODE : " + viewModel.AccountBank.SwiftCode, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("Payment 30% TT in advance + 70% TT after receipt copies of shipping document to be negotiable with BANK PT Bank Unit Test.", normal_font);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("Please find enclosed some Indonesia Banking Regulations.", normal_font);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(bulletListSymbol, normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            bodyContentJustify.Phrase = new Phrase("If you find anything not order, please let us know immediately.", normal_font);
            conditionList.AddCell(bodyContentJustify);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
            conditionList.AddCell(cellIdentityContentLeft);
            PdfPCell conditionListData = new PdfPCell(conditionList); // dont remove
            conditionList.ExtendLastRow = false;
            document.Add(conditionList);
            #endregion

            #region agentTemplate
            if (viewModel.Agent.Id != 0)
            {
                document.NewPage();

                #region Identity
                PdfPTable agentIdentity = new PdfPTable(3);
                agentIdentity.SetWidths(new float[] { 0.5f, 4.5f, 2.5f });
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase($"Sukoharjo, {viewModel.CreatedUtc.AddHours(timeoffset).ToString("dd MMMM yyyy", new CultureInfo("en-US"))}", normal_font);
                agentIdentity.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font);
                agentIdentity.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentity.AddCell(cellIdentityContentRight);
                PdfPCell agentCellIdentity = new PdfPCell(agentIdentity); // dont remove
                agentIdentity.ExtendLastRow = false;
                agentIdentity.SpacingAfter  = 10f;
                document.Add(agentIdentity);

                PdfPTable agentIdentityOpeningLetter = new PdfPTable(3);
                agentIdentityOpeningLetter.SetWidths(new float[] { 2f, 4.5f, 2.5f });
                cellIdentityContentLeft.Phrase = new Phrase("MESSRS,", normal_font);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Name, normal_font);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Address, normal_font);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Country, normal_font);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentLeft.Phrase = new Phrase(viewModel.Buyer.Contact, normal_font);
                agentIdentityOpeningLetter.AddCell(cellIdentityContentLeft);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetter.AddCell(cellIdentityContentRight);
                PdfPCell agentCellIdentityOpeningLetter = new PdfPCell(agentIdentityOpeningLetter); // dont remove
                agentIdentityOpeningLetter.ExtendLastRow = false;
                agentIdentityOpeningLetter.SpacingAfter  = 10f;
                document.Add(agentIdentityOpeningLetter);


                PdfPTable agentIdentityOpeningLetterHeader = new PdfPTable(1);
                bodyContentCenter.Phrase = new Phrase("COMMISSION AGREEMENT NO: " + viewModel.DispositionNumber, bold_font);
                agentIdentityOpeningLetterHeader.AddCell(bodyContentCenter);
                bodyContentCenter.Phrase = new Phrase("FOR SALES CONTRACT NO: " + viewModel.SalesContractNo, bold_font);
                agentIdentityOpeningLetterHeader.AddCell(bodyContentCenter);
                cellIdentityContentRight.Phrase = new Phrase("");
                agentIdentityOpeningLetterHeader.AddCell(cellIdentityContentRight);
                PdfPCell agentIdentityOpeningLetterHeaderCell = new PdfPCell(agentIdentityOpeningLetterHeader); // dont remove
                agentIdentityOpeningLetterHeader.ExtendLastRow = false;
                agentIdentityOpeningLetterHeader.SpacingAfter  = 10f;
                document.Add(agentIdentityOpeningLetterHeader);

                #endregion

                #region agentBody
                string    agentFirstParagraphString = "This is to confirm that your order for " + viewModel.Buyer.Name + " concerning " + viewModel.OrderQuantity + " ( " + QuantityToText + ") " + uom + " of " + viewModel.Commodity.Name + viewModel.CommodityDescription;
                Paragraph agentFirstParagraph       = new Paragraph(agentFirstParagraphString, normal_font)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                document.Add(agentFirstParagraph);
                //string agentFirstParagraphStringDescription = viewModel.Commodity.Name + viewModel.CommodityDescription;
                //Paragraph agentFirstParagraphDescription = new Paragraph(agentFirstParagraphStringDescription, normal_font) { Alignment = Element.ALIGN_JUSTIFIED };
                //document.Add(agentFirstParagraphDescription);
                string    agentFirstParagraphStringContruction = "CONSTRUCTION: " + viewModel.Material.Name + viewModel.MaterialConstruction.Name + " / " + viewModel.YarnMaterial.Name + " WIDTH: " + viewModel.MaterialWidth;
                Paragraph agentFirstParagraphContruction       = new Paragraph(agentFirstParagraphStringContruction, normal_font)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentFirstParagraphContruction.SpacingAfter = 10f;
                document.Add(agentFirstParagraphContruction);
                string    agentSecondParagraphString = "Placed with us, P.T. DAN LIRIS - SOLO INDONESIA, is inclusive of " + viewModel.Commission + " sales commission each " + uom1 + " on " + viewModel.TermOfShipment + " value, payable to you upon final negotiation and clearance of " + viewModel.TermOfPayment.Name + '.';
                Paragraph agentSecondParagraph       = new Paragraph(agentSecondParagraphString, normal_font)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentSecondParagraph.SpacingAfter = 10f;
                document.Add(agentSecondParagraph);
                string    agentThirdParagraphString = "Kindly acknowledge receipt by undersigning this Commission Agreement letter and returned one copy to us after having been confirmed and signed by you.";
                Paragraph agentThirdParagraph       = new Paragraph(agentThirdParagraphString, normal_font)
                {
                    Alignment = Element.ALIGN_JUSTIFIED
                };
                agentThirdParagraph.SpacingAfter = 30f;
                document.Add(agentThirdParagraph);
                #endregion

                #region signature
                PdfPTable signatureAgent = new PdfPTable(2);
                signatureAgent.SetWidths(new float[] { 1f, 1f });
                signatureAgent.SetWidths(new float[] { 1f, 1f });
                cell_signature.Phrase = new Phrase("Accepted and confrmed :", normal_font);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("PT DANLIRIS", normal_font);
                signatureAgent.AddCell(cell_signature);

                cell_signature.Phrase = new Phrase("", normal_font);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("", normal_font);
                signatureAgent.AddCell(cell_signature);

                string signatureAreaAgent = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    signatureAreaAgent += Environment.NewLine;
                }

                cell_signature.Phrase = new Phrase(signatureArea, normal_font);
                signatureAgent.AddCell(cell_signature);
                signatureAgent.AddCell(cell_signature);

                cell_signature.Phrase = new Phrase("(...........................)", normal_font);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("( ROBBY SAPUTRO )", normal_font);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("Authorized signature", normal_font);
                signatureAgent.AddCell(cell_signature);
                cell_signature.Phrase = new Phrase("Marketing Textile", normal_font);
                signatureAgent.AddCell(cell_signature);
                cellIdentityContentRight.Phrase = new Phrase("");
                signatureAgent.AddCell(cellIdentityContentRight);

                PdfPCell signatureCellAgent = new PdfPCell(signatureAgent); // dont remove
                signatureAgent.ExtendLastRow = false;
                signatureAgent.SpacingAfter  = 10f;
                document.Add(signatureAgent);
            }
            #endregion

            #endregion



            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#9
0
        public MemoryStream GeneratePdfTemplate(GarmentShippingCreditNoteViewModel viewModel)
        {
            Font normal_font     = FontFactory.GetFont(BaseFont.COURIER, 10, Font.NORMAL);
            Font underlined_font = FontFactory.GetFont(BaseFont.COURIER, 10, Font.UNDERLINE);
            Font big_font        = FontFactory.GetFont(BaseFont.COURIER, 16, Font.BOLD);

            Document     document = new Document(PageSize.A4, 20, 20, 20, 20);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            var chunkHeader = new Chunk("PT. DAN LIRIS", big_font);

            chunkHeader.SetHorizontalScaling(1.5f);
            document.Add(new Paragraph(chunkHeader));

            PdfPTable tableHeadOffice = new PdfPTable(2);

            tableHeadOffice.SetWidths(new float[] { 1.5f, 6.5f });

            PdfPCell cellHeadOffice = new PdfPCell {
                Border = Rectangle.NO_BORDER
            };

            cellHeadOffice.Phrase = new Phrase("Head Office : ", normal_font);
            tableHeadOffice.AddCell(cellHeadOffice);
            cellHeadOffice.Phrase = new Phrase("Jl. Merapi No. 23, Kel. Banaran Kec. Grogol Kab. Sukoharjo\nTelp.(0271)714400, Fax.(0271)735222\ne-Mail:", normal_font);
            cellHeadOffice.Phrase.Add(new Chunk("*****@*****.**", underlined_font));
            tableHeadOffice.AddCell(cellHeadOffice);
            Chunk chunkAddress = new Chunk("MESSRS :\n" + viewModel.buyer.Name + "\n" + viewModel.buyer.Address, normal_font);

            chunkAddress.SetHorizontalScaling(0.8f);
            Phrase phraseBuyerHeader = new Phrase(chunkAddress);

            //phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            //phraseBuyerHeader.Add(new Chunk("CREDIT NOTE", normal_font));

            phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            phraseBuyerHeader.Add(new Chunk("DATE : " + viewModel.date.GetValueOrDefault().ToString("MMMM dd, yyyy"), normal_font));

            tableHeadOffice.AddCell(new PdfPCell
            {
                Border      = Rectangle.NO_BORDER,
                Colspan     = 2,
                PaddingLeft = 10f,
                Phrase      = phraseBuyerHeader
            });

            new PdfPCell(tableHeadOffice);
            tableHeadOffice.ExtendLastRow = false;
            tableHeadOffice.SpacingAfter  = 5f;
            document.Add(tableHeadOffice);

            document.Add(new Paragraph("CREDIT NOTE", big_font)
            {
                Alignment = Element.ALIGN_CENTER, SpacingAfter = 5f
            });

            document.Add(new Paragraph(viewModel.noteNo, big_font)
            {
                Alignment = Element.ALIGN_RIGHT, SpacingAfter = 5f
            });

            PdfPTable tableItems = new PdfPTable(2);

            tableItems.SetWidths(new float[] { 3f, 1f });

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("D e s c r i p t i o n", normal_font)
            });
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("Amount", normal_font)
            });

            PdfPTable tableItemsContent = new PdfPTable(2);

            tableItemsContent.SetWidths(new float[] { 3f, 1f });

            foreach (var item in viewModel.items)
            {
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.NO_BORDER,
                    Phrase = new Phrase(item.description, normal_font)
                });
                Phrase phraseAmount = new Phrase();
                phraseAmount.Add(new Chunk("US$", normal_font));
                phraseAmount.Add(new Chunk(new VerticalPositionMark()));
                phraseAmount.Add(new Chunk(item.amount.ToString("n"), normal_font));
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.LEFT_BORDER,
                    Phrase = phraseAmount
                });
            }

            PdfPCell pdfPCellItemsContent = new PdfPCell
            {
                Colspan       = 2,
                Padding       = 0,
                Border        = Rectangle.NO_BORDER,
                MinimumHeight = 400
            };

            new PdfPCell(tableItemsContent);
            pdfPCellItemsContent.AddElement(tableItemsContent);
            tableItems.AddCell(pdfPCellItemsContent);

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                PaddingRight        = 10,
                Phrase = new Phrase("TOTAL", normal_font)
            });
            Phrase phraseTotalAmount = new Phrase();

            phraseTotalAmount.Add(new Chunk("US$", normal_font));
            phraseTotalAmount.Add(new Chunk(new VerticalPositionMark()));
            phraseTotalAmount.Add(new Chunk(viewModel.totalAmount.ToString("n"), normal_font));
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                Phrase = phraseTotalAmount
            });
            tableItems.AddCell(new PdfPCell
            {
                Colspan       = 2,
                PaddingBottom = 10f,
                Border        = Rectangle.NO_BORDER,
                Phrase        = new Phrase("SAY : US DOLLARS " + NumberToTextEN.toWords(viewModel.totalAmount).Trim().ToUpper() + " ONLY ///", normal_font)
            });

            tableItems.AddCell(new PdfPCell
            {
                Border       = Rectangle.NO_BORDER,
                PaddingRight = 10f,
                Phrase       = new Phrase(" ", normal_font)
            });
            Phrase phraseSign = new Phrase();

            phraseSign.Add(new Chunk("S.E. & O\n" + viewModel.date.GetValueOrDefault().ToString("MMMM dd, yyyy") + "\n\n\n\n", normal_font));
            Chunk chunkSignName = new Chunk("A M U M P U N I", normal_font);

            chunkSignName.SetUnderline(1, -1);
            phraseSign.Add(chunkSignName);
            phraseSign.Add(new Chunk("\nAUTHORIZED SIGNATURE", normal_font));
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = phraseSign
            });

            new PdfPCell(tableItems);
            tableItems.ExtendLastRow = false;
            tableItems.SpacingAfter  = 5f;
            document.Add(tableItems);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#10
0
        public MemoryStream GenerateExcelTemplate(GarmentPackingListViewModel viewModel, string fob, string cPrice)
        {
            //int maxSizesCount = viewModel.Items.Max(i => i.Details.Max(d => d.Sizes.GroupBy(g => g.Size.Id).Count()));
            int maxSizesCount = 0;
            var sizesMax      = new Dictionary <int, string>();

            foreach (var item in viewModel.Items)
            {
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizesMax[size.Size.Id] = size.Size.Size;
                    }
                }
            }
            maxSizesCount = sizesMax.Count;
            int SIZES_COUNT = maxSizesCount > 11 ? 20 : 11;

            var col       = GetColNameFromIndex(4 + SIZES_COUNT);
            var colCtns   = GetColNameFromIndex(SIZES_COUNT + 5);
            var colPcs    = GetColNameFromIndex(SIZES_COUNT + 6);
            var colQty    = GetColNameFromIndex(SIZES_COUNT + 7);
            var colSatuan = GetColNameFromIndex(SIZES_COUNT + 8);
            var colGw     = GetColNameFromIndex(SIZES_COUNT + 9);
            var colNw     = GetColNameFromIndex(SIZES_COUNT + 10);
            var colNnw    = GetColNameFromIndex(SIZES_COUNT + 11);



            DataTable result = new DataTable();

            ExcelPackage package = new ExcelPackage();
            var          sheet   = package.Workbook.Worksheets.Add("Report");


            sheet.Cells["A1"].Value    = "Invoice No.";
            sheet.Cells["A1:B1"].Merge = true;
            sheet.Column(1).Width      = 6;
            sheet.Column(2).Width      = 5;
            sheet.Column(3).Width      = 6;
            sheet.Column(3).Width      = 7;
            sheet.Cells["C1"].Value    = viewModel.InvoiceNo;
            sheet.Cells["C1:D1"].Merge = true;
            sheet.Cells[$"A1:{colNnw}1"].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Medium;
            sheet.Cells["E1"].Value                    = "Date : " + viewModel.Date.GetValueOrDefault().ToOffset(new TimeSpan(_identityProvider.TimezoneOffset, 0, 0)).ToString("MMM dd, yyyy.");
            sheet.Cells[$"E1:{col}1"].Merge            = true;
            sheet.Cells[$"{colCtns}1"].Value           = "Ref No. :  FM-00-SP-24-005 ";
            sheet.Cells[$"{colCtns}1"].Style.Font.Bold = true;
            sheet.Cells[$"{colCtns}1:{colNnw}1"].Merge = true;
            sheet.Cells["A3"].Value                    = cPrice;
            sheet.Cells["A3:C3"].Merge                 = true;
            sheet.Cells["D3"].Value                    = ":";
            sheet.Cells["E3"].Value                    = fob;
            sheet.Cells[$"E3:{colNnw}3"].Merge         = true;
            if (viewModel.PaymentTerm == "LC")
            {
                sheet.Cells["A4"].Value            = "LC No.";
                sheet.Cells["A4:C4"].Merge         = true;
                sheet.Cells["D4"].Value            = ":";
                sheet.Cells["E4"].Value            = viewModel.LCNo;
                sheet.Cells[$"E4:{colNnw}4"].Merge = true;
                sheet.Cells["A5"].Value            = "Tgl LC.";
                sheet.Cells["A5:C5"].Merge         = true;
                sheet.Cells["D5"].Value            = ":";
                sheet.Cells["E5"].Value            = viewModel.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(_identityProvider.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy");
                sheet.Cells[$"E5:{colNnw}5"].Merge = true;
                sheet.Cells["A6"].Value            = "ISSUED BY";
                sheet.Cells["A6:C6"].Merge         = true;
                sheet.Cells["D6"].Value            = ":";
                sheet.Cells["E6"].Value            = viewModel.IssuedBy;
                sheet.Cells[$"E6:{colNnw}6"].Merge = true;
            }
            else
            {
                sheet.Cells["A4"].Value            = "Payment Term";
                sheet.Cells["A4:C4"].Merge         = true;
                sheet.Cells["E4"].Value            = viewModel.PaymentTerm;
                sheet.Cells[$"E4:{colNnw}4"].Merge = true;
            }

            double        totalCtns       = 0;
            double        totalGw         = 0;
            double        totalNw         = 0;
            double        totalNnw        = 0;
            double        grandTotal      = 0;
            var           uom             = "";
            var           arrayGrandTotal = new Dictionary <String, double>();
            List <string> cartonNumbers   = new List <string>();

            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newItems2  = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items.OrderBy(a => a.RONo))
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Carton1).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Description         = a.Description,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            foreach (var item in newItems)
            {
                if (newItems2.Count == 0)
                {
                    newItems2.Add(item);
                }
                else
                {
                    if (newItems2.Last().OrderNo == item.OrderNo)
                    {
                        foreach (var d in item.Details.OrderBy(a => a.Carton1))
                        {
                            newItems2.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        newItems2.Add(item);
                    }
                }
            }

            var index = 8;
            var afterSubTotalIndex = 0;



            foreach (var item in newItems2)
            {
                var afterIndex = index + 1;
                var sizeIndex  = afterIndex + 1;
                var valueIndex = sizeIndex + 1;

                sheet.Cells[$"A{index}"].Value          = "DESCRIPTION OF GOODS";
                sheet.Cells[$"A{index}:C{index}"].Merge = true;
                sheet.Row(index).Height        = 25;
                sheet.Cells[$"D{index}"].Value = ":";
                sheet.Cells[$"E{index}"].Value = item.Description;
                sheet.Cells[$"E{index}:{colNnw}{index}"].Merge = true;

                sheet.Cells[$"A{afterIndex}"].Value = "CARTON NO.";
                sheet.Cells[$"A{afterIndex}:A{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"A{afterIndex}:A{afterIndex}"].Style.VerticalAlignment             = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"A{afterIndex}:A{afterIndex}"].Style.HorizontalAlignment           = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"A{afterIndex}:{colNnw}{afterIndex}"].Style.Border.Top.Style       = OfficeOpenXml.Style.ExcelBorderStyle.Double;
                sheet.Cells[$"A{afterIndex}:{colNnw}{afterIndex}"].Style.Border.Bottom.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                sheet.Cells[$"A{afterIndex}:A{afterIndex + 1}"].Style.Border.Left.Style         = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                sheet.Cells[$"A{afterIndex}:{colNnw}{afterIndex + 1}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                sheet.Cells[$"B{afterIndex}"].Value = "COLOUR";
                sheet.Cells[$"B{afterIndex}:B{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"B{afterIndex}:B{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"B{afterIndex}:B{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"C{afterIndex}"].Value = "ART. NO.";
                sheet.Cells[$"C{afterIndex}:C{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"C{afterIndex}:C{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"C{afterIndex}:C{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"D{afterIndex}"].Value = "ORDER. NO.";
                sheet.Cells[$"D{afterIndex}:D{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"D{afterIndex}:D{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"D{afterIndex}:D{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"E{afterIndex}"].Value = "SIZE";
                sheet.Cells[$"E{afterIndex}:{col}{afterIndex}"].Merge = true;
                sheet.Cells[$"E{afterIndex}:{col}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;


                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }
                ;
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var colSize = GetColNameFromIndex(5 + i);
                    var size    = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    sheet.Cells[$"{colSize}{sizeIndex}"].Value = size.Key == 0 ? "" : size.Value;
                    sheet.Cells[$"{colSize}{sizeIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                }

                sheet.Cells[$"{colCtns}{afterIndex}"].Value       = "CTNS";
                sheet.Column(GetColNumberFromName(colCtns)).Width = 4;
                sheet.Cells[$"{colCtns}{afterIndex}:{colCtns}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colCtns}{afterIndex}:{colCtns}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colCtns}{afterIndex}:{colCtns}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colPcs}{afterIndex}"].Value       = "@";
                sheet.Column(GetColNumberFromName(colPcs)).Width = 4;
                sheet.Cells[$"{colPcs}{afterIndex}:{colPcs}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colPcs}{afterIndex}:{colPcs}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colPcs}{afterIndex}:{colPcs}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colQty}{afterIndex}"].Value       = "QTY";
                sheet.Column(GetColNumberFromName(colQty)).Width = 4;
                sheet.Cells[$"{colQty}{afterIndex}:{colQty}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colQty}{afterIndex}:{colQty}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colQty}{afterIndex}:{colQty}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colSatuan}{afterIndex}"].Value       = "SATUAN";
                sheet.Column(GetColNumberFromName(colSatuan)).Width = 6;
                sheet.Cells[$"{colSatuan}{afterIndex}:{colSatuan}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colSatuan}{afterIndex}:{colSatuan}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colSatuan}{afterIndex}:{colSatuan}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colGw}{afterIndex}"].Value       = "GW";
                sheet.Column(GetColNumberFromName(colGw)).Width = 4;
                sheet.Cells[$"{colGw}{afterIndex}:{colGw}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colGw}{afterIndex}:{colGw}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colGw}{afterIndex}:{colGw}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colNw}{afterIndex}"].Value       = "NW";
                sheet.Column(GetColNumberFromName(colNw)).Width = 4;
                sheet.Cells[$"{colNw}{afterIndex}:{colNw}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colNw}{afterIndex}:{colNw}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colNw}{afterIndex}:{colNw}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colNnw}{afterIndex}"].Value       = "NNW";
                sheet.Column(GetColNumberFromName(colNnw)).Width = 4;
                sheet.Cells[$"{colNnw}{afterIndex}:{colNnw}{afterIndex + 1}"].Merge = true;
                sheet.Cells[$"{colNnw}{afterIndex}:{colNnw}{afterIndex}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colNnw}{afterIndex}:{colNnw}{afterIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                double subCtns       = 0;
                double subGw         = 0;
                double subNw         = 0;
                double subNnw        = 0;
                double subTotal      = 0;
                var    sizeSumQty    = new Dictionary <int, double>();
                var    arraySubTotal = new Dictionary <String, double>();
                foreach (var detail in item.Details)
                {
                    var ctnsQty = detail.CartonQuantity;
                    uom = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Uom.Unit;
                    if (cartonNumbers.Contains($"{detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Carton1}- {detail.Carton2}");
                    }
                    sheet.Cells[$"A{valueIndex}"].Value = $"{detail.Carton1}- {detail.Carton2}";
                    sheet.Cells[$"A{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    sheet.Cells[$"B{valueIndex}"].Value = detail.Colour;
                    sheet.Cells[$"B{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    sheet.Cells[$"C{valueIndex}"].Value = item.Article;
                    sheet.Cells[$"C{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    sheet.Cells[$"D{valueIndex}"].Value = item.OrderNo;
                    sheet.Cells[$"D{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;


                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    colSize  = GetColNameFromIndex(5 + i);
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }


                        sheet.Cells[$"{colSize}{valueIndex}"].Value       = quantity == 0 ? "" : quantity.ToString();
                        sheet.Column(GetColNumberFromName(colSize)).Width = 3.5;
                        sheet.Cells[$"{colSize}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    }
                    subCtns += ctnsQty;
                    subGw   += detail.GrossWeight;
                    subNw   += detail.NetWeight;
                    subNnw  += detail.NetNetWeight;

                    sheet.Cells[$"{colCtns}{valueIndex}"].Value = ctnsQty.ToString();
                    sheet.Cells[$"{colCtns}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colPcs}{valueIndex}"].Value = detail.QuantityPCS.ToString();
                    sheet.Cells[$"{colPcs}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    var totalQuantity = detail.CartonQuantity * detail.QuantityPCS;
                    subTotal += totalQuantity;
                    if (!arraySubTotal.ContainsKey(uom))
                    {
                        arraySubTotal.Add(uom, totalQuantity);
                    }
                    else
                    {
                        arraySubTotal[uom] += totalQuantity;
                    }

                    sheet.Cells[$"{colQty}{valueIndex}"].Value = totalQuantity.ToString();
                    sheet.Cells[$"{colQty}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colSatuan}{valueIndex}"].Value = uom;
                    sheet.Cells[$"{colSatuan}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colGw}{valueIndex}"].Value = detail.GrossWeight.ToString();
                    sheet.Cells[$"{colGw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colNw}{valueIndex}"].Value = detail.NetWeight.ToString();
                    sheet.Cells[$"{colNw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colNnw}{valueIndex}"].Value = detail.NetNetWeight.ToString();
                    sheet.Cells[$"{colNnw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    valueIndex++;
                }

                var sumValueIndex = 0;
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var colSize = GetColNameFromIndex(5 + i);
                    sumValueIndex = valueIndex + 1;
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    sheet.Cells[$"D{valueIndex}"].Value = "SUMMARY";
                    sheet.Cells[$"D{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colSize}{valueIndex}"].Value = quantity == 0 ? "" : quantity.ToString();
                }

                sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                totalCtns  += subCtns;
                totalGw    += subGw;
                totalNw    += subNw;
                totalNnw   += subNnw;
                grandTotal += subTotal;
                if (!arrayGrandTotal.ContainsKey(uom))
                {
                    arrayGrandTotal.Add(uom, subTotal);
                }
                else
                {
                    arrayGrandTotal[uom] += subTotal;
                }
                var subTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Merge = true;
                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Value = "SUB TOTAL";
                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"{colQty}{sumValueIndex}"].Value = subTotalResult;
                sheet.Cells[$"{colQty}{sumValueIndex}"].Style.HorizontalAlignment     = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"{colQty}{sumValueIndex}:{colNnw}{sumValueIndex}"].Merge = true;
                sheet.Cells[$"A{sumValueIndex}:{colNnw}{sumValueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{sumValueIndex}:{colNnw}{sumValueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                afterSubTotalIndex = sumValueIndex + 1;
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Merge = true;

                sheet.Cells[$"A{afterSubTotalIndex}"].Value = $"      - Sub Ctns = {subCtns}       - Sub G.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.GrossWeight * a.CartonQuantity))} Kgs      - Sub N.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.NetWeight * a.CartonQuantity))} Kgs     - Sub N.N.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.NetNetWeight * a.CartonQuantity))} Kgs";
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                afterIndex = sizeIndex++;
                index      = afterSubTotalIndex + 2;
            }

            #region GrandTotal
            var grandTotalResult = string.Join(" / ", arrayGrandTotal.Select(x => x.Value + " " + x.Key).ToArray());
            var grandTotalIndex  = afterSubTotalIndex + 2;
            sheet.Cells[$"A{grandTotalIndex}:{colPcs}{grandTotalIndex}"].Merge = true;
            sheet.Cells[$"A{grandTotalIndex}:{colPcs}{grandTotalIndex}"].Value = "GRAND TOTAL";
            sheet.Cells[$"A{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Double;
            sheet.Cells[$"A{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Double;
            sheet.Cells[$"{colQty}{grandTotalIndex}"].Value = grandTotalResult;
            sheet.Cells[$"{colQty}{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Merge = true;

            var comodities        = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            var spellingWordIndex = grandTotalIndex + 2;
            sheet.Cells[$"A{spellingWordIndex}:{colNnw}{spellingWordIndex}"].Merge = true;
            sheet.Cells[$"A{spellingWordIndex}"].Value = $"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]";

            for (int i = 8; i < grandTotalIndex; i++)
            {
                if (sheet.Row(i).Height != 25)
                {
                    sheet.Row(i).Height = 16;
                }
            }

            #endregion

            #region Mark
            var shippingMarkIndex = spellingWordIndex + 2;
            var sideMarkIndex     = spellingWordIndex + 2;

            sheet.Cells[$"A{shippingMarkIndex}"].Value = "SHIPPING MARKS";
            sheet.Cells[$"A{shippingMarkIndex}:B{shippingMarkIndex}"].Merge = true;
            sheet.Cells[$"A{++shippingMarkIndex}"].Value = viewModel.ShippingMark;

            sheet.Cells[$"F{sideMarkIndex}"].Value = "SIDE MARKS";
            sheet.Cells[$"F{sideMarkIndex}:G{sideMarkIndex}"].Merge = true;
            sheet.Cells[$"F{++sideMarkIndex}"].Value = viewModel.SideMark;

            byte[] shippingMarkImage;
            if (!String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
                {
                    shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));
                    Image shipMarkImage          = byteArrayToImage(shippingMarkImage);
                    var   imageShippingMarkIndex = shippingMarkIndex + 1;

                    ExcelPicture excelPictureShipMarkImage = sheet.Drawings.AddPicture("ShippingMarkImage", shipMarkImage);
                    excelPictureShipMarkImage.From.Column = 0;
                    excelPictureShipMarkImage.From.Row    = imageShippingMarkIndex;
                    excelPictureShipMarkImage.SetSize(200, 200);
                }
            }

            byte[] sideMarkImage;
            if (!String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
                {
                    sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                    Image _sideMarkImage     = byteArrayToImage(sideMarkImage);
                    var   sideMarkImageIndex = sideMarkIndex + 1;

                    ExcelPicture excelPictureSideMarkImage = sheet.Drawings.AddPicture("SideMarkImage", _sideMarkImage);
                    excelPictureSideMarkImage.From.Column = 5;
                    excelPictureSideMarkImage.From.Row    = sideMarkImageIndex;
                    excelPictureSideMarkImage.SetSize(200, 200);
                }
            }

            #endregion

            #region Measurement

            var grossWeightIndex  = shippingMarkIndex + 18;
            var netWeightIndex    = grossWeightIndex + 1;
            var netNetWeightIndex = netWeightIndex + 1;
            var measurementIndex  = netNetWeightIndex + 1;

            sheet.Cells[$"A{grossWeightIndex}"].Value = "GROSS WEIGHT";
            sheet.Cells[$"A{grossWeightIndex}:B{grossWeightIndex}"].Merge = true;
            sheet.Cells[$"C{grossWeightIndex}"].Value = viewModel.GrossWeight + " KGS";

            sheet.Cells[$"A{netWeightIndex}"].Value = "NET WEIGHT";
            sheet.Cells[$"A{netWeightIndex}:B{netWeightIndex}"].Merge = true;
            sheet.Cells[$"C{netWeightIndex}"].Value = viewModel.NettWeight + " KGS";

            sheet.Cells[$"A{netNetWeightIndex}"].Value = "NET NET WEIGHT";
            sheet.Cells[$"A{netNetWeightIndex}:B{netNetWeightIndex}"].Merge = true;
            sheet.Cells[$"C{netNetWeightIndex}"].Value = viewModel.NetNetWeight + " KGS";

            sheet.Cells[$"A{measurementIndex}"].Value = "MEASUREMENT";
            sheet.Cells[$"A{measurementIndex}:B{measurementIndex}"].Merge = true;

            decimal totalCbm = 0;
            foreach (var measurement in viewModel.Measurements)
            {
                sheet.Cells[$"C{measurementIndex}"].Value = measurement.Length + " X ";
                sheet.Cells[$"D{measurementIndex}"].Value = measurement.Width + " X ";
                sheet.Cells[$"E{measurementIndex}"].Value = measurement.Height + " X ";
                sheet.Cells[$"E{measurementIndex}:G{measurementIndex}"].Merge = true;
                sheet.Cells[$"H{measurementIndex}"].Value = measurement.CartonsQuantity + " CTNS";
                sheet.Cells[$"H{measurementIndex}:I{measurementIndex}"].Merge = true;

                sheet.Cells[$"J{measurementIndex}"].Value = "=";


                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                sheet.Cells[$"K{measurementIndex}"].Value = string.Format("{0:N2} CBM", cbm);
                sheet.Cells[$"K{measurementIndex}:M{measurementIndex}"].Merge = true;

                measurementIndex++;
            }
            var totalMeasurementIndex = measurementIndex;
            sheet.Cells[$"C{totalMeasurementIndex}:K{totalMeasurementIndex}"].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            sheet.Cells[$"D{totalMeasurementIndex}"].Value = "TOTAL";
            sheet.Cells[$"D{totalMeasurementIndex}:G{totalMeasurementIndex}"].Merge = true;
            sheet.Cells[$"H{totalMeasurementIndex}"].Value = viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .";
            sheet.Cells[$"H{totalMeasurementIndex}:I{totalMeasurementIndex}"].Merge = true;
            sheet.Cells[$"K{totalMeasurementIndex}"].Value = string.Format("{0:N2} CBM", totalCbm);
            sheet.Cells[$"J{totalMeasurementIndex}"].Value = "=";
            sheet.Cells[$"K{totalMeasurementIndex}:L{totalMeasurementIndex}"].Merge = true;


            #endregion

            #region remark
            var remarkIndex = totalMeasurementIndex + 1;
            sheet.Cells[$"A{remarkIndex}"].Value   = "REMARK";
            sheet.Cells[$"A{++remarkIndex}"].Value = viewModel.Remark;

            byte[] remarkImage;
            var    remarkImageIndex = remarkIndex + 1;
            if (!String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
                {
                    remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));
                    Image        _remarkImage            = byteArrayToImage(remarkImage);
                    ExcelPicture excelPictureRemarkImage = sheet.Drawings.AddPicture("RemarkImage", _remarkImage);
                    excelPictureRemarkImage.From.Column = 0;
                    excelPictureRemarkImage.From.Row    = remarkImageIndex;
                    excelPictureRemarkImage.SetSize(200, 200);
                }
            }


            #endregion

            #region Signature
            var signatureIndex = remarkImageIndex + 14;
            sheet.Cells[$"{colCtns}{signatureIndex}:{colNnw}{signatureIndex}"].Merge = true;
            sheet.Cells[$"{colCtns}{signatureIndex}"].Value = "( MRS.ADRIYANA DAMAYANTI )";
            sheet.Cells[$"{colCtns}{signatureIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            sheet.Cells[$"{colCtns}{++signatureIndex}"].Value = "AUTHORIZED SIGNATURE";
            sheet.Cells[$"{colCtns}{signatureIndex}:{colNnw}{signatureIndex}"].Merge = true;
            sheet.Cells[$"{colCtns}{signatureIndex}"].Style.HorizontalAlignment      = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            #endregion

            sheet.Cells.Style.Font.SetFromFont(new Font("Tahoma", 7, FontStyle.Regular));
            //sheet.Cells[sheet.Dimension.Address].AutoFitColumns(15, 40);
            sheet.Cells.Style.WrapText = true;

            sheet.PrinterSettings.LeftMargin  = 0.39M;
            sheet.PrinterSettings.TopMargin   = 0;
            sheet.PrinterSettings.RightMargin = 0;

            sheet.PrinterSettings.Orientation = maxSizesCount > 11 ? eOrientation.Landscape : eOrientation.Portrait;


            MemoryStream stream = new MemoryStream();
            package.DoAdjustDrawings = false;
            package.SaveAs(stream);
            return(stream);
        }
        public MemoryStream GeneratePdfTemplate(GarmentShippingInvoiceViewModel viewModel, Buyer buyer, BankAccount bank, GarmentPackingListViewModel pl, int timeoffset)
        {
            const int MARGIN = 20;

            Font header_font            = FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            //Font body_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(PageSize.A4, MARGIN, MARGIN, 300, MARGIN);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentShippingInvoicePDFTemplatePageEvent(viewModel, timeoffset);

            document.Open();

            #region Header
            //PdfPTable tableHeader = new PdfPTable(3);
            //tableHeader.SetWidths(new float[] { 1f, 1f, 1f });

            //PdfPCell cellHeaderContentLeft = new PdfPCell() { Border = Rectangle.NO_BORDER };
            //cellHeaderContentLeft.AddElement(new Phrase("\n", normal_font));
            //cellHeaderContentLeft.AddElement(new Phrase("Invoice No.  :  " + viewModel.InvoiceNo, normal_font));
            //tableHeader.AddCell(cellHeaderContentLeft);

            //PdfPCell cellHeaderContentCenter = new PdfPCell() { Border = Rectangle.NO_BORDER };
            //cellHeaderContentCenter.AddElement(new Phrase("\n", normal_font));
            //cellHeaderContentCenter.AddElement(new Paragraph("Date  :  " + viewModel.InvoiceDate.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font));
            //tableHeader.AddCell(cellHeaderContentCenter);

            //PdfPCell cellHeaderContentRight = new PdfPCell() { Border = Rectangle.NO_BORDER };
            //cellHeaderContentRight.AddElement(new Phrase("", bold_font));
            //tableHeader.AddCell(cellHeaderContentRight);

            //PdfPCell cellHeader = new PdfPCell(tableHeader);
            //tableHeader.ExtendLastRow = false;
            //tableHeader.SpacingAfter = 15f;
            //document.Add(tableHeader);
            #endregion

            #region detailOrders
            //PdfPTable tabledetailOrders = new PdfPTable(3);
            //tabledetailOrders.SetWidths(new float[] { 0.6f, 1.4f, 2f });

            //PdfPCell cellDetailContentLeft = new PdfPCell() { Border = Rectangle.TOP_BORDER };
            //PdfPCell cellDetailContentRight = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER };
            //PdfPCell cellDetailContentCenter = new PdfPCell() { Border = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER };

            //cellDetailContentLeft.Phrase = new Phrase("SOLD BY ORDERS AND FOR ACCOUNT AND RISK OF", normal_font);
            //cellDetailContentLeft.Colspan = 2;
            //tabledetailOrders.AddCell(cellDetailContentLeft);

            //cellDetailContentLeft.Phrase = new Phrase("CO NO.  : " + viewModel.CO, normal_font);
            //cellDetailContentLeft.Colspan = 1;
            //cellDetailContentLeft.Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentLeft);

            //cellDetailContentRight.AddElement(new Phrase("MESSRS      : ", normal_font));
            //cellDetailContentRight.Border = Rectangle.NO_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentRight);

            //cellDetailContentCenter.AddElement(new Phrase(viewModel.BuyerAgent.Name, normal_font));
            //cellDetailContentCenter.AddElement(new Phrase(viewModel.ConsigneeAddress, normal_font));
            //cellDetailContentCenter.Border = Rectangle.NO_BORDER;
            ////cellDetailContentCenter.AddElement(new Phrase(buyer.Country, normal_font));
            //tabledetailOrders.AddCell(cellDetailContentCenter);


            //cellDetailContentRight.Phrase=new Phrase("", normal_font);
            //cellDetailContentRight.AddElement(new Phrase("CONFIRMATION OF ORDER NO. : " + viewModel.ConfirmationOfOrderNo, normal_font));
            //cellDetailContentRight.AddElement(new Phrase("SHIPPED PER : " + viewModel.ShippingPer, normal_font));
            //cellDetailContentRight.AddElement(new Phrase("SAILING ON OR ABOUT : " + viewModel.SailingDate.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font));
            //cellDetailContentRight.AddElement(new Phrase("FROM : " + viewModel.From, normal_font));
            //cellDetailContentRight.AddElement(new Phrase("TO   : " + viewModel.To, normal_font));
            //// cellDetailContentRight.AddElement(new Phrase("\n", normal_font));
            //cellDetailContentRight.Border = Rectangle.LEFT_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentRight);



            //cellDetailContentRight.Phrase = new Phrase("DELIVERED TO : ", normal_font);
            //cellDetailContentRight.Colspan = 1;
            //cellDetailContentRight.Border = Rectangle.BOTTOM_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentRight);

            //cellDetailContentCenter.Phrase=new Phrase(viewModel.DeliverTo, normal_font);
            //cellDetailContentCenter.Border = Rectangle.BOTTOM_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentCenter);

            //cellDetailContentRight.Phrase = new Phrase("", normal_font);
            //cellDetailContentRight.Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER;
            //tabledetailOrders.AddCell(cellDetailContentRight);

            //PdfPCell cellDetail = new PdfPCell(tabledetailOrders);
            //tabledetailOrders.ExtendLastRow = false;
            //tabledetailOrders.SpacingAfter = 5f;
            //tabledetailOrders.HeaderRows = 3;
            //document.Add(tabledetailOrders);
            #endregion

            #region LC
            PdfPTable tableLC = new PdfPTable(3);
            tableLC.SetWidths(new float[] { 2f, 0.1f, 6f });

            if (pl.PaymentTerm == "LC")
            {
                PdfPCell cellLCContentLeft = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentLeft.AddElement(new Phrase("LETTER OF CREDIT NUMBER ", normal_font));
                cellLCContentLeft.AddElement(new Phrase("LC DATE ", normal_font));
                cellLCContentLeft.AddElement(new Phrase("ISSUED BY ", normal_font));
                tableLC.AddCell(cellLCContentLeft);

                PdfPCell cellLCContentCenter = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                tableLC.AddCell(cellLCContentCenter);

                PdfPCell cellLCContentRight = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentRight.AddElement(new Phrase(viewModel.LCNo, normal_font));
                cellLCContentRight.AddElement(new Phrase(pl.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font));
                cellLCContentRight.AddElement(new Phrase(viewModel.IssuedBy, normal_font));
                tableLC.AddCell(cellLCContentRight);
            }
            else
            {
                PdfPCell cellLCContentLeft = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentLeft.AddElement(new Phrase("PAYMENT TERM ", normal_font));
                tableLC.AddCell(cellLCContentLeft);

                PdfPCell cellLCContentCenter = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentCenter.AddElement(new Phrase(": ", normal_font));
                tableLC.AddCell(cellLCContentCenter);

                PdfPCell cellLCContentRight = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };
                cellLCContentRight.AddElement(new Phrase("TT PAYMENT", normal_font));
                tableLC.AddCell(cellLCContentRight);
            }



            PdfPCell cellLC = new PdfPCell(tableLC);
            tableLC.ExtendLastRow = false;
            tableLC.SpacingAfter  = 15f;
            document.Add(tableLC);
            #endregion

            #region Body Table

            PdfPTable bodyTable       = new PdfPTable(10);
            float[]   bodyTableWidths = new float[] { 1.6f, 1.6f, 1.6f, 1.6f, 1.2f, 0.8f, 1.5f, 1.8f, 1.5f, 1.8f };
            bodyTable.SetWidths(bodyTableWidths);
            bodyTable.WidthPercentage = 100;

            #region Set Body Table Header
            PdfPCell bodyTableHeader = new PdfPCell()
            {
                FixedHeight = 20
            };
            //PdfPCell table1RightCellHeader = new PdfPCell() { FixedHeight = 20, Colspan = 4 };

            bodyTableHeader.Phrase = new Phrase("DESCRIPTION", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            //bodyTableHeader.Rowspan = 2;
            bodyTableHeader.Colspan = 4;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("QUANTITY", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Colspan             = 2;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("UNIT PRICE", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Rowspan             = 1;
            bodyTableHeader.Colspan             = 1;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("TOTAL PRICE", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("UNIT PRICE", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("TOTAL PRICE", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            //bodyTableHeader.Rowspan = 2;
            bodyTableHeader.Colspan = 4;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Colspan             = 2;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase(viewModel.CPrice + " IN USD", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Colspan             = 2;
            bodyTable.AddCell(bodyTableHeader);

            bodyTableHeader.Phrase = new Phrase("CMT IN USD", normal_font);
            bodyTableHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableHeader.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableHeader.Colspan             = 2;
            bodyTable.AddCell(bodyTableHeader);
            #endregion

            #region Set Body Table Value
            PdfPCell bodyTableCellRightBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.RIGHT_BORDER
            };
            PdfPCell bodyTableCellLeftBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.LEFT_BORDER
            };
            PdfPCell bodyTableCellCenterBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER
            };
            PdfPCell bodyTableCellNoBorder = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.NO_BORDER
            };

            bodyTableCellLeftBorder.Phrase = new Phrase(viewModel.Description, body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 2;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);

            //SPACE
            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellLeftBorder.Phrase = new Phrase("", body_font);
            bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellLeftBorder.Colspan             = 2;
            bodyTable.AddCell(bodyTableCellLeftBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);

            bodyTableCellCenterBorder.Phrase = new Phrase("", body_font);
            bodyTableCellCenterBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellCenterBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellCenterBorder);

            bodyTableCellRightBorder.Phrase = new Phrase("", body_font);
            bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellRightBorder);


            decimal totalAmount               = 0;
            double  totalQuantity             = 0;
            double  totalCMTPrice             = 0;
            decimal totalPrice                = 0;
            Dictionary <string, double> total = new Dictionary <string, double>();
            foreach (var item in viewModel.Items)
            {
                totalAmount   += item.Amount;
                totalQuantity += item.Quantity;
                totalCMTPrice += item.Quantity * (double)item.CMTPrice;
                if (item.CMTPrice > 0)
                {
                    totalPrice += item.Amount;
                }

                bodyTableCellLeftBorder.Phrase = new Phrase(item.ComodityDesc, body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.Colspan             = 1;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellNoBorder.Phrase = new Phrase(item.Desc2, body_font);
                bodyTableCellNoBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellNoBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellNoBorder.Colspan             = 1;
                bodyTable.AddCell(bodyTableCellNoBorder);

                bodyTableCellNoBorder.Phrase = new Phrase(item.Desc3, body_font);
                bodyTableCellNoBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellNoBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellNoBorder.Colspan             = 1;
                bodyTable.AddCell(bodyTableCellNoBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Desc4, body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellRightBorder.Colspan             = 1;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellLeftBorder.Phrase = new Phrase(string.Format("{0:n2}", item.Quantity), body_font);
                bodyTableCellLeftBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellLeftBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellLeftBorder.BorderColorRight    = BaseColor.White;
                bodyTable.AddCell(bodyTableCellLeftBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Uom.Unit, body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTableCellRightBorder.BorderColorLeft     = BaseColor.White;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Price == 0? "" : string.Format("{0:n4}", item.Price), body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.Amount == 0? "" : string.Format("{0:n2}", item.Amount), body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.CMTPrice != 0 ? string.Format("{0:n4}", item.CMTPrice) : "", body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                bodyTableCellRightBorder.Phrase = new Phrase(item.CMTPrice != 0 ? string.Format("{0:n2}", item.Quantity * (double)item.CMTPrice) : "", body_font);
                bodyTableCellRightBorder.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyTableCellRightBorder.VerticalAlignment   = Element.ALIGN_CENTER;
                bodyTable.AddCell(bodyTableCellRightBorder);

                if (total.ContainsKey(item.Uom.Unit))
                {
                    total[item.Uom.Unit] += item.Quantity;
                }
                else
                {
                    total.Add(item.Uom.Unit, item.Quantity);
                }
            }
            PdfPCell bodyTableCellFooter = new PdfPCell()
            {
                FixedHeight = 20, Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER
            };

            bodyTableCellFooter.Phrase = new Phrase("TOTAL  ", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Colspan             = 4;
            bodyTable.AddCell(bodyTableCellFooter);

            var val1    = total.Select(x => String.Format("{0:n2}", x.Value));
            var result1 = String.Join("\n", val1);

            var key1    = total.Select(x => String.Format("{0}", x.Key));
            var result2 = String.Join("\n", key1);

            bodyTableCellFooter.Phrase = new Phrase($"{result1}", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Colspan             = 1;
            bodyTableCellFooter.Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);


            bodyTableCellFooter.Phrase = new Phrase(result2, body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Border = Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase("", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase(totalAmount == 0? "":string.Format("{0:n2}", totalAmount), body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Border = Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase("", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTable.AddCell(bodyTableCellFooter);

            bodyTableCellFooter.Phrase = new Phrase(totalCMTPrice != 0 ? string.Format("{0:n2}", totalCMTPrice) : "", body_font);
            bodyTableCellFooter.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyTableCellFooter.VerticalAlignment   = Element.ALIGN_CENTER;
            bodyTableCellFooter.Border = Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
            bodyTable.AddCell(bodyTableCellFooter);

            #endregion
            bodyTable.HeaderRows = 2;
            document.Add(bodyTable);
            #endregion

            #region calculationTable
            PdfPTable calculationTable = new PdfPTable(4);
            calculationTable.HorizontalAlignment = Element.ALIGN_LEFT;
            float[] calculationTableWidths = new float[] { 4f, 2f, 2f, 6f };
            calculationTable.SetWidths(calculationTableWidths);
            calculationTable.WidthPercentage = 100;

            PdfPCell calculationCellRight = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            PdfPCell calculationCellLeft = new PdfPCell()
            {
                MinimumHeight = 15, Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };

            calculationCellLeft.Phrase = new Phrase("TOTAL AMOUNT FOB ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellLeft.Phrase = new Phrase(": USD ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellRight.Phrase = new Phrase(string.Format("{0:n2}", totalAmount), normal_font);
            calculationTable.AddCell(calculationCellRight);
            calculationCellRight.Phrase = new Phrase("", normal_font);
            calculationTable.AddCell(calculationCellRight);


            calculationCellLeft.Phrase = new Phrase("LESS FABRIC COST ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellLeft.Phrase = new Phrase(": USD ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellRight.Phrase = new Phrase(string.Format("{0:n2}", (totalPrice - (decimal)totalCMTPrice) * -1), normal_font);
            calculationTable.AddCell(calculationCellRight);
            calculationCellRight.Phrase = new Phrase("", normal_font);
            calculationTable.AddCell(calculationCellRight);

            decimal totalAmountCMT = totalAmount - (totalPrice - (decimal)totalCMTPrice);
            calculationCellLeft.Phrase = new Phrase("TOTAL AMOUNT CMT ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellLeft.Phrase = new Phrase(": USD ", normal_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellRight.Phrase = new Phrase(string.Format("{0:n2}", totalAmountCMT), normal_font);
            calculationTable.AddCell(calculationCellRight);
            calculationCellRight.Phrase = new Phrase("", normal_font);
            calculationTable.AddCell(calculationCellRight);

            decimal totalPaid = totalAmountCMT;
            if (viewModel.GarmentShippingInvoiceAdjustments.Count > 0)
            {
                foreach (var adj in viewModel.GarmentShippingInvoiceAdjustments)
                {
                    totalPaid += adj.AdjustmentValue;
                    calculationCellLeft.Phrase = new Phrase($"{adj.AdjustmentDescription} ", normal_font);
                    calculationTable.AddCell(calculationCellLeft);
                    calculationCellLeft.Phrase = new Phrase(": USD ", normal_font);
                    calculationTable.AddCell(calculationCellLeft);
                    calculationCellRight.Phrase = new Phrase(string.Format("{0:n2}", adj.AdjustmentValue), normal_font);
                    calculationTable.AddCell(calculationCellRight);
                    calculationCellRight.Phrase = new Phrase("", normal_font);
                    calculationTable.AddCell(calculationCellRight);
                }
            }

            calculationCellLeft.Phrase = new Phrase($"TOTAL AMOUNT TO BE PAID ", bold_font);
            calculationCellLeft.Border = Rectangle.TOP_BORDER;
            calculationTable.AddCell(calculationCellLeft);
            calculationCellLeft.Phrase = new Phrase(": USD ", bold_font);
            calculationTable.AddCell(calculationCellLeft);
            calculationCellRight.Phrase = new Phrase(string.Format("{0:n2}", totalPaid), bold_font);
            calculationCellRight.Border = Rectangle.TOP_BORDER;
            calculationTable.AddCell(calculationCellRight);
            calculationCellRight.Phrase = new Phrase("", bold_font);
            calculationCellRight.Border = Rectangle.NO_BORDER;
            calculationTable.AddCell(calculationCellRight);

            string amountToText = "";
            if (totalPaid < 0)
            {
                totalPaid    = totalPaid * -1;
                amountToText = "MINUS " + NumberToTextEN.toWords((double)totalPaid);
            }
            else
            {
                amountToText = NumberToTextEN.toWords((double)totalPaid);
            }
            calculationCellLeft.Phrase  = new Phrase($"SAY : US DOLLARS {amountToText.ToUpper()} ONLY ///", normal_font);
            calculationCellLeft.Colspan = 4;
            calculationCellLeft.Border  = Rectangle.NO_BORDER;
            calculationTable.AddCell(calculationCellLeft);

            document.Add(calculationTable);
            #endregion

            document.Add(new Paragraph("\n", normal_font));

            if (bank != null)
            {
                document.Add(new Paragraph("PLEASE TT THE ABOVE PAYMENT TO OUR CORRESPONDENCE BANK AS FOLLOW   : ", normal_font));

                document.Add(new Paragraph(viewModel.BankAccount, normal_font));
                document.Add(new Paragraph(bank.bankAddress, normal_font));
                document.Add(new Paragraph("ACC NO. " + bank.AccountNumber + $"({bank.Currency.Code})", normal_font));
                document.Add(new Paragraph("A/N " + bank.accountName, normal_font));
                document.Add(new Paragraph("SWIFT CODE : " + bank.swiftCode, normal_font));
                document.Add(new Paragraph("PURPOSE CODE : 1011", normal_font));
                document.Add(new Paragraph("\n", normal_font));
            }


            #region MARK
            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 2f, 4f });
            tableMark.WidthPercentage = 100;

            PdfPCell cellMarkContent = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellMarkContent.AddElement(new Phrase("SHIPPING MARKS :", normal_font_underlined));
            cellMarkContent.AddElement(new Phrase(pl.ShippingMark, normal_font));
            tableMark.AddCell(cellMarkContent);

            PdfPCell cellMarkContentR = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellMarkContentR.AddElement(new Phrase("SIDE MARKS :", normal_font_underlined));
            cellMarkContentR.AddElement(new Phrase(pl.SideMark, normal_font));
            tableMark.AddCell(cellMarkContentR);

            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 15f;
            document.Add(tableMark);

            #endregion


            #region Weight
            PdfPTable tableWeight = new PdfPTable(3);
            tableWeight.SetWidths(new float[] { 3f, 1f, 6f });
            tableWeight.WidthPercentage = 100;

            PdfPCell cellWeightContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellWeightContentLeft.AddElement(new Phrase("GROSS WEIGHT ", normal_font));
            cellWeightContentLeft.AddElement(new Phrase("NETT WEIGHT ", normal_font));
            cellWeightContentLeft.AddElement(new Phrase("MEASSUREMENT ", normal_font));
            tableWeight.AddCell(cellWeightContentLeft);

            PdfPCell cellWeightContentCenter = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellWeightContentCenter.AddElement(new Phrase(" : ", normal_font));
            cellWeightContentCenter.AddElement(new Phrase(" : ", normal_font));
            cellWeightContentCenter.AddElement(new Phrase(" : ", normal_font));
            tableWeight.AddCell(cellWeightContentCenter);

            PdfPCell cellWeightContentRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellWeightContentRight.AddElement(new Phrase($"{pl.GrossWeight} KGS", normal_font));
            cellWeightContentRight.AddElement(new Phrase($"{pl.NettWeight} KGS", normal_font));

            PdfPTable tableMeasurement = new PdfPTable(5);
            tableMeasurement.SetWidths(new float[] { 1f, 1f, 1f, 2f, 2f });
            tableMeasurement.WidthPercentage = 100;

            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            if (pl.Measurements.Count > 0)
            {
                double totalctns = 0;
                double totalCM   = 0;
                foreach (var m in pl.Measurements)
                {
                    double cbm = (m.Length * m.Width * m.Height * m.CartonsQuantity) / 1000000;

                    cellMeasurement.Phrase      = new Phrase($"{m.Length} X", normal_font);
                    cellMeasurement.PaddingLeft = 1;
                    tableMeasurement.AddCell(cellMeasurement);

                    cellMeasurement.Phrase = new Phrase($"{m.Width} X", normal_font);
                    tableMeasurement.AddCell(cellMeasurement);

                    cellMeasurement.Phrase = new Phrase($"{m.Height} X", normal_font);
                    tableMeasurement.AddCell(cellMeasurement);

                    cellMeasurement.Phrase = new Phrase($"{m.CartonsQuantity} CTNS = ", normal_font);
                    tableMeasurement.AddCell(cellMeasurement);

                    cellMeasurement.Phrase = new Phrase(string.Format("{0:n2}", cbm) + " CBM", normal_font);
                    tableMeasurement.AddCell(cellMeasurement);

                    totalctns += m.CartonsQuantity;
                    totalCM   += cbm;
                }

                cellMeasurement.Phrase  = new Phrase("", normal_font);
                cellMeasurement.Colspan = 2;
                tableMeasurement.AddCell(cellMeasurement);

                cellMeasurement.Phrase = new Phrase($"{totalctns} CTNS", normal_font);
                tableMeasurement.AddCell(cellMeasurement);

                cellMeasurement.Phrase = new Phrase(string.Format("{0:n2}", totalCM) + " CBM", normal_font);
                tableMeasurement.AddCell(cellMeasurement);

                cellWeightContentRight.AddElement(tableMeasurement);
            }

            tableWeight.AddCell(cellWeightContentRight);


            tableWeight.SpacingAfter = 15f;
            document.Add(tableWeight);
            #endregion

            document.Add(new Paragraph("REMARK : ", normal_font_underlined));
            document.Add(new Paragraph(pl.Remark, normal_font));

            document.Add(new Paragraph("\n", normal_font));
            document.Add(new Paragraph("\n", normal_font));
            document.Add(new Paragraph("\n", normal_font));
            document.Add(new Paragraph("\n", normal_font));
            document.Add(new Paragraph("\n", normal_font));

            Paragraph sign = new Paragraph("( MRS. ADRIYANA DAMAYANTI )", normal_font_underlined);
            sign.Alignment = Element.ALIGN_RIGHT;
            Paragraph author = new Paragraph("AUTHORIZED SIGNATURE  ", normal_font);
            author.Alignment = Element.ALIGN_RIGHT;

            document.Add(sign);
            document.Add(author);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
        public MemoryStream GeneratePdfTemplate(GarmentShippingDebitNoteViewModel viewModel, int timeoffset)
        {
            Font normal_font     = FontFactory.GetFont(BaseFont.COURIER, 10, Font.NORMAL);
            Font underlined_font = FontFactory.GetFont(BaseFont.COURIER, 10, Font.UNDERLINE);
            Font big_font        = FontFactory.GetFont(BaseFont.COURIER, 16, Font.BOLD);

            Document     document = new Document(PageSize.A4, 20, 20, 20, 20);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            var chunkHeader = new Chunk("PT. DAN LIRIS", big_font);

            chunkHeader.SetHorizontalScaling(1.5f);
            document.Add(new Paragraph(chunkHeader));

            PdfPTable tableHeadOffice = new PdfPTable(2);

            tableHeadOffice.SetWidths(new float[] { 1.5f, 6.5f });

            PdfPCell cellHeadOffice = new PdfPCell {
                Border = Rectangle.NO_BORDER
            };

            cellHeadOffice.Phrase = new Phrase("Head Office : ", normal_font);
            tableHeadOffice.AddCell(cellHeadOffice);
            cellHeadOffice.Phrase = new Phrase("Jl. Merapi No. 23, Kel. Banaran Kec. Grogol Kab. Sukoharjo\nTelp.(0271)714400, Fax.(0271)735222\ne-Mail:", normal_font);
            cellHeadOffice.Phrase.Add(new Chunk("*****@*****.**", underlined_font));
            tableHeadOffice.AddCell(cellHeadOffice);
            Chunk chunkAddress = new Chunk("MESSRS :\n" + viewModel.buyer.Name + "\n" + viewModel.buyer.Address, normal_font);

            chunkAddress.SetHorizontalScaling(0.8f);
            Phrase phraseBuyerHeader = new Phrase(chunkAddress);

            //phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            //phraseBuyerHeader.Add(new Chunk("DEBIT NOTE", normal_font));

            phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            phraseBuyerHeader.Add(new Chunk("DATE : " + viewModel.date.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font));

            tableHeadOffice.AddCell(new PdfPCell
            {
                Border      = Rectangle.NO_BORDER,
                Colspan     = 2,
                PaddingLeft = 10f,
                Phrase      = phraseBuyerHeader
            });

            new PdfPCell(tableHeadOffice);
            tableHeadOffice.ExtendLastRow = false;
            tableHeadOffice.SpacingAfter  = 5f;
            document.Add(tableHeadOffice);

            document.Add(new Paragraph("DEBIT NOTE", big_font)
            {
                Alignment = Element.ALIGN_CENTER, SpacingAfter = 5f
            });

            document.Add(new Paragraph(viewModel.noteNo, big_font)
            {
                Alignment = Element.ALIGN_RIGHT, SpacingAfter = 5f
            });

            PdfPTable tableItems = new PdfPTable(2);

            tableItems.SetWidths(new float[] { 3f, 1f });

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("D e s c r i p t i o n", normal_font)
            });
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("Amount", normal_font)
            });

            PdfPTable tableItemsContent = new PdfPTable(2);

            tableItemsContent.SetWidths(new float[] { 3f, 1f });

            tableItemsContent.AddCell(new PdfPCell
            {
                Border = Rectangle.NO_BORDER,
                Phrase = new Phrase(viewModel.description, normal_font)
            });

            tableItemsContent.AddCell(new PdfPCell
            {
                Border = Rectangle.LEFT_BORDER,
                Phrase = new Phrase(" ", normal_font)
            });

            foreach (var item in viewModel.items)
            {
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.NO_BORDER,
                    Phrase = new Phrase(item.description, normal_font)
                });
                Phrase phraseAmount = new Phrase();
                phraseAmount.Add(new Chunk(viewModel.bank.Currency.Code, normal_font));
                phraseAmount.Add(new Chunk(new VerticalPositionMark()));
                phraseAmount.Add(new Chunk(item.amount.ToString("n"), normal_font));
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.LEFT_BORDER,
                    Phrase = phraseAmount
                });
            }

            PdfPCell pdfPCellItemsContent = new PdfPCell
            {
                Colspan       = 2,
                Padding       = 0,
                Border        = Rectangle.NO_BORDER,
                MinimumHeight = 400
            };

            new PdfPCell(tableItemsContent);
            pdfPCellItemsContent.AddElement(tableItemsContent);
            tableItems.AddCell(pdfPCellItemsContent);

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                PaddingRight        = 10,
                Phrase = new Phrase("TOTAL", normal_font)
            });
            Phrase phraseTotalAmount = new Phrase();

            phraseTotalAmount.Add(new Chunk(viewModel.bank.Currency.Code, normal_font));
            phraseTotalAmount.Add(new Chunk(new VerticalPositionMark()));
            phraseTotalAmount.Add(new Chunk(viewModel.totalAmount.ToString("n"), normal_font));
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                Phrase = phraseTotalAmount
            });
            //tableItems.AddCell(new PdfPCell
            //{
            //    Colspan = 2,
            //    PaddingBottom = 10f,
            //    Border = Rectangle.NO_BORDER,
            //    Phrase = new Phrase("KETERANGAN   : " + viewModel.description, normal_font)
            //});

            if (viewModel.bank.Currency.Code == "USD")
            {
                tableItems.AddCell(new PdfPCell
                {
                    Colspan       = 2,
                    PaddingBottom = 10f,
                    Border        = Rectangle.NO_BORDER,
                    Phrase        = new Phrase("SAY : US DOLLARS " + NumberToTextEN.toWords(viewModel.totalAmount).Trim().ToUpper() + " ONLY ///", normal_font)
                });
            }
            else
            {
                tableItems.AddCell(new PdfPCell
                {
                    Colspan       = 2,
                    PaddingBottom = 10f,
                    Border        = Rectangle.NO_BORDER,
                    Phrase        = new Phrase("TERBILANG : " + NumberToTextIDN.terbilang(viewModel.totalAmount).Trim().ToUpper() + " RUPIAH ///", normal_font)
                });
            }

            //tableItems.AddCell(new PdfPCell
            //{
            //    Border = Rectangle.NO_BORDER,
            //    PaddingRight = 10f,
            //    Phrase = new Phrase("Please TT the above payment to our correspondence bank as follow :", normal_font)
            //});
            Phrase phraseSign = new Phrase();

            phraseSign.Add(new Chunk("S.E. & O\n" + viewModel.date.GetValueOrDefault().ToString("MMMM dd, yyyy") + "\n\n\n\n", normal_font));
            Chunk chunkSignName = new Chunk("A M U M P U N I", normal_font);

            chunkSignName.SetUnderline(1, -1);
            phraseSign.Add(chunkSignName);
            phraseSign.Add(new Chunk("\nAUTHORIZED SIGNATURE", normal_font));

            string branch = "";

            if (viewModel.bank.bankName == "PT. CIMB NIAGA Tbk.")
            {
                branch = "SOLO BRANCH OFFICE";
            }
            else if (viewModel.bank.bankName == "PANIN BANK")
            {
                branch = "SOLO BRANCH OFFICE";
            }
            else
            {
                branch = "SRIWEDARI BRANCH OFFICE";
            }

            tableItems.AddCell(new PdfPCell
            {
                Border       = Rectangle.NO_BORDER,
                PaddingLeft  = 20f,
                PaddingRight = 10f,
                Phrase       = new Phrase($"{viewModel.bank.bankName}\n{branch}\n{viewModel.bank.bankAddress}\nACC. No. {viewModel.bank.AccountNumber} ({viewModel.bank.Currency.Code})\nA/N. PT. DAN LIRIS\nSWIFT CODE : {viewModel.bank.swiftCode}\nPURPOSE CODE : 1011", normal_font)
            });

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Rowspan             = 2,
                Phrase = phraseSign
            });

            new PdfPCell(tableItems);
            tableItems.ExtendLastRow = false;
            tableItems.SpacingAfter  = 5f;
            document.Add(tableItems);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#13
0
        public MemoryStream GenerateExcelTemplate(GarmentPackingListViewModel viewModel)
        {
            //int maxSizesCount = viewModel.Items == null || viewModel.Items.Count < 1 ? 0 : viewModel.Items.Max(i => i.Details == null || i.Details.Count < 1 ? 0 : i.Details.Max(d => d.Sizes == null || d.Sizes.Count < 1 ? 0 : d.Sizes.GroupBy(g => g.Size.Id).Count()));
            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newItems2  = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items.OrderBy(a => a.RONo))
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Carton1).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.OrderBy(o => o.RONo).Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            foreach (var item in newItems)
            {
                if (newItems2.Count == 0)
                {
                    newItems2.Add(item);
                }
                else
                {
                    if (newItems2.Last().RONo == item.RONo && newItems2.Last().OrderNo == item.OrderNo)
                    {
                        foreach (var d in item.Details.OrderBy(a => a.Carton1))
                        {
                            newItems2.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        newItems2.Add(item);
                    }
                }
            }

            var sizesCount = false;

            foreach (var item in newItems2)
            {
                var sizesMax = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizesMax[size.Size.Id] = size.Size.Size;
                    }
                }
                if (sizesMax.Count > 11)
                {
                    sizesCount = true;
                }
            }
            int SIZES_COUNT = sizesCount ? 20 : 11;

            var col       = GetColNameFromIndex(SIZES_COUNT + 4);
            var colCtns   = GetColNameFromIndex(SIZES_COUNT + 5);
            var colPcs    = GetColNameFromIndex(SIZES_COUNT + 6);
            var colQty    = GetColNameFromIndex(SIZES_COUNT + 7);
            var colSatuan = GetColNameFromIndex(SIZES_COUNT + 8);
            var colGw     = GetColNameFromIndex(SIZES_COUNT + 9);
            var colNw     = GetColNameFromIndex(SIZES_COUNT + 10);
            var colNnw    = GetColNameFromIndex(SIZES_COUNT + 11);

            DataTable result = new DataTable();

            ExcelPackage package = new ExcelPackage();
            var          sheet   = package.Workbook.Worksheets.Add("Report");

            sheet.Cells.Style.Font.SetFromFont(new Font("Tahoma", 7, FontStyle.Regular));

            sheet.Cells["A1"].Value            = "DRAFT PACKING LIST";
            sheet.Cells[$"A1:{colNnw}1"].Merge = true;
            sheet.Cells[$"A1:{colNnw}1"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
            sheet.Cells["A1"].Style.Font.SetFromFont(new Font("Helvetica", 25));
            sheet.Cells["A1"].Style.Font.Bold = true;
            sheet.Row(1).Height = 30;

            sheet.Cells["A2"].Value    = "Invoice No.";
            sheet.Cells["A2:B2"].Merge = true;
            sheet.Cells["C2"].Value    = ":";
            sheet.Cells["D2"].Value    = viewModel.InvoiceNo;
            sheet.Cells["D2:E2"].Merge = true;

            sheet.Cells[$"{colCtns}2"].Value          = "Date";
            sheet.Cells[$"{colPcs}2"].Value           = ":";
            sheet.Cells[$"{colQty}2"].Value           = viewModel.CreatedUtc.ToString("MMM dd, yyyy.");
            sheet.Cells[$"{colQty}2:{colNnw}2"].Merge = true;

            sheet.Cells[$"A2:{colNnw}2"].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thick;

            sheet.Cells["A4"].Value    = "SHIPPING METHOD";
            sheet.Cells["A4:B4"].Merge = true;
            sheet.Cells["C4"].Value    = ":";
            sheet.Cells["D4"].Value    = viewModel.ShipmentMode;
            sheet.Cells["D4:E4"].Merge = true;

            var           cartons       = new List <GarmentPackingListDetailViewModel>();
            double        grandTotal    = 0;
            var           arraySubTotal = new Dictionary <String, double>();
            List <string> cartonNumbers = new List <string>();


            var index              = 8;
            var indexHeader        = 5;
            var afterSubTotalIndex = 0;

            foreach (var item in newItems2)
            {
                var sizeIndex  = index + 1;
                var valueIndex = sizeIndex + 1;

                #region Item
                sheet.Cells[$"A{indexHeader}"].Value = "RO No";
                sheet.Cells[$"A{indexHeader}:B{indexHeader}"].Merge = true;
                sheet.Cells[$"C{indexHeader}"].Value = ":";
                sheet.Cells[$"D{indexHeader}"].Value = item.RONo;
                sheet.Cells[$"D{indexHeader}:H{indexHeader}"].Merge = true;

                sheet.Cells[$"I{indexHeader}"].Value = "ARTICLE";
                sheet.Cells[$"I{indexHeader}:O{indexHeader}"].Merge = true;
                sheet.Cells[$"P{indexHeader}"].Value = ":";
                sheet.Cells[$"Q{indexHeader}"].Value = item.Article;
                sheet.Cells[$"Q{indexHeader}:{colNnw}{indexHeader}"].Merge = true;

                sheet.Cells[$"A{indexHeader + 1}"].Value = "BUYER";
                sheet.Cells[$"A{indexHeader + 1}:B{indexHeader + 1}"].Merge = true;
                sheet.Cells[$"C{indexHeader + 1}"].Value = ":";
                sheet.Cells[$"D{indexHeader + 1}"].Value = viewModel.BuyerAgent.Name;
                sheet.Cells[$"D{indexHeader + 1}:H{indexHeader + 1}"].Merge = true;

                sheet.Cells[$"I{indexHeader + 1}"].Value = "DESCRIPTION OF GOODS";
                sheet.Cells[$"I{indexHeader + 1}:O{indexHeader + 1}"].Merge = true;
                sheet.Cells[$"P{indexHeader + 1}"].Value = ":";
                sheet.Cells[$"Q{indexHeader + 1}"].Value = item.ComodityDescription;
                sheet.Cells[$"Q{indexHeader + 1}:{colNnw}{indexHeader + 1}"].Merge = true;
                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }

                sheet.Cells[$"A{index}"].Value = "CARTON NO.";
                sheet.Cells[$"A{index}:A{index + 1}"].Merge = true;
                sheet.Cells[$"A{index}:A{index}"].Style.VerticalAlignment             = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"A{index}:A{index}"].Style.HorizontalAlignment           = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"A{index}:{colNnw}{index}"].Style.Border.Top.Style       = OfficeOpenXml.Style.ExcelBorderStyle.Double;
                sheet.Cells[$"A{index}:{colNnw}{index}"].Style.Border.Bottom.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                sheet.Cells[$"A{index}:A{index + 1}"].Style.Border.Left.Style         = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                sheet.Cells[$"A{index}:{colNnw}{index + 1}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                sheet.Column(GetColNumberFromName("A")).Width = 8;

                sheet.Cells[$"B{index}"].Value = "COLOUR";
                sheet.Cells[$"B{index}:B{index + 1}"].Merge = true;
                sheet.Cells[$"B{index}:B{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"B{index}:B{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Column(GetColNumberFromName("B")).Width = 5;

                sheet.Cells[$"C{index}"].Value = "STYLE";
                sheet.Cells[$"C{index}:C{index + 1}"].Merge = true;
                sheet.Cells[$"C{index}:C{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"C{index}:C{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Column(GetColNumberFromName("C")).Width = 5;

                sheet.Cells[$"D{index}"].Value = "ORDER NO.";
                sheet.Cells[$"D{index}:D{index + 1}"].Merge = true;
                sheet.Cells[$"D{index}:D{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"D{index}:D{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Column(GetColNumberFromName("D")).Width = 7;

                sheet.Cells[$"E{index}"].Value = "SIZE";
                sheet.Cells[$"E{index}:{col}{index}"].Merge = true;
                sheet.Cells[$"E{index}:{col}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colCtns}{index}"].Value                      = "CTNS";
                sheet.Column(GetColNumberFromName(colCtns)).Width           = 5;
                sheet.Cells[$"{colCtns}{index}:{colCtns}{index + 1}"].Merge = true;
                sheet.Cells[$"{colCtns}{index}:{colCtns}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colCtns}{index}:{colCtns}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colPcs}{index}"].Value                     = "@";
                sheet.Column(GetColNumberFromName(colPcs)).Width          = 5;
                sheet.Cells[$"{colPcs}{index}:{colPcs}{index + 1}"].Merge = true;
                sheet.Cells[$"{colPcs}{index}:{colPcs}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colPcs}{index}:{colPcs}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colQty}{index}"].Value                     = "QTY";
                sheet.Column(GetColNumberFromName(colQty)).Width          = 4;
                sheet.Cells[$"{colQty}{index}:{colQty}{index + 1}"].Merge = true;
                sheet.Cells[$"{colQty}{index}:{colQty}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colQty}{index}:{colQty}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colSatuan}{index}"].Value                        = "SATUAN";
                sheet.Column(GetColNumberFromName(colSatuan)).Width             = 4;
                sheet.Cells[$"{colSatuan}{index}:{colSatuan}{index + 1}"].Merge = true;
                sheet.Cells[$"{colSatuan}{index}:{colSatuan}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colSatuan}{index}:{colSatuan}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colGw}{index}"].Value                    = "GW";
                sheet.Column(GetColNumberFromName(colGw)).Width         = 4;
                sheet.Cells[$"{colGw}{index}:{colGw}{index + 1}"].Merge = true;
                sheet.Cells[$"{colGw}{index}:{colGw}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colGw}{index}:{colGw}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colNw}{index}"].Value                    = "NW";
                sheet.Column(GetColNumberFromName(colNw)).Width         = 4;
                sheet.Cells[$"{colNw}{index}:{colNw}{index + 1}"].Merge = true;
                sheet.Cells[$"{colNw}{index}:{colNw}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colNw}{index}:{colNw}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colNnw}{index}"].Value                     = "NNW";
                sheet.Column(GetColNumberFromName(colNnw)).Width          = 4;
                sheet.Cells[$"{colNnw}{index}:{colNnw}{index + 1}"].Merge = true;
                sheet.Cells[$"{colNnw}{index}:{colNnw}{index}"].Style.VerticalAlignment   = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                sheet.Cells[$"{colNnw}{index}:{colNnw}{index}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var colSize = GetColNameFromIndex(5 + i);
                    var size    = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    sheet.Cells[$"{colSize}{sizeIndex}"].Value = size.Key == 0 ? "" : size.Value;
                    sheet.Cells[$"{colSize}{sizeIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                }

                var    subCartons      = new List <GarmentPackingListDetailViewModel>();
                var    subGrossWeight  = new List <GarmentPackingListDetailViewModel>();
                var    subNetWeight    = new List <GarmentPackingListDetailViewModel>();
                var    subNetNetWeight = new List <GarmentPackingListDetailViewModel>();
                double subTotal        = 0;
                var    sizeSumQty      = new Dictionary <int, double>();
                foreach (var detail in item.Details)
                {
                    var ctnsQty      = detail.CartonQuantity;
                    var grossWeight  = detail.GrossWeight;
                    var netWeight    = detail.NetWeight;
                    var netNetWeight = detail.NetNetWeight;
                    if (cartonNumbers.Contains($"{detail.Index}-{detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty      = 0;
                        grossWeight  = 0;
                        netWeight    = 0;
                        netNetWeight = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Index}-{detail.Carton1}- {detail.Carton2}");
                    }
                    sheet.Cells[$"A{valueIndex}"].Value = $"{detail.Carton1}- {detail.Carton2}";
                    sheet.Cells[$"A{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"B{valueIndex}"].Value = detail.Colour;
                    sheet.Cells[$"B{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"C{valueIndex}"].Value = detail.Style;
                    sheet.Cells[$"C{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"D{valueIndex}"].Value = item.OrderNo;
                    sheet.Cells[$"D{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                    sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    colSize  = GetColNameFromIndex(5 + i);
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        sheet.Cells[$"{colSize}{valueIndex}"].Value       = quantity == 0 ? "" : quantity.ToString();
                        sheet.Column(GetColNumberFromName(colSize)).Width = 3.5;
                        sheet.Cells[$"{colSize}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    }

                    sheet.Cells[$"{colCtns}{valueIndex}"].Value = ctnsQty.ToString();
                    sheet.Cells[$"{colCtns}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colPcs}{valueIndex}"].Value = detail.QuantityPCS.ToString();
                    sheet.Cells[$"{colPcs}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;

                    sheet.Cells[$"{colQty}{valueIndex}"].Value = totalQuantity.ToString();
                    sheet.Cells[$"{colQty}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colSatuan}{valueIndex}"].Value = item.Uom.Unit;
                    sheet.Cells[$"{colSatuan}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colGw}{valueIndex}"].Value = string.Format("{0:n2}", detail.GrossWeight);
                    sheet.Cells[$"{colGw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colNw}{valueIndex}"].Value = string.Format("{0:n2}", detail.NetWeight);
                    sheet.Cells[$"{colNw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    sheet.Cells[$"{colNnw}{valueIndex}"].Value = string.Format("{0:n2}", detail.NetNetWeight);
                    sheet.Cells[$"{colNnw}{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    if (cartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        cartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                    }
                    if (subCartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        subCartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                        subGrossWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, GrossWeight = grossWeight
                        });
                        subNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetWeight = netWeight
                        });
                        subNetNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetNetWeight = netNetWeight
                        });
                    }
                    valueIndex++;
                }
                var sumValueIndex = 0;
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var colSize = GetColNameFromIndex(5 + i);
                    sumValueIndex = valueIndex + 1;
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }
                    sheet.Cells[$"D{valueIndex}"].Value = "SUMMARY";
                    sheet.Cells[$"D{valueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    sheet.Cells[$"{colSize}{valueIndex}"].Value             = quantity == 0 ? "" : quantity.ToString();
                }

                sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{valueIndex}:{colNnw}{valueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                if (!arraySubTotal.ContainsKey(item.Uom.Unit))
                {
                    arraySubTotal.Add(item.Uom.Unit, subTotal);
                }
                else
                {
                    arraySubTotal[item.Uom.Unit] += subTotal;
                }
                grandTotal += subTotal;

                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Merge = true;
                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Value = "SUB TOTAL";
                sheet.Cells[$"A{sumValueIndex}:{colPcs}{sumValueIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                sheet.Cells[$"{colQty}{sumValueIndex}"].Value = subTotal.ToString() + " " + item.Uom.Unit;
                sheet.Cells[$"{colQty}{sumValueIndex}:{colNnw}{sumValueIndex}"].Merge = true;
                sheet.Cells[$"{colQty}{sumValueIndex}"].Style.HorizontalAlignment     = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"A{sumValueIndex}:{colNnw}{sumValueIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{sumValueIndex}:{colNnw}{sumValueIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                afterSubTotalIndex = sumValueIndex + 1;

                var subCtns = subCartons.Sum(c => c.CartonQuantity);
                var subGw   = subGrossWeight.Sum(c => c.GrossWeight * c.CartonQuantity);
                var subNw   = subNetWeight.Sum(c => c.NetWeight * c.CartonQuantity);
                var subNnw  = subNetNetWeight.Sum(c => c.NetNetWeight * c.CartonQuantity);

                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Merge = true;
                sheet.Cells[$"A{afterSubTotalIndex}"].Value = $"      - Sub Ctns = {subCtns}       - Sub G.W. = {String.Format("{0:0.00}", subGw)} Kgs      - Sub N.W. = {String.Format("{0:0.00}", subNw)} Kgs     - Sub N.N.W. = {String.Format("{0:0.00}", subNnw)} Kgs";
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
                sheet.Cells[$"A{afterSubTotalIndex}:{colNnw}{afterSubTotalIndex}"].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;


                index       = afterSubTotalIndex + 3;
                indexHeader = afterSubTotalIndex + 1;
            }

            #region GrandTotal
            var grandTotalIndex = afterSubTotalIndex + 2;
            sheet.Cells[$"A{grandTotalIndex}:{colPcs}{grandTotalIndex}"].Merge = true;
            sheet.Cells[$"A{grandTotalIndex}:{colPcs}{grandTotalIndex}"].Value = "GRAND TOTAL";
            sheet.Cells[$"A{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Double;
            sheet.Cells[$"A{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Double;
            var grandTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
            sheet.Cells[$"{colQty}{grandTotalIndex}"].Value = grandTotalResult;
            sheet.Cells[$"{colQty}{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Merge = true;
            sheet.Cells[$"{colQty}{grandTotalIndex}:{colNnw}{grandTotalIndex}"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;


            var totalCtns         = cartons.Sum(c => c.CartonQuantity);
            var comodities        = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            var spellingWordIndex = grandTotalIndex + 2;
            sheet.Cells[$"A{spellingWordIndex}:{colNnw}{spellingWordIndex}"].Merge = true;
            sheet.Cells[$"A{spellingWordIndex}"].Value = $"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]";

            for (int i = 8; i < grandTotalIndex; i++)
            {
                sheet.Row(i).Height = 16;
            }

            #endregion

            #region Mark
            var shippingMarkIndex = spellingWordIndex + 2;
            var sideMarkIndex     = spellingWordIndex + 2;

            sheet.Cells[$"A{shippingMarkIndex}"].Value = "SHIPPING MARKS";
            sheet.Cells[$"A{shippingMarkIndex}:B{shippingMarkIndex}"].Merge = true;
            sheet.Cells[$"A{++shippingMarkIndex}"].Value = viewModel.ShippingMark;

            sheet.Cells[$"H{sideMarkIndex}"].Value = "SIDE MARKS";
            sheet.Cells[$"H{sideMarkIndex}:J{sideMarkIndex}"].Merge = true;
            sheet.Cells[$"H{++sideMarkIndex}"].Value = viewModel.SideMark;

            byte[] shippingMarkImage;
            if (!String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
                {
                    shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));
                    Image shipMarkImage          = byteArrayToImage(shippingMarkImage);
                    var   imageShippingMarkIndex = shippingMarkIndex + 1;

                    ExcelPicture excelPictureShipMarkImage = sheet.Drawings.AddPicture("ShippingMarkImage", shipMarkImage);
                    excelPictureShipMarkImage.From.Column = 0;
                    excelPictureShipMarkImage.From.Row    = imageShippingMarkIndex;
                    excelPictureShipMarkImage.SetSize(200, 200);
                }
            }

            byte[] sideMarkImage;
            if (!String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
                {
                    sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                    Image _sideMarkImage     = byteArrayToImage(sideMarkImage);
                    var   sideMarkImageIndex = sideMarkIndex + 1;

                    ExcelPicture excelPictureSideMarkImage = sheet.Drawings.AddPicture("SideMarkImage", _sideMarkImage);
                    excelPictureSideMarkImage.From.Column = 7;
                    excelPictureSideMarkImage.From.Row    = sideMarkImageIndex;
                    excelPictureSideMarkImage.SetSize(200, 200);
                }
            }

            #endregion

            #region Measurement
            var grossWeightIndex  = shippingMarkIndex + 13;
            var netWeightIndex    = grossWeightIndex + 1;
            var netNetWeightIndex = netWeightIndex + 1;
            var measurementIndex  = netNetWeightIndex + 1;

            sheet.Cells[$"A{grossWeightIndex}"].Value = "GROSS WEIGHT";
            sheet.Cells[$"A{grossWeightIndex}:B{grossWeightIndex}"].Merge = true;
            sheet.Cells[$"C{grossWeightIndex}"].Value = ":";
            sheet.Cells[$"D{grossWeightIndex}"].Value = viewModel.GrossWeight + " KGS";

            sheet.Cells[$"A{netWeightIndex}"].Value = "NET WEIGHT";
            sheet.Cells[$"A{netWeightIndex}:B{netWeightIndex}"].Merge = true;
            sheet.Cells[$"C{netWeightIndex}"].Value = ":";
            sheet.Cells[$"D{netWeightIndex}"].Value = viewModel.NettWeight + " KGS";

            sheet.Cells[$"A{netNetWeightIndex}"].Value = "NET NET WEIGHT";
            sheet.Cells[$"A{netNetWeightIndex}:B{netNetWeightIndex}"].Merge = true;
            sheet.Cells[$"C{netNetWeightIndex}"].Value = ":";
            sheet.Cells[$"D{netNetWeightIndex}"].Value = viewModel.NetNetWeight + " KGS";

            sheet.Cells[$"A{measurementIndex}"].Value = "MEASUREMENT";
            sheet.Cells[$"A{measurementIndex}:B{measurementIndex}"].Merge = true;
            sheet.Cells[$"C{measurementIndex}"].Value = ":";

            decimal totalCbm = 0;
            foreach (var measurement in viewModel.Measurements)
            {
                sheet.Cells[$"D{measurementIndex}"].Value = measurement.Length + " X ";
                sheet.Cells[$"D{measurementIndex}:E{measurementIndex}"].Merge = true;

                sheet.Cells[$"F{measurementIndex}"].Value = measurement.Width + " X ";
                sheet.Cells[$"F{measurementIndex}:G{measurementIndex}"].Merge = true;

                sheet.Cells[$"H{measurementIndex}"].Value = measurement.Height + " X ";
                sheet.Cells[$"H{measurementIndex}:I{measurementIndex}"].Merge = true;

                sheet.Cells[$"J{measurementIndex}"].Value = measurement.CartonsQuantity + " CTNS";
                sheet.Cells[$"J{measurementIndex}:K{measurementIndex}"].Merge = true;

                sheet.Cells[$"L{measurementIndex}"].Value = "=";

                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                sheet.Cells[$"M{measurementIndex}"].Value = string.Format("{0:N3} CBM", cbm);
                sheet.Cells[$"M{measurementIndex}:O{measurementIndex}"].Merge = true;

                measurementIndex++;
            }
            var totalMeasurementIndex = measurementIndex;
            sheet.Cells[$"D{totalMeasurementIndex}:O{totalMeasurementIndex}"].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
            sheet.Cells[$"D{totalMeasurementIndex}"].Value = "TOTAL";
            sheet.Cells[$"D{totalMeasurementIndex}:I{totalMeasurementIndex}"].Merge = true;

            sheet.Cells[$"J{totalMeasurementIndex}"].Value = viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .";
            sheet.Cells[$"J{totalMeasurementIndex}:K{totalMeasurementIndex}"].Merge = true;
            sheet.Cells[$"M{totalMeasurementIndex}"].Value = string.Format("{0:N3} CBM", totalCbm);
            sheet.Cells[$"L{totalMeasurementIndex}"].Value = "=";
            sheet.Cells[$"M{totalMeasurementIndex}:O{totalMeasurementIndex}"].Merge = true;

            #endregion

            #region remark
            var remarkIndex = totalMeasurementIndex + 1;
            sheet.Cells[$"A{remarkIndex}"].Value   = "REMARK";
            sheet.Cells[$"A{++remarkIndex}"].Value = viewModel.Remark;

            byte[] remarkImage;
            var    remarkImageIndex = remarkIndex + 1;
            if (!String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
                {
                    remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));
                    Image        _remarkImage            = byteArrayToImage(remarkImage);
                    ExcelPicture excelPictureRemarkImage = sheet.Drawings.AddPicture("RemarkImage", _remarkImage);
                    excelPictureRemarkImage.From.Column = 0;
                    excelPictureRemarkImage.From.Row    = remarkImageIndex;
                    excelPictureRemarkImage.SetSize(200, 200);
                }
            }
            #endregion

            sheet.Cells.Style.WrapText        = true;
            sheet.PrinterSettings.LeftMargin  = 0.39M;
            sheet.PrinterSettings.TopMargin   = 0;
            sheet.PrinterSettings.RightMargin = 0;
            sheet.PrinterSettings.Orientation = sizesCount ? eOrientation.Landscape : eOrientation.Portrait;

            MemoryStream stream = new MemoryStream();
            package.DoAdjustDrawings = false;
            package.SaveAs(stream);
            return(stream);
        }
示例#14
0
        public MemoryStream GeneratePdfTemplate(SalesInvoiceExportViewModel viewModel, int clientTimeZoneOffset)
        {
            const int MARGIN = 15;

            Font header_font     = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18);
            Font normal_font     = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font bold_font       = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font Title_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);

            Document     document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region Header

            #region Header_A
            PdfPTable headerTable_A  = new PdfPTable(3);
            PdfPTable headerTable_A1 = new PdfPTable(1);
            PdfPTable headerTable_A2 = new PdfPTable(1);
            PdfPTable headerTable_A3 = new PdfPTable(1);
            headerTable_A.SetWidths(new float[] { 10f, 10f, 10f });
            headerTable_A.WidthPercentage = 100;

            PdfPCell cellHeaderBody_A = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_A1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_A2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_A3 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellHeaderBody_A.Phrase = new Phrase("\n", normal_font);
            headerTable_A1.AddCell(cellHeaderBody_A);

            cellHeaderBody_A.Phrase = new Phrase("INVOICE NO : " + viewModel.SalesInvoiceNo, normal_font);
            headerTable_A1.AddCell(cellHeaderBody_A);

            cellHeader_A1.AddElement(headerTable_A1);
            headerTable_A.AddCell(cellHeader_A1);

            cellHeaderBody_A.Phrase = new Phrase("\n", normal_font);
            headerTable_A2.AddCell(cellHeaderBody_A);

            cellHeaderBody_A.Phrase = new Phrase("DATE : " + viewModel.SalesInvoiceDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
            headerTable_A2.AddCell(cellHeaderBody_A);

            cellHeader_A2.AddElement(headerTable_A2);
            headerTable_A.AddCell(cellHeader_A2);

            cellHeaderBody_A.Phrase = new Phrase("FM-PJ-00-03-006", normal_font);
            headerTable_A3.AddCell(cellHeaderBody_A);

            cellHeaderBody_A.Phrase = new Phrase("Page : " + "?????" + " of " + "?????", normal_font);
            headerTable_A3.AddCell(cellHeaderBody_A);

            cellHeader_A3.AddElement(headerTable_A3);
            headerTable_A.AddCell(cellHeader_A3);

            document.Add(headerTable_A);
            #endregion Header_A

            #region Header_B
            PdfPTable headerTable_B  = new PdfPTable(2);
            PdfPTable headerTable_B1 = new PdfPTable(1);
            PdfPTable headerTable_B2 = new PdfPTable(1);
            headerTable_B.SetWidths(new float[] { 10f, 10f });
            headerTable_B.WidthPercentage = 100;

            PdfPCell cellHeaderBody_B = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_B1 = new PdfPCell();
            PdfPCell cellHeader_B2 = new PdfPCell();

            cellHeaderBody_B.Phrase = new Phrase("SOLD BY ORDERS AND FOR ACCOUNT AND RISK OF MESSRS : " + viewModel.BuyerName + "\n" + viewModel.BuyerAddress, normal_font);
            headerTable_B1.AddCell(cellHeaderBody_B);

            cellHeader_B1.AddElement(headerTable_B1);
            headerTable_B.AddCell(cellHeader_B1);

            foreach (var detail in viewModel.SalesInvoiceExportDetails)
            {
                cellHeaderBody_B.Phrase = new Phrase("CONTRACT NO : " + detail.ContractNo, normal_font);
                headerTable_B2.AddCell(cellHeaderBody_B);
            }

            cellHeaderBody_B.Phrase = new Phrase("SHIPPED PER : " + viewModel.ShippedPer, normal_font);
            headerTable_B2.AddCell(cellHeaderBody_B);

            cellHeaderBody_B.Phrase = new Phrase("SAILING ON OR ABOUT : " + viewModel.SailingDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
            headerTable_B2.AddCell(cellHeaderBody_B);

            cellHeaderBody_B.Phrase = new Phrase("FROM : " + viewModel.From, normal_font);
            headerTable_B2.AddCell(cellHeaderBody_B);

            cellHeaderBody_B.Phrase = new Phrase("TO : " + viewModel.To, normal_font);
            headerTable_B2.AddCell(cellHeaderBody_B);

            cellHeader_B2.AddElement(headerTable_B2);
            headerTable_B.AddCell(cellHeader_B2);

            document.Add(headerTable_B);
            #endregion Header_B

            #region Header_C
            PdfPTable headerTable_C  = new PdfPTable(2);
            PdfPTable headerTable_C1 = new PdfPTable(1);
            PdfPTable headerTable_C2 = new PdfPTable(1);
            headerTable_C.SetWidths(new float[] { 10f, 10f });
            headerTable_C.WidthPercentage = 100;

            PdfPCell cellHeaderBody_C = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_C1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader_C2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellHeaderBody_C.Phrase = new Phrase("\n", normal_font);
            headerTable_C1.AddCell(cellHeaderBody_C);

            cellHeaderBody_C.Phrase = new Phrase("LETTER OF CREDIT NUMBER  : " + viewModel.LetterOfCreditNumber, normal_font);
            headerTable_C1.AddCell(cellHeaderBody_C);

            cellHeaderBody_C.Phrase = new Phrase("ISSUED BY  : " + viewModel.IssuedBy, normal_font);
            headerTable_C1.AddCell(cellHeaderBody_C);

            cellHeader_C1.AddElement(headerTable_C1);
            headerTable_C.AddCell(cellHeader_C1);

            cellHeaderBody_C.Phrase = new Phrase("\n", normal_font);
            headerTable_C2.AddCell(cellHeaderBody_C);

            cellHeaderBody_C.Phrase = new Phrase("DATE : " + viewModel.LCDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
            headerTable_C2.AddCell(cellHeaderBody_C);

            cellHeaderBody_C.Phrase = new Phrase("", normal_font);
            headerTable_C1.AddCell(cellHeaderBody_C);

            cellHeader_C2.AddElement(headerTable_C2);
            headerTable_C.AddCell(cellHeader_C2);

            document.Add(headerTable_C);
            #endregion Header_C

            #endregion Header

            #region Body

            #region Body_A
            PdfPTable bodyTable_A = new PdfPTable(4);
            PdfPCell  bodyCell_A  = new PdfPCell();

            float[] widthsBody = new float[] { 20f, 8f, 8f, 10f };
            bodyTable_A.SetWidths(widthsBody);
            bodyTable_A.WidthPercentage = 100;

            bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER;

            bodyCell_A.Phrase = new Phrase("DESCRIPTION", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase("QUANTITY IN METERS", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase("UNIT PRICE IDR", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase("TOTAL PRICE IDR", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            double price           = 0;
            double totalPrice      = 0;
            double grandTotalPrice = 0;
            double totalLength     = 0;

            foreach (var detail in viewModel.SalesInvoiceExportDetails)
            {
                //TAMBAHIN DESCRIPTION
                bodyCell_A.HorizontalAlignment = Element.ALIGN_LEFT;

                bodyCell_A.Phrase = new Phrase(detail.Description, normal_font);
                bodyTable_A.AddCell(bodyCell_A);

                bodyCell_A.Phrase = new Phrase("", normal_font);
                bodyTable_A.AddCell(bodyCell_A);

                bodyCell_A.Phrase = new Phrase("", normal_font);
                bodyTable_A.AddCell(bodyCell_A);

                bodyCell_A.Phrase = new Phrase("", normal_font);
                bodyTable_A.AddCell(bodyCell_A);

                foreach (var item in detail.SalesInvoiceExportItems)
                {
                    //14447 is rate to convert USD to IDR
                    price            = item.Price.GetValueOrDefault() * 14447;
                    totalPrice       = item.QuantityItem.GetValueOrDefault() * price;
                    grandTotalPrice += totalPrice;
                    totalLength     += item.QuantityItem.GetValueOrDefault();

                    bodyCell_A.HorizontalAlignment = Element.ALIGN_LEFT;
                    bodyCell_A.Phrase = new Phrase(item.ProductName, normal_font);
                    bodyTable_A.AddCell(bodyCell_A);

                    bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER;
                    bodyCell_A.Phrase = new Phrase(string.Format("{0:n2}", item.QuantityItem), normal_font);
                    bodyTable_A.AddCell(bodyCell_A);

                    bodyCell_A.Phrase = new Phrase(price.ToString("N2"), normal_font);
                    bodyTable_A.AddCell(bodyCell_A);

                    bodyCell_A.Phrase = new Phrase(totalPrice.ToString("N2"), normal_font);
                    bodyTable_A.AddCell(bodyCell_A);
                }
            }


            bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyCell_A.Phrase = new Phrase("TOTAL", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase(totalLength.ToString("N2"), bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase(".............", bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            bodyCell_A.Phrase = new Phrase(grandTotalPrice.ToString("N2"), bold_font);
            bodyTable_A.AddCell(bodyCell_A);

            document.Add(bodyTable_A);
            #endregion Body_A

            double convert = ((double)grandTotalPrice);
            string ENText  = NumberToTextEN.toWords(convert);

            #region Body_B
            PdfPTable bodyTable_B  = new PdfPTable(2);
            PdfPTable bodyTable_B1 = new PdfPTable(1);
            PdfPTable bodyTable_B2 = new PdfPTable(1);
            bodyTable_B.SetWidths(new float[] { 10f, 10f });
            bodyTable_B.WidthPercentage = 100;

            PdfPCell cellBody_B = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell bodyCell_A1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell bodyCell_A2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellBody_B.Phrase = new Phrase("", normal_font);
            bodyTable_B1.AddCell(cellBody_B);

            cellBody_B.Phrase = new Phrase("SAY : " + ENText + "Rupiah", normal_font);
            bodyTable_B1.AddCell(cellBody_B);

            cellBody_B.Phrase = new Phrase("SHIPPING MARKS : " + viewModel.ShippingRemark, normal_font);
            bodyTable_B1.AddCell(cellBody_B);

            bodyCell_A1.AddElement(bodyTable_B1);
            bodyTable_B.AddCell(bodyCell_A1);

            cellBody_B.Phrase = new Phrase("", normal_font);
            bodyTable_B2.AddCell(cellBody_B);

            cellBody_B.Phrase = new Phrase(viewModel.TermOfPaymentType + " " + viewModel.TermOfPaymentRemark, normal_font);
            bodyTable_B2.AddCell(cellBody_B);

            cellBody_B.Phrase = new Phrase("REMARKS : " + viewModel.Remark, normal_font);
            bodyTable_B2.AddCell(cellBody_B);

            bodyCell_A2.AddElement(bodyTable_B2);
            bodyTable_B.AddCell(bodyCell_A2);

            document.Add(bodyTable_B);
            #endregion Body_B

            #endregion Body

            #region Footer

            #region Footer_A
            PdfPTable footerTable_A  = new PdfPTable(1);
            PdfPTable footerTable_A1 = new PdfPTable(2);
            footerTable_A1.SetWidths(new float[] { 10f, 40f });
            footerTable_A1.WidthPercentage = 80;

            PdfPCell cellFooter_A = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell footerCell_A1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            footerTable_A.HorizontalAlignment = Element.ALIGN_LEFT;
            cellFooter_A.HorizontalAlignment  = Element.ALIGN_LEFT;

            cellFooter_A.Phrase = new Phrase("", normal_font);
            footerTable_A1.AddCell(cellFooter_A);
            cellFooter_A.Phrase = new Phrase("", normal_font);
            footerTable_A1.AddCell(cellFooter_A);

            cellFooter_A.Phrase = new Phrase("", normal_font);
            footerTable_A1.AddCell(cellFooter_A);
            cellFooter_A.Phrase = new Phrase("", normal_font);
            footerTable_A1.AddCell(cellFooter_A);

            foreach (var detail in viewModel.SalesInvoiceExportDetails)
            {
                cellFooter_A.Phrase = new Phrase("GROSS WEIGHT", normal_font);
                footerTable_A1.AddCell(cellFooter_A);
                cellFooter_A.Phrase = new Phrase(" :    " + detail.GrossWeight + " " + detail.WeightUom + "S", normal_font);
                footerTable_A1.AddCell(cellFooter_A);

                cellFooter_A.Phrase = new Phrase("NETT WEIGHT", normal_font);
                footerTable_A1.AddCell(cellFooter_A);
                cellFooter_A.Phrase = new Phrase(" :    " + detail.NetWeight + " " + detail.WeightUom + "S", normal_font);
                footerTable_A1.AddCell(cellFooter_A);

                cellFooter_A.Phrase = new Phrase("TOTAL MEASS.", normal_font);
                footerTable_A1.AddCell(cellFooter_A);
                cellFooter_A.Phrase = new Phrase(" :    " + detail.TotalMeas + " " + detail.TotalUom, normal_font);
                footerTable_A1.AddCell(cellFooter_A);
            }

            footerCell_A1.AddElement(footerTable_A1);
            footerTable_A.AddCell(footerCell_A1);

            document.Add(footerTable_A);
            #endregion Footer_A

            #region Footer_B
            PdfPTable footerTable_B  = new PdfPTable(1);
            PdfPTable footerTable_B1 = new PdfPTable(1);

            PdfPCell cellFooter_B = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell footerCell_B1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            footerTable_B.HorizontalAlignment = Element.ALIGN_CENTER;
            cellFooter_B.HorizontalAlignment  = Element.ALIGN_RIGHT;

            cellFooter_B.Phrase = new Phrase("\n\n\n ( " + viewModel.Authorized + " )", normal_font);
            footerTable_B1.AddCell(cellFooter_B);

            cellFooter_B.Phrase = new Phrase("AUTHORIZED SIGNATURE", normal_font);
            footerTable_B1.AddCell(cellFooter_B);

            footerCell_B1.AddElement(footerTable_B1);
            footerTable_B.AddCell(footerCell_B1);

            document.Add(footerTable_B);
            #endregion Footer_B

            #endregion Footer

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
示例#15
0
        public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel)
        {
            //int maxSizesCount = viewModel.Items == null || viewModel.Items.Count < 1 ? 0 : viewModel.Items.Max(i => i.Details == null || i.Details.Count < 1 ? 0 : i.Details.Max(d => d.Sizes == null || d.Sizes.Count < 1 ? 0 : d.Sizes.GroupBy(g => g.Size.Id).Count()));

            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items)
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Carton1).ToList();

            foreach (var x in viewModel.Items.OrderBy(o => o.RONo))
            {
                if (newItems.Count == 0)
                {
                    newItems.Add(x);
                }
                else
                {
                    if (newItems.Last().RONo == x.RONo && newItems.Last().OrderNo == x.OrderNo)
                    {
                        foreach (var d in x.Details.OrderBy(a => a.Carton1))
                        {
                            newItems.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Uom                 = a.Uom,
                        }).Single(a => a.RONo == x.RONo && a.OrderNo == x.OrderNo && a.Id == x.Id);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        foreach (var d in x.Details.OrderBy(a => a.Carton1))
                        {
                            y.Details.Add(d);
                        }
                        newItems.Add(y);
                    }
                }
            }
            var sizesCount = false;

            foreach (var item in newItems.OrderBy(a => a.RONo))
            {
                var sizesMax = new Dictionary <int, string>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1))
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizesMax[size.Size.Id] = size.Size.Size;
                    }
                }
                if (sizesMax.Count > 11)
                {
                    sizesCount = true;
                }
            }
            int SIZES_COUNT = sizesCount ? 20 : 11;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(sizesCount ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 70, 30);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentPackingListDraftPDFTemplatePageEvent(_identityProvider, viewModel);

            document.Open();
            PdfContentByte cb = writer.DirectContent;

            PdfPCell cellBorderBottomRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellBorderBottom = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            var    cartons    = new List <GarmentPackingListDetailViewModel>();
            double grandTotal = 0;

            var           arraySubTotal = new Dictionary <String, double>();
            List <string> cartonNumbers = new List <string>();



            //foreach (var d in newDetails)
            //{
            //    if (newItems.Count == 0)
            //    {
            //        var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
            //        i.Details = new List<GarmentPackingListDetailViewModel>();
            //        i.Details.Add(d);
            //        newItems.Add(i);
            //    }
            //    else
            //    {
            //        if (newItems.Last().Id == d.PackingListItemId)
            //        {
            //            newItems.Last().Details.Add(d);
            //        }
            //        else
            //        {
            //            var y = viewModel.Items.Select(a=> new GarmentPackingListItemViewModel {
            //                Id =a.Id, RONo=a.RONo, Article=a.Article, BuyerAgent=a.BuyerAgent, ComodityDescription=a.ComodityDescription,
            //                OrderNo=a.OrderNo, AVG_GW=a.AVG_GW, AVG_NW=a.AVG_NW})
            //                .Single(a => a.Id == d.PackingListItemId);
            //            y.Details = new List<GarmentPackingListDetailViewModel>();
            //            y.Details.Add(d);
            //            newItems.Add(y);
            //        }
            //    }
            //}

            document.Add(new Paragraph("SHIPPING METHOD : " + viewModel.ShipmentMode + "\n", normal_font));

            foreach (var item in newItems.OrderBy(a => a.RONo))
            {
                #region Item

                PdfPTable tableItem = new PdfPTable(6);
                tableItem.SetWidths(new float[] { 2f, 0.2f, 2.8f, 2f, 0.2f, 2.8f });
                PdfPCell cellItemContent = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };

                cellItemContent.Phrase = new Phrase("RO No", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.RONo, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("ARTICLE", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.Article, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("BUYER", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.BuyerAgent.Name, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.ComodityDescription, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);

                new PdfPCell(tableItem);
                tableItem.ExtendLastRow = false;
                document.Add(tableItem);

                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }

                PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + 11);
                var       width       = new List <float> {
                    2f, 3.5f, 4f, 4f
                };
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    width.Add(1f);
                }
                width.AddRange(new List <float> {
                    1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f
                });
                tableDetail.SetWidths(width.ToArray());

                PdfPCell cellDetailLine = new PdfPCell()
                {
                    Border = Rectangle.BOTTOM_BORDER, Colspan = 20, Padding = 0.5f, Phrase = new Phrase("")
                };
                tableDetail.AddCell(cellDetailLine);
                tableDetail.AddCell(cellDetailLine);

                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = SIZES_COUNT;
                cellBorderBottomRight.Rowspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("UNIT", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Rowspan = 1;

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f));
                    cellBorderBottomRight.Rowspan = 1;
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                var subCartons      = new List <GarmentPackingListDetailViewModel>();
                var subGrossWeight  = new List <GarmentPackingListDetailViewModel>();
                var subNetWeight    = new List <GarmentPackingListDetailViewModel>();
                var subNetNetWeight = new List <GarmentPackingListDetailViewModel>();

                double subTotal   = 0;
                var    sizeSumQty = new Dictionary <int, double>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1))
                {
                    var ctnsQty      = detail.CartonQuantity;
                    var grossWeight  = detail.GrossWeight;
                    var netWeight    = detail.NetWeight;
                    var netNetWeight = detail.NetNetWeight;
                    if (cartonNumbers.Contains($"{detail.Index}-{detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty      = 0;
                        grossWeight  = 0;
                        netWeight    = 0;
                        netNetWeight = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Index}-{detail.Carton1}- {detail.Carton2}");
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.Uom.Unit, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);

                    if (cartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        cartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                    }
                    if (subCartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2 && c.Index == detail.Index) < 0)
                    {
                        subCartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                        subGrossWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, GrossWeight = grossWeight
                        });
                        subNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetWeight = netWeight
                        });
                        subNetNetWeight.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = detail.CartonQuantity, NetNetWeight = netNetWeight
                        });
                    }
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.5f));

                    tableDetail.AddCell(cellBorderBottomRight);
                }
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);


                if (!arraySubTotal.ContainsKey(item.Uom.Unit))
                {
                    arraySubTotal.Add(item.Uom.Unit, subTotal);
                }
                else
                {
                    arraySubTotal[item.Uom.Unit] += subTotal;
                }
                grandTotal += subTotal;

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 7,
                    Padding = 5,
                    Phrase  = new Phrase("SUB TOTAL ....................................................................................................................................................................... ", normal_font)
                });
                cellBorderBottom.Phrase  = new Phrase(subTotal.ToString() + " " + item.Uom.Unit, normal_font);
                cellBorderBottom.Colspan = 2;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Phrase  = new Phrase("", normal_font);
                cellBorderBottom.Colspan = 3;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Colspan = 1;

                var subCtns = subCartons.Sum(c => c.CartonQuantity);
                var subGw   = subGrossWeight.Sum(c => c.GrossWeight * c.CartonQuantity);
                var subNw   = subNetWeight.Sum(c => c.NetWeight * c.CartonQuantity);
                var subNnw  = subNetNetWeight.Sum(c => c.NetNetWeight * c.CartonQuantity);

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 11,
                    Phrase  = new Phrase($"      - Sub Ctns = {subCtns}           - Sub G.W. = {String.Format("{0:0.00}", subGw)} Kgs           - Sub N.W. = {String.Format("{0:0.00}", subNw)} Kgs            - Sub N.N.W. = {String.Format("{0:0.00}", subNnw)} Kgs", normal_font)
                });

                new PdfPCell(tableDetail);
                tableDetail.ExtendLastRow = false;
                //tableDetail.KeepTogether = true;
                tableDetail.WidthPercentage = 95f;
                //tableDetail.HeaderRows = 3;
                document.Add(tableDetail);
            }

            #region GrandTotal

            PdfPTable tableGrandTotal = new PdfPTable(2);
            tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 5f });
            PdfPCell cellHeaderLine = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("")
            };

            tableGrandTotal.AddCell(cellHeaderLine);
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.BOTTOM_BORDER,
                Padding = 5,
                Phrase  = new Phrase("GRAND TOTAL .......................................................................................................................................................................", normal_font)
            });
            var grandTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border              = Rectangle.BOTTOM_BORDER,
                Padding             = 5,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase              = new Phrase(grandTotalResult, normal_font)
            });
            tableGrandTotal.AddCell(cellHeaderLine);
            var totalCtns  = cartons.Sum(c => c.CartonQuantity);
            var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 2,
                Padding = 5,
                Phrase  = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]", normal_font)
            });

            new PdfPCell(tableGrandTotal);
            tableGrandTotal.ExtendLastRow   = false;
            tableGrandTotal.WidthPercentage = 95f;
            tableGrandTotal.SpacingAfter    = 5f;
            document.Add(tableGrandTotal);

            #endregion

            #region Mark

            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 1f, 1f });

            PdfPCell cellShippingMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font);
            chunkShippingMark.SetUnderline(0.5f, -1);
            Phrase phraseShippingMark = new Phrase();
            phraseShippingMark.Add(chunkShippingMark);
            phraseShippingMark.Add(new Chunk("     :", normal_font));
            cellShippingMark.AddElement(phraseShippingMark);
            cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font));
            tableMark.AddCell(cellShippingMark);

            PdfPCell cellSideMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font);
            chunkSideMark.SetUnderline(0.5f, -1);
            Phrase phraseSideMark = new Phrase();
            phraseSideMark.Add(chunkSideMark);
            phraseSideMark.Add(new Chunk("     :", normal_font));
            cellSideMark.AddElement(phraseSideMark);
            cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font)
            {
            });
            tableMark.AddCell(cellSideMark);
            var    noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z";
            byte[] shippingMarkImage;
            if (String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                viewModel.ShippingMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
            {
                shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));

                Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);
                if (shipMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / shipMarkImage.Width;
                    shipMarkImage.ScalePercent(percentage * 100);
                    PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
                    shipMarkImageCell.Border = Rectangle.NO_BORDER;
                    tableMark.AddCell(shipMarkImageCell);
                }
            }

            byte[] sideMarkImage;
            if (String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                viewModel.SideMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
            {
                sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);
                if (_sideMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / _sideMarkImage.Width;
                    _sideMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
                _sideMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark.AddCell(_sideMarkImageCell);
            }

            new PdfPCell(tableMark);
            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 5f;
            document.Add(tableMark);

            #endregion

            #region Measurement

            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.GrossWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NettWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NetNetWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 2f, 2f, 2f, 2f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm = 0;
            foreach (var measurement in viewModel.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Length) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Width) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Height) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N3} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N3} CBM", totalCbm), normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);

            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            var paddingRight = SIZES_COUNT > 11 ? 400 : 200;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = paddingRight
            });

            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase("REMARK :", normal_font_underlined)
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase(viewModel.Remark, normal_font)
            });
            byte[] remarkImage;
            if (String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                viewModel.RemarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
            {
                remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));

                Image images = Image.GetInstance(imgb: remarkImage);

                if (images.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / images.Width;
                    images.ScalePercent(percentage * 100);
                }

                PdfPCell imageCell = new PdfPCell(images);
                imageCell.Border  = Rectangle.NO_BORDER;
                imageCell.Colspan = 3;
                tableMeasurement.AddCell(imageCell);
            }

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);
            //document.Add(images);

            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }