Пример #1
0
        private void CreatePDF(string ruta)
        {
            try
            {
                using (FileStream msReport = new FileStream(ruta, FileMode.Create))
                {
                    //step 1
                    using (Document pdfDoc = new Document(PageSize.LETTER, 22f, 10f, 180f, 40f))
                    {
                        try
                        {
                            // step 2
                            PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                            ITextOEN  ITE       = new ITextOEN();
                            ITE.NombreDoc       = "ORDEN DE ENTRADA OEN";
                            ITE.NoDoc           = OENGralSeleccionada.Id.ToString();
                            ITE.CodigoDoc       = OENGralSeleccionada.CODIGODEBARRAS;
                            ITE.FechaDoc        = OENGralSeleccionada.FECHA;
                            ITE.NombreProveedor = ProveedorSeleccionado.NOMBRE;
                            ITE.total           = totales;
                            pdfWriter.PageEvent = ITE;
                            //open the stream
                            pdfDoc.Open();
                            #region tablas
                            //     Conv conv = new Conv();
                            PdfPTable NombreColumnas2 = new PdfPTable(5);
                            NombreColumnas2.TotalWidth      = pdfDoc.PageSize.Width - 90f;
                            NombreColumnas2.LockedWidth     = true;
                            NombreColumnas2.WidthPercentage = 70;
                            float[] widths2 = new float[] { 1f, 4f, 8f, 1f, 2 };
                            NombreColumnas2.SetWidths(widths2);

                            #region foreach
                            foreach (oen_indiv partida in OENGralSeleccionada.PARTIDAS)
                            {
                                productos pctos = new productos(partida.ID_PRODUCTO);


                                PdfPCell item = new PdfPCell(new Phrase(partida.ITEM.ToString(), ITextEvents.arial2));
                                item.HorizontalAlignment = 1;
                                item.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                //  item.BackgroundColor = BaseColor.LIGHT_GRAY;
                                NombreColumnas2.AddCell(item);

                                PdfPCell Catalogo;

                                Catalogo = new PdfPCell(new Phrase(pctos.CATALOGO, ITextEvents.arial2));
                                //  PdfPCell Catalogo = new PdfPCell(new Phrase(partida.ALIAS, ITextEvents.arial2));
                                Catalogo.FixedHeight         = 22f;
                                Catalogo.HorizontalAlignment = 0;
                                Catalogo.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                //  Catalogo.BackgroundColor = BaseColor.LIGHT_GRAY;
                                NombreColumnas2.AddCell(Catalogo);

                                PdfPCell Descrip = new PdfPCell(new Phrase(pctos.DESCRIPCION, ITextEvents.arial2));
                                Descrip.HorizontalAlignment = 0;
                                Descrip.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                //  Descrip.BackgroundColor = BaseColor.LIGHT_GRAY;
                                NombreColumnas2.AddCell(Descrip);

                                PdfPCell Cantidad = new PdfPCell(new Phrase(partida.QTY.ToString(), ITextEvents.arial2));
                                Cantidad.HorizontalAlignment = 1;
                                Cantidad.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                //  Cantidad.BackgroundColor = BaseColor.LIGHT_GRAY;
                                NombreColumnas2.AddCell(Cantidad);

                                PdfPCell Factura = new PdfPCell(new Phrase(partida.FACTURA_PROVEEDOR, ITextEvents.arial2));
                                Factura.HorizontalAlignment = 1;
                                Factura.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                //  Cantidad.BackgroundColor = BaseColor.LIGHT_GRAY;
                                NombreColumnas2.AddCell(Factura);
                            }
                            #endregion

                            PdfPCell espacio1 = new PdfPCell();
                            espacio1.FixedHeight = 8F;
                            espacio1.Colspan     = 6;
                            espacio1.Border      = 0;
                            NombreColumnas2.AddCell(espacio1);
                            NombreColumnas2.DefaultCell.PaddingBottom = 60;
                            NombreColumnas2.DefaultCell.PaddingTop    = 60;
                            pdfDoc.Add(NombreColumnas2);
                            #endregion tablas
                            pdfDoc.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Cierre el pdf");
                        }
                        finally
                        {
                        }
                    }
                }
            }
            catch
            { MessageBox.Show("Cierre el pdf"); }
        }
        private void BtnExportPdf_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter   = "PDF File(*.pdf)|*.pdf";
            saveDialog.FileName = "";
            if (saveDialog.ShowDialog() == true)
            {
                // PDF 변환
                try
                {
                    // 0.PDF 사용 폰트 설정
                    string   nanumPath    = Path.Combine(Environment.CurrentDirectory, @"NanumGothic.ttf");
                    BaseFont nanumBase    = BaseFont.CreateFont(nanumPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    var      nanumTitle   = new iTextSharp.text.Font(nanumBase, 20f); // 20 타이틀용 나눔폰트
                    var      nanumContent = new iTextSharp.text.Font(nanumBase, 12f); // 12 내용 나눔폰트

                    //iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
                    string pdfFilePath = saveDialog.FileName;

                    // 1. PDF 객체 생성
                    iTextSharp.text.Document pdfDoc = new Document(PageSize.A4);

                    // 2. PDF 내용 만들기
                    Paragraph title    = new Paragraph("부경대 재고관리시스템(SMS)\n", nanumTitle);
                    Paragraph subTitle = new Paragraph($"사용자리스트 exported : {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\n", nanumContent);

                    PdfPTable pdfTable = new PdfPTable(GrdData.Columns.Count);
                    pdfTable.WidthPercentage = 100; // 전체 사이즈 다 사용

                    // 그리드 헤더 작업
                    foreach (DataGridColumn column in GrdData.Columns)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.Header.ToString(), nanumContent));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;

                        pdfTable.AddCell(cell);
                    }

                    // 각 셀의 사이즈 조정
                    float[] columnsWidth = new float[] { 5f, 15f, 10f, 15f, 30f, 12f, 10f };
                    pdfTable.SetWidths(columnsWidth);

                    // 그리드 Row 작업
                    foreach (var item in GrdData.Items)
                    {
                        if (item is Model.User)
                        {
                            var temp = item as Model.User;
                            // UserId
                            PdfPCell cell = new PdfPCell(new Phrase(temp.UserID.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            pdfTable.AddCell(cell);
                            // UserIdentityNumber
                            cell = new PdfPCell(new Phrase(temp.UserIdentityNumber.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserSurname
                            cell = new PdfPCell(new Phrase(temp.UserSurname.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserName
                            cell = new PdfPCell(new Phrase(temp.UserName.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserEmail
                            cell = new PdfPCell(new Phrase(temp.UserEmail.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserAdmin
                            cell = new PdfPCell(new Phrase(temp.UserAdmin.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserActivated
                            cell = new PdfPCell(new Phrase(temp.UserActivated.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                        }
                    }

                    // 3. PDF 파일 생성
                    using (FileStream stream = new FileStream(pdfFilePath, FileMode.OpenOrCreate))
                    {
                        PdfWriter.GetInstance(pdfDoc, stream);
                        pdfDoc.Open();

                        // 2번에서 만든 내용 추가
                        pdfDoc.Add(title);
                        pdfDoc.Add(subTitle);
                        pdfDoc.Add(pdfTable);

                        pdfDoc.Close();
                        stream.Close(); // option
                    }

                    Commons.ShowMessageAsync("PDF 변환", "PDF 익스포트 성공했습니다.");
                }
                catch (Exception ex)
                {
                    Commons.LOGGER.Error($"예외발생 BtnExportPdf_Click: {ex}");
                }
            }
        }
        public MemoryStream GeneratePdfTemplate(CostCalculationRetailViewModel viewModel)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font_8 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font     font_9      = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            DateTime now         = DateTime.Now;

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

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

            float margin          = 10;
            float printedOnHeight = 10;
            float startY          = 840 - margin;

            #region Header
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0);
            cb.SetFontAndSize(bf_bold, 12);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "COST CALCULATION RETAIL", 10, 805, 0);
            cb.EndText();
            #endregion

            #region Top
            PdfPTable table_top = new PdfPTable(9);
            table_top.TotalWidth = 500f;

            float[] top_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 0.1f, 2f };
            table_top.SetWidths(top_widths);

            PdfPCell cell_top = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2
            };
            PdfPCell cell_colon = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
            };
            PdfPCell cell_top_keterangan = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2, Colspan = 7
            };
            cell_colon.Phrase = new Phrase(":", normal_font);

            cell_top.Phrase = new Phrase("RO", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.RO}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("BUYER", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Buyer.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OL", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OLValue = viewModel.OL.Value ?? 0;
            string OL      = OLValue > 0 ? OLValue.ToString() + " menit" : OLValue.ToString();
            cell_top.Phrase = new Phrase($"{OL}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("ARTICLE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Article}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("DELIVERY", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.DeliveryDate.ToString("dd MMMM yyyy")}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 1", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL1Value = viewModel.OTL1.Value ?? 0;
            string OTL1      = OTL1Value > 0 ? OTL1Value.ToString() + " detik" : OTL1Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL1}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("STYLE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Style.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("SIZE RANGE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.SizeRange.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 2", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL2Value = viewModel.OTL2.Value ?? 0;
            string OTL2      = OTL2Value > 0 ? OTL2Value.ToString() + " detik" : OTL2Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL2}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("SEASON", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Season.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("EFFICIENCY", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Efficiency.Value}%", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 3", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL3Value = viewModel.OTL3.Value ?? 0;
            string OTL3      = OTL3Value > 0 ? OTL3Value.ToString() + " detik" : OTL3Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL3}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("COUNTER", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Counter.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("RISK", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Risk}%", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("TOTAL SMV", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double STD_HourValue = viewModel.SH_Cutting.Value + viewModel.SH_Finishing.Value + viewModel.SH_Sewing.Value;
            string STD_Hour      = STD_HourValue > 0 ? STD_HourValue.ToString() : STD_HourValue.ToString();
            cell_top.Phrase = new Phrase($"{STD_Hour}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("KETERANGAN", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top_keterangan.Phrase = new Phrase($"{viewModel.Description}", normal_font);
            table_top.AddCell(cell_top_keterangan);
            #endregion

            #region Draw Image
            float imageHeight;
            try
            {
                byte[] imageByte = Convert.FromBase64String(Base64.GetBase64File(viewModel.ImageFile));
                Image  image     = Image.GetInstance(imgb: imageByte);
                if (image.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 60 / image.Width;
                    image.ScalePercent(percentage * 100);
                }
                imageHeight = image.ScaledHeight;
                float imageY = 800 - imageHeight;
                image.SetAbsolutePosition(520, imageY);
                cb.AddImage(image, inlineImage: true);
            }
            catch (Exception)
            {
                imageHeight = 0;
            }
            #endregion

            #region Draw Top
            float row1Y = 800;
            table_top.WriteSelectedRows(0, -1, 10, row1Y, cb);
            #endregion

            #region Detail (Bottom, Column 1.2)
            PdfPTable table_detail = new PdfPTable(2);
            table_detail.TotalWidth = 280f;

            float[] detail_widths = new float[] { 1f, 1f };
            table_detail.SetWidths(detail_widths);

            PdfPCell cell_detail = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5, Rowspan = 4
            };

            double total = Convert.ToDouble(viewModel.OL.CalculatedValue + viewModel.OTL1.CalculatedValue + viewModel.OTL2.CalculatedValue + viewModel.OTL3.CalculatedValue);
            cell_detail.Phrase = new Phrase(
                "OL".PadRight(22) + ": " + viewModel.OL.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 1".PadRight(20) + ": " + viewModel.OTL1.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 2".PadRight(20) + ": " + viewModel.OTL2.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 3".PadRight(20) + ": " + viewModel.OTL3.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "Total".PadRight(22) + ": " + total + Environment.NewLine
                , normal_font);
            table_detail.AddCell(cell_detail);

            cell_detail = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5
            };
            cell_detail.Phrase = new Phrase("HPP", normal_font);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5
            };
            cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.HPP), font_9);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5
            };
            cell_detail.Phrase = new Phrase("Wholesale Price: HPP X 2.20", normal_font);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5
            };
            cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.WholesalePrice), font_9);
            table_detail.AddCell(cell_detail);
            #endregion

            #region Signature (Bottom, Column 1.2)
            PdfPTable table_signature = new PdfPTable(3);
            table_signature.TotalWidth = 280f;

            float[] signature_widths = new float[] { 1f, 1f, 1f };
            table_signature.SetWidths(signature_widths);

            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_signature.Phrase = new Phrase("Mengetahui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Menyetujui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Creative Director", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Marketing Director", normal_font);
            table_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);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("Anita Purnamaningrum", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ari Seputra", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Haenis Gunarto", normal_font);
            table_signature.AddCell(cell_signature);
            #endregion

            #region Price (Bottom, Column 2)
            PdfPTable table_price = new PdfPTable(5);
            table_price.TotalWidth = 280f;

            float[] price_widths = new float[] { 1.6f, 3f, 3f, 4f, 1f };
            table_price.SetWidths(price_widths);

            PdfPCell cell_price_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            PdfPCell cell_price_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            PdfPCell cell_price_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_price_center.Phrase = new Phrase("KET (X)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("HARGA (Rp)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("PEMBULATAN HARGA (Rp)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("KETERANGAN", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("", bold_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed20), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding20), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding20") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.1", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed21), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding21), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding21") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.2", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed22), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding22), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding22") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.3", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed23), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding23), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding23") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.4", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed24), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding24), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding24") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.5", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed25), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding25), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding25") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.6", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed26), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding26), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding26") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.7", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed27), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding27), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding27") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.8", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed28), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding28), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding28") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.9", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed29), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding29), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding29") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("3.0", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed30), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding30), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding30") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("Others", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(viewModel.RoundingOthers > 0 ? Number.ToRupiahWithoutSymbol(viewModel.RoundingOthers) : "", normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("RoundingOthers") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);
            #endregion

            #region Cost Calculation Material
            PdfPTable table_ccm = new PdfPTable(7);
            table_ccm.TotalWidth = 570f;

            float[] ccm_widths = new float[] { 1.25f, 3.5f, 4f, 9f, 3f, 4f, 4f };
            table_ccm.SetWidths(ccm_widths);

            PdfPCell cell_ccm_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            PdfPCell cell_ccm_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            PdfPCell cell_ccm_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_ccm_center.Phrase = new Phrase("NO", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("CATEGORIES", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("MATERIALS", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("QUANTITY", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("RP. PTC/PC", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("RP. TOTAL", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            double Total               = 0;
            float  row1Height          = imageHeight > table_top.TotalHeight ? imageHeight : table_top.TotalHeight;
            float  row2Y               = row1Y - row1Height - 10;
            float  calculatedHppHeight = 7;
            float  row3LeftHeight      = table_detail.TotalHeight + 5 + table_signature.TotalHeight;
            float  row3RightHeight     = table_price.TotalHeight;
            float  row3Height          = row3LeftHeight > row3RightHeight ? row3LeftHeight : row3RightHeight;
            float  remainingRow2Height = row2Y - 10 - row3Height - printedOnHeight - margin;
            float  allowedRow2Height   = row2Y - printedOnHeight - margin;
            for (int i = 0; i < viewModel.CostCalculationRetail_Materials.Count; i++)
            {
                cell_ccm_center.Phrase = new Phrase((i + 1).ToString(), normal_font);
                table_ccm.AddCell(cell_ccm_center);

                cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Category.SubCategory != null ? String.Format("{0} - {1}", viewModel.CostCalculationRetail_Materials[i].Category.Name, viewModel.CostCalculationRetail_Materials[i].Category.SubCategory) : viewModel.CostCalculationRetail_Materials[i].Category.Name, normal_font);
                table_ccm.AddCell(cell_ccm_left);

                cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Material.Name, normal_font);
                table_ccm.AddCell(cell_ccm_left);

                cell_ccm_left.Phrase = new Phrase(viewModel.CostCalculationRetail_Materials[i].Description, normal_font);
                table_ccm.AddCell(cell_ccm_left);

                cell_ccm_right.Phrase = new Phrase(String.Format("{0} {1}", viewModel.CostCalculationRetail_Materials[i].Quantity, viewModel.CostCalculationRetail_Materials[i].UOMQuantity.Name), normal_font);
                table_ccm.AddCell(cell_ccm_right);

                cell_ccm_right.Phrase = new Phrase(String.Format("{0}/{1}", Number.ToRupiahWithoutSymbol(viewModel.CostCalculationRetail_Materials[i].Price), viewModel.CostCalculationRetail_Materials[i].UOMPrice.Name), normal_font);
                table_ccm.AddCell(cell_ccm_right);

                cell_ccm_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.CostCalculationRetail_Materials[i].Total), normal_font);
                table_ccm.AddCell(cell_ccm_right);
                Total += viewModel.CostCalculationRetail_Materials[i].Total;

                float currentHeight = table_ccm.TotalHeight;
                if (currentHeight / remainingRow2Height > 1)
                {
                    if (currentHeight / allowedRow2Height > 1)
                    {
                        PdfPRow headerRow = table_ccm.GetRow(0);
                        PdfPRow lastRow   = table_ccm.GetRow(table_ccm.Rows.Count - 1);
                        table_ccm.DeleteLastRow();
                        table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);
                        table_ccm.DeleteBodyRows();
                        this.DrawPrintedOn(now, bf, cb);
                        document.NewPage();
                        table_ccm.Rows.Add(headerRow);
                        table_ccm.Rows.Add(lastRow);
                        table_ccm.CalculateHeights();
                        row2Y = startY;
                        remainingRow2Height = row2Y - 10 - row3Height - printedOnHeight - margin;
                        allowedRow2Height   = row2Y - printedOnHeight - margin;
                    }
                }
            }

            cell_ccm_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2, Colspan = 6
            };
            cell_ccm_right.Phrase = new Phrase("TOTAL", bold_font_8);
            table_ccm.AddCell(cell_ccm_right);
            cell_ccm_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            cell_ccm_right.Phrase = new Phrase(Number.ToRupiah(Total), bold_font_8);
            table_ccm.AddCell(cell_ccm_right);
            #endregion

            #region Draw Middle and Bottom
            table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);

            float row3Y = row2Y - table_ccm.TotalHeight - 10;
            float remainingRow3Height = row3Y - printedOnHeight - margin;
            if (remainingRow3Height < row3Height)
            {
                this.DrawPrintedOn(now, bf, cb);
                row3Y = startY;
                document.NewPage();
            }

            #region Calculated HPP
            float calculatedHppY = row3Y - calculatedHppHeight;
            cb.BeginText();
            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "KALKULASI HPP: (OL + OTL1 + OTL2 + FABRIC + ACC) + ((OL + OTL1 + OTL2 + FABRIC + ACC) * Risk)", 10, calculatedHppY, 0);
            cb.EndText();
            #endregion

            float table_detailY = calculatedHppY - 5;
            table_detail.WriteSelectedRows(0, -1, 10, table_detailY, cb);

            float table_signatureY = table_detailY - row3Height + table_signature.TotalHeight;
            table_signature.WriteSelectedRows(0, -1, 10, table_signatureY, cb);

            table_price.WriteSelectedRows(0, -1, 300, table_detailY, cb);

            this.DrawPrintedOn(now, bf, cb);
            #endregion

            document.Close();

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

            return(stream);
        }
Пример #4
0
        //
        /// <summary>
        /// Cria Documento de Fatura para Exportar PDF
        /// </summary>
        /// <param name="dtTable"></param>
        /// <param name="strHeader"></param>
        void ExportaPDF(DataTable dtTable, string strHeader)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter      = "PDF Files|*.pdf";
            dlg.FilterIndex = 0;

            string fileName = string.Empty;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
                Document  document = new Document(iTextSharp.text.PageSize.A4, 20, 20, 42, 35);
                PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None));

                //MessageBox.Show("arquivo salvo em " + fileName);
                //System.IO.FileStream fs = new FileStream(myDocument, new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                //Document document = new Document();
                //document.SetPageSize(iTextSharp.text.PageSize.A4);
                //PdfWriter writer = PdfWriter.GetInstance(document, fs);
                //
                document.Open();
                //
                //documento aberto para escrita
                //
                //BaseFont helvTable = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                //Font fontTable = new Font(helvTable, 7, 1);
                //
                //Report Header
                BaseFont  bfntHead   = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font      fntHead    = new Font(bfntHead, 16, 1);
                Paragraph prgHeading = new Paragraph();
                prgHeading.Alignment = Element.ALIGN_RIGHT;
                prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead));
                prgHeading.IndentationRight = 40;
                prgHeading.PaddingTop       = 80;
                //prgHeading.IndentationLeft = 250;
                prgHeading.SpacingAfter = 20;
                document.Add(prgHeading);
                //
                //IMAGEM DA LOGO
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("logo.jpg");
                img.SetAbsolutePosition(document.PageSize.Width - 50f - 495f, document.PageSize.Height - 50f - 100f);
                img.ScalePercent(22f);
                document.Add(img);
                //
                //
                //PEGA IMAGEM DO QR CODE GERADA AO ABRIR
                MemoryStream ms = new MemoryStream();
                imgQr.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] buff = ms.GetBuffer();
                iTextSharp.text.Image qrCode = iTextSharp.text.Image.GetInstance(buff);
                qrCode.SetAbsolutePosition(document.PageSize.Width - 65f - 48f, document.PageSize.Height - 65f - 148f);
                qrCode.ScalePercent(33f);
                document.Add(qrCode);
                //
                //Author
                Paragraph prgAuthor = new Paragraph();
                BaseFont  btnAuthor = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font      fntAuthor = new Font(btnAuthor, 8, 2);
                prgAuthor.Alignment        = Element.ALIGN_RIGHT;
                prgAuthor.IndentationRight = 35;
                prgAuthor.SpacingAfter     = 20;
                prgAuthor.Add(new Chunk("Designer Responsável : Marcelo Motta", fntAuthor));
                prgAuthor.Add(new Chunk("\nTelefone/WhatsApp : (22) 9 8818-9303", fntAuthor));
                prgAuthor.Add(new Chunk("\nWebsite : www.marcelomotta.com", fntAuthor));
                document.Add(prgAuthor);
                //
                //Cliente info
                Paragraph prgCliente = new Paragraph();
                BaseFont  btnCliente = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font      fntCliente = new Font(btnCliente, 8, 2);
                prgCliente.Alignment       = Element.ALIGN_LEFT;
                prgCliente.IndentationLeft = 35;
                //prgCliente.SpacingAfter = 20;
                prgCliente.Add(new Chunk("Faturado para : " + lblCliente.Text, fntCliente));
                prgCliente.Add(new Chunk("\n" + lblPrecoHora.Text, fntCliente));
                prgCliente.Add(new Chunk("\nData de Emissão : " + txtDataEmissao.Text, fntCliente));
                prgCliente.Add(new Chunk("\nData de Vencimento : " + txtDataVencimento.Text, fntCliente));

                //
                document.Add(prgCliente);
                //
                //Add line break
                document.Add(new Chunk("\n", fntHead));
                //
                // cria tabela
                // Write the table
                //
                //BaseFont btnTable = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                //Font fntTable = new Font(btnTable, 9, 1);
                //
                iTextSharp.text.Font fontTable       = FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                iTextSharp.text.Font fontHeaderTable = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                //
                PdfPTable table = new PdfPTable(5);
                //set overall width
                table.WidthPercentage = 90f;
                //table.DefaultCell.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                //table.DefaultCell.BorderColor = new BaseColor(171, 183, 183);
                //set column widths
                int[] firstTablecellwidth = { 5, 10, 70, 10, 10 };
                //table.DefaultCell.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                //table.DefaultCell.Border =Rectangle.NO_BORDER;
                table.SetWidths(firstTablecellwidth);
                //Criar colunas
                PdfPCell pi = new PdfPCell(new Phrase("ID", fontHeaderTable));
                pi.Border          = Rectangle.NO_BORDER;
                pi.BackgroundColor = new BaseColor(171, 183, 183);
                pi.Padding         = 5f;
                table.AddCell(pi);
                //Date
                PdfPCell date = new PdfPCell(new Phrase("Data", fontHeaderTable));
                date.Border          = Rectangle.NO_BORDER;
                date.BackgroundColor = new BaseColor(171, 183, 183);
                date.Padding         = 5f;
                table.AddCell(date);

                PdfPCell desc = new PdfPCell(new Phrase("Descrição", fontHeaderTable));
                desc.Border          = Rectangle.NO_BORDER;
                desc.BackgroundColor = new BaseColor(171, 183, 183);
                desc.Padding         = 5f;
                table.AddCell(desc);

                PdfPCell rendimento = new PdfPCell(new Phrase("Horas", fontHeaderTable));
                rendimento.Border          = Rectangle.NO_BORDER;
                rendimento.BackgroundColor = new BaseColor(171, 183, 183);
                rendimento.Padding         = 5f;
                table.AddCell(rendimento);

                PdfPCell def = new PdfPCell(new Phrase("Preço", fontHeaderTable));
                def.Border          = Rectangle.NO_BORDER;
                def.BackgroundColor = new BaseColor(171, 183, 183);
                def.Padding         = 5f;
                table.AddCell(def);
                table.HeaderRows = 1;
                //table.DefaultCell.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                // add header from dgv
                //for (int j = 0; j < gridTrabalhos.Columns.Count; j++)
                //{
                //    table.AddCell(new Phrase(gridTrabalhos.Columns[j].HeaderText, fontTable));
                //}
                //flag first row as header
                //table.HeaderRows = 1;
                // add atual rows from dgv to table

                for (int i = 0; i < gridTrabalhos.Rows.Count; i++)
                {
                    for (int k = 0; k < gridTrabalhos.Columns.Count; k++)
                    {
                        if (gridTrabalhos[k, i].Value != null)
                        {
                            PdfPCell item = new PdfPCell(new Phrase(gridTrabalhos[k, i].Value.ToString(), fontTable));
                            //item.Border = Rectangle.NO_BORDER;
                            item.Border          = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER;
                            item.BorderColor     = new BaseColor(171, 183, 183);
                            item.BackgroundColor = new BaseColor(238, 238, 238);
                            item.Padding         = 5f;
                            table.AddCell(item);
                            //table.AddCell(new Phrase(gridTrabalhos[k, i].Value.ToString(), fontTable));
                        }
                    }
                }
                //
                table.SpacingAfter = 10;
                document.Add(table);
                //
                //
                //Footer > detalhes totalizadores
                Paragraph prgTotalDet = new Paragraph();
                BaseFont  btnTotalDet = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font      fntTotalDet = new Font(btnTotalDet, 8, 2);
                prgTotalDet.Alignment        = Element.ALIGN_RIGHT;
                prgTotalDet.IndentationRight = 35;
                //prgTotalDet.SpacingAfter = 20;
                //
                //Conta linhas do gridview pra exibir a contagem de entradas
                int linhas = gridTrabalhos.Rows.Count;
                //soma horas pra exibir a contagem
                decimal totalH = 0;
                foreach (DataGridViewRow row in gridTrabalhos.Rows)
                {
                    totalH += Convert.ToDecimal(row.Cells[3].Value);
                }
                var totalHoras = Convert.ToString(totalH);
                //
                prgTotalDet.Add(new Chunk("\nContagem Final de " + Convert.ToString(linhas) + " Entradas de Trabalho, com um total de " + totalHoras + " Horas Trabalhadas.", fntTotalDet));
                document.Add(prgTotalDet);
                //
                //Add a line seperation
                Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 90.0F, BaseColor.BLACK, Element.ALIGN_CENTER, 1)));
                //p.SpacingAfter = 20;
                document.Add(p);
                //
                //Footer > TOTAL FATURA
                Paragraph prgTotal = new Paragraph();
                BaseFont  btnTotal = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font      fntTotal = new Font(btnTotal, 12, 2);
                prgTotal.Alignment        = Element.ALIGN_RIGHT;
                prgTotal.IndentationRight = 35;
                //prgTotal.SpacingAfter = 10;
                prgTotal.Add(new Chunk("Valor devido : " + txtTotal.Text, fntTotal));
                document.Add(prgTotal);
                document.Close();
                writer.Close();
                //
                //verifica opção abrir apos salvar
                if (cbxOpen.Checked)
                {
                    System.Diagnostics.Process.Start(fileName);
                    this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
                }
                else
                {
                    MessageBox.Show("Arquivo Salvo com Sucesso!\nDiretório: " + fileName);
                }
            }
        }
        public MemoryStream GeneratePdfTemplate(GarmentInvoicePurchasingDispositionViewModel 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);

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

            document.Open();

            #region Header

            PdfPTable headerTable = new PdfPTable(2);
            headerTable.SetWidths(new float[] { 10f, 10f });
            headerTable.WidthPercentage = 100;
            PdfPTable headerTable1 = new PdfPTable(1);
            PdfPTable headerTable2 = new PdfPTable(2);
            headerTable2.SetWidths(new float[] { 15f, 40f });
            headerTable2.WidthPercentage = 100;

            PdfPCell cellHeader1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeaderBody = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            PdfPCell cellHeaderCS2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Colspan = 2
            };


            cellHeaderCS2.Phrase = new Phrase("BUKTI PENGELUARAN BANK - DISPOSISI", bold_font);
            cellHeaderCS2.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.AddCell(cellHeaderCS2);

            cellHeaderCS2.Phrase = new Phrase("", bold_font);
            cellHeaderCS2.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.AddCell(cellHeaderCS2);

            cellHeaderBody.Phrase = new Phrase("PT. DANLIRIS", normal_font);
            headerTable1.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase("Kel. Banaran, Kec. Grogol", normal_font);
            headerTable1.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase("Sukoharjo - 57100", normal_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeader1.AddElement(headerTable1);
            headerTable.AddCell(cellHeader1);

            cellHeaderCS2.Phrase = new Phrase("", bold_font);
            headerTable2.AddCell(cellHeaderCS2);

            cellHeaderBody.Phrase = new Phrase("Tanggal", normal_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase(": " + viewModel.PaymentDate.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.Phrase = new Phrase("NO", normal_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase(": " + viewModel.PaymentDispositionNo, normal_font);
            headerTable2.AddCell(cellHeaderBody);

            //List<string> supplier = model.Details.Select(m => m.SupplierName).Distinct().ToList();
            cellHeaderBody.Phrase = new Phrase("Dibayarkan ke", normal_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase(": " + viewModel.Supplier.Name, normal_font);
            headerTable2.AddCell(cellHeaderBody);


            cellHeaderBody.Phrase = new Phrase("Bank", normal_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase(": " + viewModel.AccountBank.BankName + " - A/C : " + viewModel.AccountBank.AccountNumber, normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeader2.AddElement(headerTable2);
            headerTable.AddCell(cellHeader2);

            cellHeaderCS2.Phrase = new Phrase("", normal_font);
            headerTable.AddCell(cellHeaderCS2);

            document.Add(headerTable);

            #endregion Header

            Dictionary <string, double> units           = new Dictionary <string, double>();
            Dictionary <string, double> percentageUnits = new Dictionary <string, double>();


            int    index    = 1;
            double total    = 0;
            double totalPay = 0;

            //if (viewModel.AccountBank.Currency.Code != "IDR" || viewModel.CurrencyCode == "IDR")
            //{
            #region BodyNonIDR

            PdfPTable bodyNonIDRTable = new PdfPTable(6);
            PdfPCell  bodyNonIDRCell  = new PdfPCell();

            float[] widthsBodyNonIDR = new float[] { 5f, 10f, 10f, 10f, 7f, 15f };
            bodyNonIDRTable.SetWidths(widthsBodyNonIDR);
            bodyNonIDRTable.WidthPercentage = 100;

            bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyNonIDRCell.Phrase = new Phrase("No.", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Phrase = new Phrase("No. Disposisi", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Colspan = 2;
            bodyNonIDRCell.Phrase  = new Phrase("Kategori Barang", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);
            bodyNonIDRCell.Colspan = 1;

            //bodyNonIDRCell.Phrase = new Phrase("Divisi", bold_font);
            //bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Phrase = new Phrase("Mata Uang", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Phrase = new Phrase("Jumlah", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            foreach (GarmentInvoicePurchasingDispositionItemViewModel item in viewModel.Items)
            {
                //var details = item.Details
                //    .GroupBy(m => new { m.unit.code, m.unit.name })
                //    .Select(s => new
                //    {
                //        s.First().unit.code,
                //        s.First().unit.name,
                //        Total = s.Sum(d => d.price)
                //    });
                bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER;
                bodyNonIDRCell.VerticalAlignment   = Element.ALIGN_TOP;
                bodyNonIDRCell.Phrase = new Phrase((index++).ToString(), normal_font);
                bodyNonIDRTable.AddCell(bodyNonIDRCell);

                bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_LEFT;
                bodyNonIDRCell.Phrase = new Phrase(item.DispositionNoteNo, normal_font);
                bodyNonIDRTable.AddCell(bodyNonIDRCell);

                bodyNonIDRCell.Colspan = 2;
                bodyNonIDRCell.Phrase  = new Phrase(item.Category, normal_font);
                bodyNonIDRTable.AddCell(bodyNonIDRCell);
                bodyNonIDRCell.Colspan = 1;

                //bodyNonIDRCell.Phrase = new Phrase(item.ProformaNo, normal_font);
                //bodyNonIDRTable.AddCell(bodyNonIDRCell);

                bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER;
                bodyNonIDRCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, normal_font);
                bodyNonIDRTable.AddCell(bodyNonIDRCell);


                bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                bodyNonIDRCell.Phrase = new Phrase(string.Format("{0:n4}", item.TotalPaidPayment), normal_font);
                bodyNonIDRTable.AddCell(bodyNonIDRCell);

                total += item.TotalPaidPayment;

                //foreach (var detail in details)
                //{
                //    if (units.ContainsKey(detail.code))
                //    {
                //        units[detail.code] += detail.Total;
                //    }
                //    else
                //    {
                //        units.Add(detail.code, detail.Total);
                //    }

                //    totalPay += detail.Total;
                //}
            }

            //foreach (var un in units)
            //{
            //    percentageUnits[un.Key] = un.Value * 100 / totalPay;
            //}

            bodyNonIDRCell.Colspan = 3;
            bodyNonIDRCell.Border  = Rectangle.NO_BORDER;
            bodyNonIDRCell.Phrase  = new Phrase("", normal_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Colspan             = 1;
            bodyNonIDRCell.Border              = Rectangle.BOX;
            bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyNonIDRCell.Phrase              = new Phrase("Total", bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.Colspan             = 1;
            bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyNonIDRCell.Phrase = new Phrase(viewModel.CurrencyCode, bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyNonIDRCell.Phrase = new Phrase(string.Format("{0:n4}", total), bold_font);
            bodyNonIDRTable.AddCell(bodyNonIDRCell);

            document.Add(bodyNonIDRTable);

            #endregion BodyNonIDR
            //}
            //else
            //{
            //    #region Body

            //    PdfPTable bodyTable = new PdfPTable(7);
            //    PdfPCell bodyCell = new PdfPCell();

            //    float[] widthsBody = new float[] { 5f, 10f, 10f, 10f, 7f, 10f, 10f };
            //    bodyTable.SetWidths(widthsBody);
            //    bodyTable.WidthPercentage = 100;

            //    bodyCell.HorizontalAlignment = Element.ALIGN_CENTER;
            //    bodyCell.Phrase = new Phrase("No.", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("No. Disposisi", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("Kategori Barang", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("Divisi", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("Mata Uang", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("Jumlah", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Phrase = new Phrase("Jumlah (IDR)", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    foreach (GarmentInvoicePurchasingDispositionItemViewModel item in viewModel.Items)
            //    {
            //        //var details = item.Details
            //        //    .GroupBy(m => new { m.unit.code, m.unit.name })
            //        //    .Select(s => new
            //        //    {
            //        //        s.First().unit.code,
            //        //        s.First().unit.name,
            //        //        Total = s.Sum(d => d.price)
            //        //    });
            //        bodyCell.HorizontalAlignment = Element.ALIGN_CENTER;
            //        bodyCell.VerticalAlignment = Element.ALIGN_TOP;
            //        bodyCell.Phrase = new Phrase((index++).ToString(), normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        bodyCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //        bodyCell.Phrase = new Phrase(item.DispositionNoteNo, normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        bodyCell.Phrase = new Phrase(item.Category, normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        bodyCell.Phrase = new Phrase(item.ProformaNo, normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        bodyCell.HorizontalAlignment = Element.ALIGN_CENTER;
            //        bodyCell.Phrase = new Phrase(viewModel.CurrencyCode, normal_font);
            //        bodyTable.AddCell(bodyCell);


            //        bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            //        bodyCell.Phrase = new Phrase(string.Format("{0:n4}", item.TotalPaid), normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            //        bodyCell.Phrase = new Phrase(string.Format("{0:n4}", (item.TotalPaid * viewModel.CurrencyRate)), normal_font);
            //        bodyTable.AddCell(bodyCell);

            //        total += item.TotalPaid;

            //        //foreach (var detail in details)
            //        //{
            //        //    if (units.ContainsKey(detail.code))
            //        //    {
            //        //        units[detail.code] += detail.Total;
            //        //    }
            //        //    else
            //        //    {
            //        //        units.Add(detail.code, detail.Total);
            //        //    }

            //        //    totalPay += detail.Total;
            //        //}
            //    }

            //    //foreach (var un in units)
            //    //{
            //    //    percentageUnits[un.Key] = (un.Value * viewModel.CurrencyRate) * 100 / (totalPay * viewModel.CurrencyRate);
            //    //}

            //    bodyCell.Colspan = 3;
            //    bodyCell.Border = Rectangle.NO_BORDER;
            //    bodyCell.Phrase = new Phrase("", normal_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Colspan = 1;
            //    bodyCell.Border = Rectangle.BOX;
            //    bodyCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //    bodyCell.Phrase = new Phrase("Total", bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.Colspan = 1;
            //    bodyCell.HorizontalAlignment = Element.ALIGN_CENTER;
            //    bodyCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            //    bodyCell.Phrase = new Phrase(string.Format("{0:n4}", total), bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            //    bodyCell.Phrase = new Phrase(string.Format("{0:n4}", total * viewModel.CurrencyRate), bold_font);
            //    bodyTable.AddCell(bodyCell);

            //    document.Add(bodyTable);

            //    #endregion Body
            //}



            #region BodyFooter

            PdfPTable bodyFooterTable = new PdfPTable(6);
            bodyFooterTable.SetWidths(new float[] { 3f, 6f, 2f, 6f, 10f, 10f });
            bodyFooterTable.WidthPercentage = 100;

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

            //bodyFooterCell.Colspan = 1;
            //bodyFooterCell.Phrase = new Phrase("");
            //bodyFooterTable.AddCell(bodyFooterCell);

            //bodyFooterCell.Colspan = 1;
            //bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //bodyFooterCell.Phrase = new Phrase("Total :", normal_font);
            //bodyFooterTable.AddCell(bodyFooterCell);

            //bodyFooterCell.Colspan = 4;
            //bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            //bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", total));
            //bodyFooterTable.AddCell(bodyFooterCell);

            ////total = viewModel.CurrencyId > 0 ? total * viewModel.CurrencyRate : total;

            //foreach (var unit in percentageUnits)
            //{
            //    bodyFooterCell.Colspan = 1;
            //    bodyFooterCell.Phrase = new Phrase("");
            //    bodyFooterTable.AddCell(bodyFooterCell);

            //    bodyFooterCell.Phrase = new Phrase(unit.Key, normal_font);
            //    bodyFooterTable.AddCell(bodyFooterCell);

            //    bodyFooterCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, normal_font);
            //    bodyFooterTable.AddCell(bodyFooterCell);

            //    //bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", unit.Value), normal_font);
            //    //bodyFooterTable.AddCell(bodyFooterCell);



            //    bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", unit.Value * total / 100), normal_font);
            //    bodyFooterTable.AddCell(bodyFooterCell);


            //    bodyFooterCell.Colspan = 2;
            //    bodyFooterCell.Phrase = new Phrase("");
            //    bodyFooterTable.AddCell(bodyFooterCell);
            //}

            //bodyFooterCell.Colspan = 6;
            //bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //bodyFooterCell.Phrase = new Phrase("");
            //bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.Colspan             = 1;
            bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyFooterCell.Phrase = new Phrase("");
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.Phrase = new Phrase("Total", normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyFooterCell.Phrase = new Phrase(": " + viewModel.AccountBank.Currency.Code, normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.Colspan             = 3;
            bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", total), normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);


            //document.Add(bodyFooterTable);
            //document.Add(new Paragraph("\n"));


            bodyFooterCell.Colspan             = 1;
            bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyFooterCell.Phrase = new Phrase("");
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.Phrase = new Phrase("Terbilang", normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            bodyFooterCell.Phrase = new Phrase(": " + viewModel.AccountBank.Currency.Code, normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);

            bodyFooterCell.Colspan             = 3;
            bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT;
            bodyFooterCell.Phrase = new Phrase(NumberToTextIDN.terbilang(total), normal_font);
            bodyFooterTable.AddCell(bodyFooterCell);


            document.Add(bodyFooterTable);
            document.Add(new Paragraph("\n"));

            #endregion BodyFooter

            #region Footer

            PdfPTable footerTable = new PdfPTable(2);
            PdfPCell  cellFooter  = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            float[] widthsFooter = new float[] { 10f, 5f };
            footerTable.SetWidths(widthsFooter);
            footerTable.WidthPercentage = 100;

            cellFooter.Phrase = new Phrase("Dikeluarkan dengan cek/BG No. : " + viewModel.BGCheckNumber, normal_font);
            footerTable.AddCell(cellFooter);

            cellFooter.Phrase = new Phrase("", normal_font);
            footerTable.AddCell(cellFooter);

            PdfPTable signatureTable = new PdfPTable(3);
            PdfPCell  signatureCell  = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            };
            signatureCell.Phrase = new Phrase("Bag. Keuangan", normal_font);
            signatureTable.AddCell(signatureCell);

            signatureCell.Colspan             = 2;
            signatureCell.HorizontalAlignment = Element.ALIGN_CENTER;
            signatureCell.Phrase = new Phrase("Direksi", normal_font);
            signatureTable.AddCell(signatureCell);

            signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("---------------------------", normal_font),
                FixedHeight         = 40,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("---------------------------", normal_font),
                FixedHeight         = 40,
                Border              = Rectangle.NO_BORDER,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("---------------------------", normal_font),
                FixedHeight         = 40,
                Border              = Rectangle.NO_BORDER,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            footerTable.AddCell(new PdfPCell(signatureTable));

            cellFooter.Phrase = new Phrase("", normal_font);
            footerTable.AddCell(cellFooter);
            document.Add(footerTable);

            #endregion Footer

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

            return(stream);
        }
        private static void SetReportTable(Document document, MemoGarmentPurchasingModel data)
        {
            var table = new PdfPTable(5)
            {
                WidthPercentage = 100
            };

            table.SetWidths(new float[] { 5f, 12f, 23f, 15f, 15f });

            SetReportTableHeader(table);

            var cell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var cellColspan3 = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Colspan             = 3
            };

            var cellAlignRight = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var cellAlignLeft = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            double totalDebit  = 0;
            double totalCredit = 0;
            int    no          = 1;

            foreach (var detail in data.MemoGarmentPurchasingDetails)
            {
                cell.Phrase = new Phrase(no + "", _smallerFont);
                table.AddCell(cell);

                cell.Phrase = new Phrase(detail.COANo, _smallFont);
                table.AddCell(cell);

                cellAlignLeft.Phrase = new Phrase(detail.COAName, _smallFont);
                table.AddCell(cellAlignLeft);

                cellAlignRight.Phrase = new Phrase(detail.DebitNominal.ToString("#,##0.#0"), _smallFont);
                table.AddCell(cellAlignRight);

                cellAlignRight.Phrase = new Phrase(detail.CreditNominal.ToString("#,##0.#0"), _smallFont);
                table.AddCell(cellAlignRight);

                totalDebit  += detail.DebitNominal;
                totalCredit += detail.CreditNominal;
                no++;
            }

            cellColspan3.Phrase = new Phrase("Jumlah Total", _smallBoldFont);
            table.AddCell(cellColspan3);

            cellAlignRight.Phrase = new Phrase(totalDebit.ToString("#,##0.#0"), _smallBoldFont);
            table.AddCell(cellAlignRight);

            cellAlignRight.Phrase = new Phrase(totalCredit.ToString("#,##0.#0"), _smallBoldFont);
            table.AddCell(cellAlignRight);

            document.Add(table);
        }
Пример #7
0
        public static PdfPTable CreateAlarmTable(PdfReportConfig cfg)
        {
            //Left in as a teaser for next phase of the project

            // the table object
            const int cols  = 6;
            PdfPTable table = new PdfPTable(cols);

            table.DefaultCell.PaddingBottom = 5;
            table.WidthPercentage           = 100;
            table.HeaderRows         = 2;
            table.DefaultCell.Phrase = new Phrase {
                Font = cfg.TableAlmCellFont
            };

            // columns relative widths
            float[] colWidths = new float[] { 10, 30, 0, 20, 20, 20 };
            table.SetWidths(colWidths);


            // Alarms - Row1
            Phrase   phrase = new Phrase("ALARMS", cfg.TableHeaderFont);
            PdfPCell cell   = new PdfPCell(phrase);

            cell.GrayFill = (float).95;
            cell.Border   = 0;
            cell.Colspan  = 6;
            table.AddCell(cell);

            // Alarms - Row2 - col1
            phrase       = new Phrase("ALM #", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col2
            phrase       = new Phrase("DESCRIPTION", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col3
            phrase       = new Phrase("GROUP", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col4
            phrase       = new Phrase("SET TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col5
            phrase       = new Phrase("CLEAR TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);


            // Alarms - Row2 - col6
            phrase       = new Phrase("ACK TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            //clsAlarmList almList = cfg.OrderBase.AggregateAlarms();


            //if (almList.Count > 0)
            //{

            //	foreach (clsAlarm alm in almList)
            //	{
            //		cell = new PdfPCell(new Phrase(alm.Alm_ID.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_Desc, cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_Group, cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_SetTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_ClearTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_AckTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);
            //	}
            //}
            //else
            //{
            cell         = new PdfPCell(new Phrase("No alarms recorded for this order", cfg.TableAlmTableEmptyFont));
            cell.Colspan = 6;
            table.AddCell(cell);
            //}

            return(table);
        }
Пример #8
0
        private void bgworker_DoWork(object sender, DoWorkEventArgs e)
        {
            String    query = "", empid = "", loan_type = "", date_from = "", date_to = "", pay_code = "", table = "hr_rpt_files", filename = "", code = "", col = "", val = "", date_in = "";
            DataTable pay_period = null;

            Double total      = 0.00;
            String loan_query = "";

            query = "SELECT empid, firstname, lastname,pay_rate FROM rssys.hr_employee";
            cbo_employee.Invoke(new Action(() => {
                if (cbo_employee.SelectedIndex != -1)
                {
                    empid  = cbo_employee.SelectedValue.ToString();
                    query += " WHERE empid='" + empid + "'";
                }
            }));
            query += " ORDER BY empid ASC";


            DataTable employees = db.QueryBySQLCode(query);

            loan_query = "SELECT * FROM rssys.hr_loan_type";
            cbo_loan_type.Invoke(new Action(() =>
            {
                if (cbo_loan_type.SelectedIndex != -1)
                {
                    loan_type   = cbo_loan_type.SelectedValue.ToString();
                    loan_query += " WHERE code = '" + loan_type + "'";
                }
            }));
            DataTable dt_loan_type = db.QueryBySQLCode(loan_query);

            cbo_payollperiod.Invoke(new Action(() => {
                pay_code = cbo_payollperiod.SelectedValue.ToString();
            }));

            pay_period = get_date(pay_code);

            if (pay_period.Rows.Count > 0)
            {
                date_from = gm.toDateString(pay_period.Rows[0]["date_from"].ToString(), "yyyy-MM-dd");
                date_to   = gm.toDateString(pay_period.Rows[0]["date_to"].ToString(), "yyyy-MM-dd");
            }

            filename  = RandomString(5) + "_" + DateTime.Now.ToString("yyyy-MM-dd");
            filename += ".pdf";


            //System.IO.FileStream fs = new FileStream("\\\\RIGHTAPPS\\RightApps\\Eastland\\payroll_reports\\loan_summary\\" + filename, FileMode.Create);
            System.IO.FileStream fs = new FileStream(fileloc_dtr + "\\ViewController\\RPT\\Payroll\\loan_summary\\" + filename, FileMode.Create);

            Document document = new Document(PageSize.LEGAL, 25, 25, 30, 30);

            PdfWriter.GetInstance(document, fs);
            document.Open();

            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL);

            Paragraph paragraph = new Paragraph();

            paragraph.Alignment = Element.ALIGN_CENTER;
            paragraph.Font      = FontFactory.GetFont("Arial", 12);
            paragraph.SetLeading(1, 1);
            paragraph.Add("EMPLOYEE LOAN SUMMARY REPORTS");


            Phrase line_break = new Phrase("\n");

            document.Add(paragraph);
            document.Add(line_break);

            Paragraph paragraph_2 = new Paragraph();

            paragraph_2.Alignment = Element.ALIGN_CENTER;
            paragraph_2.Font      = FontFactory.GetFont("Arial", 12);
            paragraph_2.SetLeading(1, 1);
            paragraph_2.Add("For the payroll period " + date_from + " to " + date_to);


            Phrase line_break_2 = new Phrase("\n");

            document.Add(paragraph_2);
            document.Add(line_break_2);



            PdfPTable t = new PdfPTable(1);

            float[] widths = new float[] { 100 };
            t.WidthPercentage = 100;
            t.SetWidths(widths);

            PdfPTable dis_earnings = new PdfPTable(1);

            float[] _w2 = new float[] { 100f };
            dis_earnings.SetWidths(_w2);

            foreach (DataRow _employees in employees.Rows)
            {
                String fname = _employees["firstname"].ToString();
                String lname = _employees["lastname"].ToString();
                String empno = _employees["empid"].ToString();
                try
                {
                    foreach (DataRow _loan_type in dt_loan_type.Rows)
                    {
                        DataTable has_loan = db.QueryBySQLCode("SELECT employee_no FROM rssys.hr_loanhdr WHERE employee_no = '" + empno + "' AND loan_type = '" + _loan_type["code"].ToString() + "'");
                        if (has_loan != null && has_loan.Rows.Count > 0)
                        {
                            dis_earnings.AddCell(new PdfPCell(new Paragraph(fname + " " + lname))
                            {
                                Colspan = 2, Border = 2
                            });

                            DataTable hoe = db.QueryBySQLCode("SELECT DISTINCT(de.code) as code, de.description  FROM rssys.hr_loan_type de  LEFT JOIN rssys.hr_loanhdr od  ON de.code = od.loan_type WHERE od.employee_no = '" + empno + "'");

                            foreach (DataRow _hoe in hoe.Rows)
                            {
                                dis_earnings.AddCell(new PdfPCell(new Paragraph(_hoe["description"].ToString()))
                                {
                                    PaddingLeft = 30f, Colspan = 2, Border = 0
                                });
                                DataTable hee = db.QueryBySQLCode("SELECT * FROM rssys.hr_loanhdr WHERE loan_type = '" + _hoe["code"].ToString() + "' AND employee_no = '" + empno + "'");
                                foreach (DataRow _hee in hee.Rows)
                                {
                                    dis_earnings.AddCell(new PdfPCell(new Paragraph(_hee["loan_amount"].ToString()))
                                    {
                                        PaddingLeft = 40f, Colspan = 2, Border = 0
                                    });
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                empno = null;
            }

            document.Add(dis_earnings);
            document.Add(t);
            document.Close();

            code = db.get_pk("rpt_id");
            col  = "rpt_id,filename,date_added,rpt_type";
            val  = "'" + code + "','" + filename + "','" + DateTime.Now.ToShortDateString() + "','LOAN'";

            if (db.InsertOnTable(table, col, val))
            {
                db.set_pkm99("rpt_id", db.get_nextincrementlimitchar(code, 8)); //changes from 'hr_empid'
                MessageBox.Show("New summary reports created");
            }
            else
            {
                MessageBox.Show("Failed on saving.");
            }
            pic_loading.Invoke(new Action(() => {
                pic_loading.Visible = false;
                btn_submit.Enabled  = true;
            }));

            display_list();
        }
Пример #9
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //The two files that we are creating
            string file1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "File1.pdf");
            string file2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "File2.pdf");

            //Create a base file to write on top of
            using (FileStream fs = new FileStream(file1, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                    {
                        doc.Open();
                        doc.Add(new Paragraph("Hello world"));
                        doc.Close();
                    }
                }
            }

            //Bind a reader to our first document
            PdfReader reader = new PdfReader(file1);

            //Create our second document
            using (FileStream fs = new FileStream(file2, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    StyleSheet styles = new StyleSheet();
                    //...styles omitted for brevity

                    //Our HTML
                    string html = "<table><tr><th>First Name</th><th>Last Name</th></tr><tr><td>Chris</td><td>Haas</td></tr></table>";
                    //ParseToList requires a StreamReader instead of just a string so just wrap it
                    using (StringReader sr = new StringReader(html))
                    {
                        //Get our raw PdfContentByte object letting us draw "above" existing content
                        PdfContentByte cb = stamper.GetOverContent(1);
                        //Create a new ColumnText object bound to the above PdfContentByte object
                        ColumnText ct = new ColumnText(cb);
                        //Get the dimensions of the first page of our source document
                        iTextSharp.text.Rectangle page1size = reader.GetPageSize(1);
                        //Create a single column object spanning the entire page
                        ct.SetSimpleColumn(0, 0, page1size.Width, page1size.Height);

                        ct.AddElement(new Paragraph("Hello world!"));

                        //Convert our HTML to iTextSharp elements
                        List <IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);
                        //Loop through each element (in this case there's actually just one PdfPTable)
                        foreach (IElement el in elements)
                        {
                            //If the element is a PdfPTable
                            if (el is PdfPTable)
                            {
                                //Cast it
                                PdfPTable tt = (PdfPTable)el;
                                //Change the widths, these are relative width by the way
                                tt.SetWidths(new float[] { 75, 25 });
                            }
                            //Add the element to the ColumnText
                            ct.AddElement(el);
                        }
                        //IMPORTANT, this actually commits our object to the PDF
                        ct.Go();
                    }
                }
            }

            this.Close();
        }
Пример #10
0
        public ActionResult Printaj(int id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Racuni r = db.RacuniDbSet.Find(id);

            if (r == null)
            {
                return(HttpNotFound());
            }


            RacunPrintajVM model = db.RacuniDbSet
                                   .Where(x => x.Id == id)
                                   .Select(f => new RacunPrintajVM
            {
                Id             = f.Id,
                Placen         = f.Placen ? "DA" : "NE",
                DatumIzdavanja = f.DatumIzdavanja,
                KorisnikId     = f.KorisnikId,
                PeriodDo       = f.ObracunskiPeriodDO,
                PeriodOd       = f.ObracunskiPeriodOD,
                RokPlacanja    = f.RokPlacanja,
                Sifra          = f.Sifra,
                Ukupno         = f.UkupnoBezPDV.ToString(),
                PDF            = (f.UkupnoSaPDV - f.UkupnoBezPDV).ToString(),
                UkupnoPDV      = f.UkupnoSaPDV.ToString(),
            }).Single();



            model.Korisnik    = db.KorisnikDbSet.Find(model.KorisnikId);
            model.ListaStavki = db.RacuniStavkeDbSet.Where(g => g.RacunId == model.Id).ToList();



            PdfPTable pdftabela    = new PdfPTable(2);
            PdfPTable tabela3      = new PdfPTable(3);
            PdfPTable tabelaUsluge = new PdfPTable(7);
            PdfPTable tabelaTotal  = new PdfPTable(5);


            PdfPCell celija;

            string FONT = "c:/Windows/Fonts/arial.ttf";
            Font   font = FontFactory.GetFont(FONT, BaseFont.IDENTITY_H, true);

            using (MemoryStream ms = new MemoryStream())
            {
                Document document = new Document();

                document.SetPageSize(PageSize.A4);
                document.SetMargins(50f, 50f, 20f, 20f);


                pdftabela.WidthPercentage     = 100;
                pdftabela.HorizontalAlignment = Element.ALIGN_LEFT;


                tabela3.WidthPercentage     = 100;
                tabela3.HorizontalAlignment = Element.ALIGN_LEFT;

                tabelaUsluge.WidthPercentage     = 100;
                tabelaUsluge.HorizontalAlignment = Element.ALIGN_LEFT;

                tabelaTotal.WidthPercentage     = 100;
                tabelaTotal.HorizontalAlignment = Element.ALIGN_LEFT;

                PdfWriter writer = PdfWriter.GetInstance(document, ms);
                document.Open();

                BaseFont nf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);
                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false);

                var Sivaboja = new BaseColor(25, 25, 25);

                Font fontsadrzaj = new Font(nf, 11);
                Font font8       = new Font(nf, 8);
                Font font8bold   = new Font(bf, 8);
                Font font11      = new Font(nf, 11);
                Font font9       = new Font(nf, 9);
                Font font10      = new Font(nf, 10);
                Font font11bold  = new Font(bf, 11);
                Font font16Bold  = new Font(bf, 16);
                Font font16      = new Font(nf, 16);
                Font font20      = new Font(nf, 18);

                string putanja = Server.MapPath("~/Slike/");
                Image  header  = Image.GetInstance(putanja + "header.png");

                //////////////////////////////////////////////////////////////////////////

                header.ScaleToFit(PageSize.A4.Width - 90f, 80f);
                header.SpacingBefore = 10f;
                header.SpacingAfter  = 10f;
                header.Alignment     = Element.ALIGN_LEFT;
                document.Add(header);

                //////////////////////////////////////////////////////////////////////////

                pdftabela.SetWidths(new float[] { 160f, 100f });
                tabela3.SetWidths(new float[] { 50, 40, 50 });
                tabelaUsluge.SetWidths(new float[] { 35, 35, 35, 35, 35, 35, 35 });
                tabelaTotal.SetWidths(new float[] { 50, 50, 50, 50, 50 });



                #region tijelo

                pdftabela.SpacingBefore = 50f;


                celija = new PdfPCell(new Phrase("RAČUN - " + model.Sifra, font20));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                pdftabela.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                pdftabela.AddCell(celija);

                //celija = new PdfPCell(new Phrase("Sifra " + model.Sifra, font11));
                //celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                //celija.VerticalAlignment = Element.ALIGN_MIDDLE;
                //celija.BackgroundColor = BaseColor.WHITE;
                //celija.Border = Rectangle.NO_BORDER;
                //pdftabela.AddCell(celija);


                tabela3.SpacingBefore = 50f;


                #endregion


                document.Add(pdftabela);



                celija = new PdfPCell(new Phrase("Klijent: ", font11bold));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 25f;
                tabela3.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Detalji o računu: ", font11bold));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.MinimumHeight       = 25f;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Ime + " " + model.Korisnik.Prezime, font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Datum izdavanja: " + model.DatumIzdavanja.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.MinimumHeight       = 16f;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Adresa + " ", font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Period od: " + model.PeriodOd.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();



                celija = new PdfPCell(new Phrase(model.Korisnik.Opcina.NazivOpcine, font11));
                celija.HorizontalAlignment = Element.ALIGN_LEFT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 16f;
                tabela3.AddCell(celija);


                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                celija = new PdfPCell(new Phrase("Period od: " + model.PeriodDo.ToShortDateString(), font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.PaddingLeft         = 20;
                celija.Border = Rectangle.NO_BORDER;
                tabela3.AddCell(celija);

                tabela3.CompleteRow();

                document.Add(tabela3);



                tabelaUsluge.SpacingBefore = 50f;



                celija = new PdfPCell(new Phrase("USLUGA ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("NAZIV ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("DATUM OD ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("DATUM DO ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("CIJENA ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("PDV ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);

                celija = new PdfPCell(new Phrase("UKUPNO ", font10));
                celija.HorizontalAlignment = Element.ALIGN_CENTER;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border        = Rectangle.NO_BORDER;
                celija.MinimumHeight = 20f;
                tabelaUsluge.AddCell(celija);


                /////////////////////////////////////////////////////////////////
                tabelaUsluge.CompleteRow();
                /////////////////////////////////////////////////////////////////


                foreach (var item in model.ListaStavki)
                {
                    celija = new PdfPCell(new Phrase(item.AktivnaUsluga.Paket.Naziv, font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    celija = new PdfPCell(new Phrase(item.AktivnaUsluga.Paket.TipUsluga.Naziv, font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);


                    celija = new PdfPCell(new Phrase(item.DatumPocetka.ToShortDateString(), font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    celija = new PdfPCell(new Phrase(item.DatumKraja.ToShortDateString(), font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    celija = new PdfPCell(new Phrase(item.IznosBezPDV.ToString(), font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    celija = new PdfPCell(new Phrase((item.IznosSaPDV - item.IznosBezPDV).ToString(), font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    celija = new PdfPCell(new Phrase(item.IznosSaPDV.ToString(), font11));
                    celija.HorizontalAlignment = Element.ALIGN_CENTER;
                    celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    celija.BackgroundColor     = BaseColor.WHITE;
                    celija.Border        = Rectangle.NO_BORDER;
                    celija.MinimumHeight = 20f;
                    tabelaUsluge.AddCell(celija);

                    ////////////////////////////////////////////////////////////////////////
                    tabelaUsluge.CompleteRow();
                    ///////////////////////////////////////////////////////////////////////////
                }


                tabelaUsluge.CompleteRow();
                document.Add(tabelaUsluge);

                ////////////////////////////////////////////////////////////////////////


                tabelaTotal.SpacingBefore = 100f;

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);


                celija = new PdfPCell(new Phrase("Ukupno bez PDV", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("PDV 17%", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase("Ukupno sa PDV", font11));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                tabelaTotal.CompleteRow();

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija        = new PdfPCell();
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);



                celija = new PdfPCell(new Phrase(model.Ukupno.ToString(), font16));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase(model.PDF, font16));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                celija = new PdfPCell(new Phrase(model.UkupnoPDV, font16Bold));
                celija.HorizontalAlignment = Element.ALIGN_RIGHT;
                celija.VerticalAlignment   = Element.ALIGN_MIDDLE;
                celija.BackgroundColor     = BaseColor.WHITE;
                celija.Border = Rectangle.NO_BORDER;
                tabelaTotal.AddCell(celija);

                tabelaTotal.CompleteRow();

                document.Add(tabelaTotal);



                document.Close();

                byte[] bytes = ms.ToArray();
                ms.Close();



                return(File(bytes, "application/pdf"));
            }
        }
Пример #11
0
        public void gyujtoToPDF(List <Auto> autok, DateTime date)
        {
            using (SaveFileDialog fd = new SaveFileDialog())
            {
                fd.CheckPathExists = fd.AddExtension = true;
                fd.Filter          = "PDF fájl|*.pdf";
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        iTextSharp.text.Font fon    = FontFactory.GetFont("c:\\Windows\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, true, Font.Size - 1);
                        iTextSharp.text.Font bold   = FontFactory.GetFont("c:\\Windows\\Fonts\\arialbd.ttf", BaseFont.IDENTITY_H, true, Font.Size);
                        Document             doc    = new Document(PageSize.A4, 30, 30, 30, 30);
                        PdfWriter            writer = PdfWriter.GetInstance(doc, new FileStream(fd.FileName, FileMode.Create, FileAccess.Write));

                        doc.Open();

                        PdfPTable table;

                        int napszakfuvar;

                        PdfPCell cell;
                        int      count = 0;
                        foreach (Auto auto in autok)
                        {
                            if (auto.OsszM3 == 0)
                            {
                                continue;
                            }
                            table = new PdfPTable(2);
                            table.DefaultCell.Border = 0;
                            table.SetWidths(new float[] { .8f, .2f });

                            cell        = new PdfPCell(new Phrase("Gyűjtő - " + auto.Rendszam, bold));
                            cell.Border = 0;
                            table.AddCell(cell);
                            cell        = new PdfPCell(new Phrase(date.ToShortDateString(), bold));
                            cell.Border = 0;
                            cell.HorizontalAlignment = 2;
                            table.AddCell(cell);

                            cell         = new PdfPCell(new Phrase("Járművezető: " + auto.Sofor + "     Segéd: " + (auto.KettenUlnek ? auto.Seged : "Nincs"), bold));
                            cell.Colspan = 2;
                            cell.Border  = 0;
                            table.AddCell(cell);
                            for (int a = 0; a < 3; a++)
                            {
                                List <WorkData> lapok = auto.OsszesMunkalap(a);
                                if (lapok.Count > 0)
                                {
                                    cell            = new PdfPCell(new Phrase(Enum.GetNames(typeof(Napszak))[a], bold));
                                    cell.Border     = 0;
                                    cell.PaddingTop = cell.PaddingBottom = 10f;
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase("Tényl. m3", bold));
                                    cell.HorizontalAlignment = 2;
                                    cell.Border     = 0;
                                    cell.PaddingTop = cell.PaddingBottom = 10f;
                                    table.AddCell(cell);

                                    napszakfuvar = 1;

                                    foreach (WorkData wd in lapok)
                                    {
                                        table.AddCell(new Phrase(string.Format("{0}. {1} - {2} m cső", napszakfuvar++, wd.GetInfo(true, true, false, true), wd.CsoHossz), fon));
                                        cell = new PdfPCell(new Phrase(wd.TenylegesKobmeter.ToString(), fon));
                                        cell.HorizontalAlignment = 2;
                                        cell.Border = 0;
                                        table.AddCell(cell);
                                    }
                                }
                            }

                            cell            = new PdfPCell(new Phrase("Megrendelt mennyiség (tonna): " + auto.OsszM3.ToString(), bold));
                            cell.PaddingTop = 20f;
                            cell.Colspan    = 2;
                            cell.Border     = 0;
                            table.AddCell(cell);

                            cell         = new PdfPCell(new Phrase("Telítettségi cél %: " + Properties.Settings.Default.telitettCel.ToString(), bold)); cell.Colspan = 2;
                            cell.Colspan = 2;
                            cell.Border  = 0;
                            table.AddCell(cell);

                            cell = new PdfPCell(new Phrase("Beszállított mennyiség (tonna): " +
                                                           auto.OsszM3 * Properties.Settings.Default.telitettCel / 100, bold));
                            cell.Colspan = 2;
                            cell.Border  = 0;
                            table.AddCell(cell);

                            cell         = new PdfPCell(new Phrase("Összes csőhossz (m): " + auto.Csohossz.ToString(), bold));
                            cell.Colspan = 2;
                            cell.Border  = 0;
                            table.AddCell(cell);

                            cell         = new PdfPCell(new Phrase("Összes km: " + auto.OsszTavolsag.ToString(), bold));
                            cell.Colspan = 2;
                            cell.Border  = 0;
                            table.AddCell(cell);

                            doc.Add(table);
                            if (count < autok.Count - 1)
                            {
                                doc.NewPage();
                            }
                            count++;
                        }


                        doc.Close();

                        MessageBox.Show("A mentés sikerült!", "Mentés kész", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception e)
                    {
                        AppLogger.WriteException(e);
                        MessageBox.Show("A mentés nem sikerült!\nEllenőrízze, a kiválasztott fájl nincs-e mással megnyitva", "Hiba", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        var presupuestoId = Request.QueryString["presupuestoId"];
        var centro        = HttpContext.Current.Session["user"] as ApplicationUser;
        var polizaId      = Request.QueryString["polizaId"];
        var poliza        = Poliza.ById(polizaId);
        var dictionary    = ApplicationDictionary.Load("es");

        var path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}.pdf",
            dictionary["Item_Prespuesto"],
            Guid.NewGuid());

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        string status   = string.Empty;
        var    document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var    writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        document.Open();

        var borderNone  = Rectangle.NO_BORDER;
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderAll   = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD)));
        document.Add(new Paragraph("N.I.F: " + centro.NIF, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.Nombre, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph(centro.CP + ", " + centro.Poblacion, FontFactory.GetFont(FontFactory.HELVETICA, 8)));
        document.Add(new Paragraph("Telf.: " + centro.Telefono1, FontFactory.GetFont(FontFactory.HELVETICA, 8)));

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var table = new PdfPTable(2)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 30f });
        var labelFont = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.NORMAL);
        var totalFont = FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL);
        var dataFont  = FontFactory.GetFont(FontFactory.HELVETICA, 8, Font.BOLD);

        var presupuestoCodigo = string.Empty;
        var presupuestoFecha  = string.Empty;

        var aseguradoNombre    = poliza.AseguradoNombre;
        var aseguradoDireccion = string.Empty;
        var aseguradoCP        = string.Empty;
        var aseguradoPoblacion = string.Empty;
        var aseguradoProvincia = string.Empty;
        var aseguradoNIF       = poliza.AseguradoNIF;
        var observaciones      = string.Empty;

        // Linea Total
        string  impuestoText = dictionary["PDF_IVA"] + " " + ConfigurationManager.AppSettings["IVA"].ToString() + "%";
        decimal impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IVA"].ToString());

        if (centro.Provincia.IndexOf("tenerife", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("canaria", StringComparison.OrdinalIgnoreCase) != -1 || centro.Provincia.IndexOf("las palmas", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_IGIC"] + " " + ConfigurationManager.AppSettings["IGIC"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["IGIC"].ToString());
        }

        if (centro.Provincia.IndexOf("melilla", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Melilla"] + " " + ConfigurationManager.AppSettings["Melilla"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Melilla"].ToString());
        }

        if (centro.Provincia.IndexOf("ceuta", StringComparison.OrdinalIgnoreCase) != -1)
        {
            impuestoText = dictionary["PDF_Ceuta"] + " " + ConfigurationManager.AppSettings["Ceuta"].ToString() + "%";
            impuesto     = Convert.ToDecimal(ConfigurationManager.AppSettings["Ceuta"].ToString());
        }

        var tableObservaciones = new PdfPTable(2)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        var tableCostsAspad = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 10f
        };

        var tableCostsPropios = new PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 10f,
            SpacingAfter        = 20f
        };

        tableObservaciones.SetWidths(new float[] { 1f, 3f });
        tableCostsAspad.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });
        tableCostsPropios.SetWidths(new float[] { 25f, 23f, 10f, 10f, 10f, 15f });

        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Especialidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Concepto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Cantidad"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Base"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Dto"]));
        tableCostsAspad.AddCell(ToolsPdf.HeaderCell(dictionary["PDF_Importe"]));

        /* CREATE PROCEDURE ASPADLAND_GetPresupuestoPendienteByPresupuestoId
         *   @PresupuestoId uniqueidentifier,
         *   @CentroId nvarchar(50) */
        bool    propios            = false;
        bool    hasObservaciones   = false;
        decimal totalBaseCost      = 0;
        decimal totalBaseCostASPAD = 0;

        using (var cmd = new SqlCommand("ASPADLAND_Salesforce_GetPresupuestoPendienteByPresupuestoId"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
            {
                cmd.Connection = cnn;
                cmd.Parameters.Add(DataParameter.Input("@PresupuestoId", presupuestoId));
                cmd.Parameters.Add(DataParameter.Input("@CentroId", centro.Id));
                try
                {
                    cmd.Connection.Open();
                    using (var rdr = cmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            observaciones     = rdr.GetString(9);
                            presupuestoCodigo = rdr.GetString(1);
                            presupuestoFecha  = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", rdr.GetDateTime(7));

                            string amountText        = string.Empty;
                            string totalRowText      = string.Empty;
                            string actoObservaciones = rdr.GetString(10);
                            var    especialidad      = rdr.GetString(4);

                            decimal finalAmount = 0M;
                            if (!rdr.IsDBNull(5))
                            {
                                finalAmount = rdr.GetDecimal(5);

                                if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                                {
                                    finalAmount = finalAmount / (1 + impuesto / 100);
                                }

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            var dto = string.Empty;
                            if (!rdr.IsDBNull(6))
                            {
                                decimal dtoAmount = rdr.GetDecimal(6);
                                finalAmount = finalAmount / (1 + impuesto / 100);

                                amountText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");

                                finalAmount = finalAmount * (100 - dtoAmount) / 100;
                                dto         = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} %",
                                    dtoAmount).Replace(",", ".");
                                totalRowText = string.Format(
                                    CultureInfo.InvariantCulture,
                                    @"{0:#0.00} €",
                                    finalAmount).Replace(",", ".");
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                totalBaseCost += finalAmount;
                            }
                            else
                            {
                                totalBaseCostASPAD += finalAmount;
                            }

                            if (especialidad.Equals("propio", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!propios)
                                {
                                    tableCostsPropios.AddCell(new PdfPCell(new Phrase(dictionary["PDF_Actospropios"], ToolsPdf.TimesBold))
                                    {
                                        Border              = ToolsPdf.BorderBottom,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0,
                                        Colspan             = 6
                                    });
                                }

                                tableCostsPropios.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsPropios.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));
                                propios = true;

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                            else
                            {
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(especialidad, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCell(rdr.GetString(3), labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(1, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(amountText, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dto, labelFont));
                                tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalRowText, labelFont));

                                if (!string.IsNullOrEmpty(actoObservaciones))
                                {
                                    hasObservaciones = true;
                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(rdr.GetString(3), labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });

                                    tableObservaciones.AddCell(new PdfPCell(new Phrase(actoObservaciones, labelFont))
                                    {
                                        Border              = ToolsPdf.BorderNone,
                                        Padding             = 6f,
                                        PaddingTop          = 6f,
                                        HorizontalAlignment = 0
                                    });
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (cmd.Connection.State != ConnectionState.Closed)
                    {
                        cmd.Connection.Close();
                    }
                }
            }
        }

        var la1 = new Chunk(dictionary["PDF_Albaran"] + ": ", labelFont);
        var la2 = new Chunk(presupuestoCodigo + Environment.NewLine, FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.BOLD));
        var la3 = new Chunk(dictionary["PDF_Fecha"] + ": ", labelFont);
        var la4 = new Chunk(presupuestoFecha, dataFont);

        var p1 = new Paragraph
        {
            la1,
            la2,
            la3,
            la4
        };

        document.Add(new Paragraph(Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine));

        var lb1 = new Chunk(aseguradoNombre + Environment.NewLine, dataFont);
        var lb2 = new Chunk(dictionary["PDF_Poliza"] + ": ", labelFont);
        var lb3 = new Chunk(poliza.Numero + Environment.NewLine, dataFont);

        var p2 = new Paragraph
        {
            lb1,
            lb2,
            lb3
        };

        var cell1 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };
        var cell2 = new PdfPCell {
            Border = ToolsPdf.BorderNone
        };

        cell1.AddElement(p1);
        cell2.AddElement(p2);


        table.AddCell(cell1);
        table.AddCell(cell2);

        document.Add(table);

        decimal baseIvaASPAD     = totalBaseCostASPAD * impuesto / 100;
        string  baseIvaTextASPAD = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIvaASPAD).Replace(",", ".");
        string  totalASPAD       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");

        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCostASPAD).Replace(",", "."), totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(baseIvaTextASPAD, totalFont));

        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
        tableCostsAspad.AddCell(ToolsPdf.DataCellRight(totalASPAD, totalFont));
        document.Add(tableCostsAspad);

        if (propios)
        {
            decimal baseIva     = totalBaseCost * impuesto / 100;
            string  baseIvaText = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", baseIva).Replace(",", ".");
            string  total       = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva).Replace(",", ".");

            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(dictionary["PDF_Base"], labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellTotal(string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost).Replace(",", "."), totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(impuestoText + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(baseIvaText, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(dictionary["PDF_Total"] + ":", labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCellRight(total, totalFont));

            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));
            tableCostsPropios.AddCell(ToolsPdf.DataCell(string.Empty, labelFont));

            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(string.Empty));
            tableCostsPropios.AddCell(TotalCell(dictionary["PDF_Total"] + ":"));
            string superTotal = string.Format(CultureInfo.InvariantCulture, @"{0:#0.00} €", totalBaseCost + baseIva + totalBaseCostASPAD + baseIvaASPAD).Replace(",", ".");
            tableCostsPropios.AddCell(TotalCell(superTotal));

            document.Add(tableCostsPropios);
        }

        if (!string.IsNullOrEmpty(observaciones))
        {
            document.Add(new Paragraph("Observaciones", ToolsPdf.TimesBold));
            document.Add(new Paragraph(observaciones, labelFont));
        }

        if (hasObservaciones)
        {
            document.Add(tableObservaciones);
        }

        document.Add(new Phrase(dictionary["Item_Presupuesto_Print_Caducity"], ToolsPdf.TimesLittle));

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Пример #13
0
        public MemoryStream GeneratePdfTemplate(GarmentShippingLocalPriceCorrectionNoteViewModel viewModel, Buyer buyer, int timeoffset)
        {
            const int MARGIN = 20;

            Font header_font_bold_big        = FontFactory.GetFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12);
            Font header_font_bold            = FontFactory.GetFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            Font header_font_bold_underlined = FontFactory.GetFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10, Font.UNDERLINE);
            Font header_font            = FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11);
            Font normal_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 normal_font_bold       = FontFactory.GetFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document document = new Document(PageSize.A5.Rotate(), MARGIN, MARGIN, MARGIN, MARGIN);

            MemoryStream stream = new MemoryStream();
            PdfWriter    writer = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region header
            PdfPTable tableHeader = new PdfPTable(2);
            tableHeader.WidthPercentage = 100;
            tableHeader.SetWidths(new float[] { 3f, 2f });

            PdfPCell cellHeaderContent1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeaderContent2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };


            cellHeaderContent1.AddElement(new Phrase("\n", normal_font));
            cellHeaderContent1.AddElement(new Phrase("PT. DAN LIRIS", header_font_bold));
            cellHeaderContent1.AddElement(new Phrase("Jl. Merapi No. 23, Kel. Banaran Kec.Grogol Kab. Sukoharjo", normal_font));
            cellHeaderContent1.AddElement(new Phrase("Telp : 0271-714400, Fax. 0271-717178", normal_font));
            cellHeaderContent1.AddElement(new Phrase("PO. Box. 166 Solo-57100 Indonesia", normal_font));
            cellHeaderContent1.AddElement(new Phrase("\n", normal_font));
            cellHeaderContent1.AddElement(new Phrase("\n", normal_font));
            cellHeaderContent1.AddElement(new Phrase("NOTA KOREKSI HARGA", normal_font));
            tableHeader.AddCell(cellHeaderContent1);

            cellHeaderContent2.AddElement(new Phrase("Sukoharjo, " + viewModel.correctionDate.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID")), normal_font));
            cellHeaderContent2.AddElement(new Phrase("\n", normal_font));
            cellHeaderContent2.AddElement(new Phrase("\n", normal_font));
            cellHeaderContent2.AddElement(new Phrase(viewModel.salesNote.buyer.Name, normal_font));
            cellHeaderContent2.AddElement(new Phrase(buyer.Address, normal_font));
            tableHeader.AddCell(cellHeaderContent2);

            document.Add(tableHeader);
            #endregion

            #region title

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

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

            cellTitle1.Phrase  = new Phrase(viewModel.correctionNoteNo, normal_font_bold);
            cellTitle1.Colspan = 2;
            tableTitle.AddCell(cellTitle1);

            cellTitle1.Phrase              = new Phrase("SUKOHARJO - JATENG", normal_font_underlined);
            cellTitle1.Colspan             = 1;
            cellTitle1.HorizontalAlignment = Element.ALIGN_LEFT;
            tableTitle.AddCell(cellTitle1);

            tableTitle.SpacingAfter = 10;
            document.Add(tableTitle);
            #endregion

            #region bodyTable
            PdfPTable tableBody = new PdfPTable(5);
            tableBody.WidthPercentage = 100;
            tableBody.SetWidths(new float[] { 4f, 2f, 1f, 2.3f, 2.5f });
            PdfPCell cellBodyLeft = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellBodyLeftNoBorder = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellBodyRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            PdfPCell cellBodyRightNoBorder = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            PdfPCell cellBodyCenter = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            cellBodyCenter.Phrase = new Phrase("N a m a B a r a n g", normal_font);
            tableBody.AddCell(cellBodyCenter);

            cellBodyCenter.Phrase  = new Phrase("Quantity", normal_font);
            cellBodyCenter.Colspan = 2;
            tableBody.AddCell(cellBodyCenter);

            cellBodyCenter.Phrase  = new Phrase("Harga Sat.", normal_font);
            cellBodyCenter.Colspan = 1;
            tableBody.AddCell(cellBodyCenter);

            cellBodyCenter.Phrase  = new Phrase("Jumlah", normal_font);
            cellBodyCenter.Colspan = 1;
            tableBody.AddCell(cellBodyCenter);

            double totalPrice = 0;
            foreach (var item in viewModel.items)
            {
                cellBodyLeft.Phrase = new Phrase(item.salesNoteItem.product.name, normal_font);
                tableBody.AddCell(cellBodyLeft);

                cellBodyRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", item.salesNoteItem.quantity), normal_font);
                tableBody.AddCell(cellBodyRightNoBorder);

                cellBodyLeftNoBorder.Phrase = new Phrase(item.salesNoteItem.uom.Unit, normal_font);
                tableBody.AddCell(cellBodyLeftNoBorder);

                var diffPrice = item.priceCorrection - item.salesNoteItem.price;
                cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", diffPrice), normal_font);
                tableBody.AddCell(cellBodyRight);

                var price = diffPrice * item.salesNoteItem.quantity;
                cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", price), normal_font);
                tableBody.AddCell(cellBodyRight);

                totalPrice += price;
            }

            double ppn = 0;
            if (viewModel.salesNote.useVat)
            {
                ppn = totalPrice * 0.1;
            }
            double finalPrice = totalPrice + ppn;

            cellBodyRight.Phrase  = new Phrase("Dasar Pengenaan Pajak...............Rp.", normal_font);
            cellBodyRight.Border  = Rectangle.NO_BORDER;
            cellBodyRight.Colspan = 4;
            tableBody.AddCell(cellBodyRight);

            cellBodyRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", totalPrice), normal_font);
            cellBodyRightNoBorder.Border = Rectangle.NO_BORDER;
            tableBody.AddCell(cellBodyRightNoBorder);

            cellBodyRight.Phrase = new Phrase("PPN = 10% X Dasar Pengenaan Pajak...Rp.", normal_font);
            tableBody.AddCell(cellBodyRight);

            cellBodyRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", ppn), normal_font);
            cellBodyRightNoBorder.Border = Rectangle.BOTTOM_BORDER;
            tableBody.AddCell(cellBodyRightNoBorder);

            cellBodyRight.Phrase = new Phrase("Jumlah..............................Rp.", normal_font);
            tableBody.AddCell(cellBodyRight);

            cellBodyRightNoBorder.Phrase = new Phrase(string.Format("{0:n2}", finalPrice), normal_font);
            cellBodyRightNoBorder.Border = Rectangle.NO_BORDER;
            tableBody.AddCell(cellBodyRightNoBorder);


            tableBody.SpacingAfter = 10;
            document.Add(tableBody);
            #endregion

            #region footer
            PdfPTable tableFooter = new PdfPTable(2);
            tableFooter.WidthPercentage = 100;
            tableFooter.SetWidths(new float[] { 1.5f, 9f });

            PdfPCell cellFooterContent1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellFooterContent2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            string terbilang = NumberToTextIDN.terbilang(Math.Round(finalPrice, 2));

            cellFooterContent1.Phrase = (new Phrase("Terbilang :", normal_font));
            tableFooter.AddCell(cellFooterContent1);
            cellFooterContent2.Phrase = (new Phrase(terbilang, normal_font));
            tableFooter.AddCell(cellFooterContent2);

            cellFooterContent1.Phrase = (new Phrase("Catatan   :", normal_font));
            tableFooter.AddCell(cellFooterContent1);
            cellFooterContent2.Phrase = (new Phrase(viewModel.remark, normal_font));
            tableFooter.AddCell(cellFooterContent2);

            tableFooter.SpacingAfter = 10;
            document.Add(tableFooter);
            #endregion

            #region sign
            PdfPTable tableSign = new PdfPTable(5);
            tableSign.WidthPercentage = 80;
            tableSign.SetWidths(new float[] { 1f, 1f, 1f, 1f, 1f });
            PdfPCell cellBodySign = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellBodySignNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            cellBodySign.Phrase = new Phrase("Diterima Oleh", normal_font);
            tableSign.AddCell(cellBodySign);

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

            cellBodySign.Phrase = new Phrase("Dibuat Oleh", normal_font);
            tableSign.AddCell(cellBodySign);
            cellBodySign.Phrase = new Phrase("Diperiksa Oleh", normal_font);
            tableSign.AddCell(cellBodySign);
            cellBodySign.Phrase = new Phrase("Disetujui Oleh", normal_font);
            tableSign.AddCell(cellBodySign);


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

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

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

            document.Add(tableSign);
            #endregion

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

            return(stream);
        }
Пример #14
0
        protected override void drawBottom(string Comment)
        {
            PdfPTable table = new PdfPTable(4);

            table.HorizontalAlignment = 1;
            table.WidthPercentage     = 100;
            table.SpacingBefore       = 0;
            table.SpacingAfter        = 0;
            table.DefaultCell.Border  = Rectangle.BOX;
            table.SetWidths(new int[] { 1, 1, 1, 1 });


            PdfPCell bottom = new PdfPCell(new Phrase("For Office Use Only \n\n" + Comment, fontBoxHeader));

            bottom.Colspan     = 3;
            bottom.FixedHeight = 180f;
            table.AddCell(bottom);

            PdfPTable nested = new PdfPTable(1);

            PdfPCell totInvoL = new PdfPCell(new Phrase("15. Total Invoice Value", fontBoxHeader));

            totInvoL.FixedHeight         = 20f;
            totInvoL.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            totInvoL.Border = Rectangle.NO_BORDER;
            nested.AddCell(totInvoL);

            PdfPCell totInvoD = new PdfPCell(new Phrase(this.Model.TotalInvoiceValue, fontBoxDetail));//---------this.CertificateHead.TotalInvoiceValue1.ToString()

            totInvoD.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            totInvoD.Border      = Rectangle.NO_BORDER;
            totInvoD.FixedHeight = 20f;
            nested.AddCell(totInvoD);

            PdfPCell totQuantL = new PdfPCell(new Phrase("16. Total Quantity", fontBoxHeader));

            totQuantL.FixedHeight         = 20f;
            totQuantL.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            totQuantL.Border = Rectangle.NO_BORDER;
            nested.AddCell(totQuantL);

            PdfPCell totQuntyD = new PdfPCell(new Phrase(this.Model.TotalQuantity, fontBoxDetail)); //this.CertificateHead.TotalQuantity1

            totQuntyD.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            totQuntyD.Border      = Rectangle.NO_BORDER;
            totQuntyD.FixedHeight = 20f;
            nested.AddCell(totQuntyD);

            string s1 = "I declare that the goods are of Sri Lanka origin,";
            string s2 = "all particulars above are correctly stated,";
            string s3 = "and that the minimum value addition of goods exported is not less than 25% of the FOB price";

            string StatementTxt = s1 + s2 + s3;

            PdfPCell Statement = new PdfPCell(new Phrase(StatementTxt, fontSmallBold));

            Statement.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            Statement.Border = Rectangle.NO_BORDER;
            nested.AddCell(Statement);


            PdfPCell nesthousing = new PdfPCell(nested);

            nesthousing.Padding = 0f;
            table.AddCell(nesthousing);



            //----------------------------------------------------------

            PdfPTable FooterTable = new PdfPTable(4);


            FooterTable.HorizontalAlignment = 1;
            FooterTable.WidthPercentage     = 100;
            FooterTable.SpacingBefore       = 0;
            FooterTable.SpacingAfter        = 0;
            FooterTable.DefaultCell.Border  = Rectangle.BOX;
            FooterTable.SetWidths(new int[] { 1, 1, 1, 1 });

            PdfPCell Cell1 = new PdfPCell(new Phrase("Competent Authority - National Chamber of Exporters of Sri Lanka", fontSmallBold));

            Cell1.Colspan             = 2;
            Cell1.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

            PdfPCell Cell2 = new PdfPCell(new Phrase("Submitted by", fontSmallBold));

            Cell2.Colspan             = 2;
            Cell2.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

            FooterTable.AddCell(Cell1);
            FooterTable.AddCell(Cell2);


            PdfPCell NameAO = new PdfPCell(new Phrase("Name of NCE Authorized officer", fontFooterDetails));

            NameAO.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell Contact = new PdfPCell(new Phrase("Contact No +94 114651765", fontFooterDetails));

            Contact.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell SubName = new PdfPCell(new Phrase("Name & Designation", fontFooterDetails));

            SubName.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell SubContact = new PdfPCell(new Phrase("Contact No ", fontFooterDetails));

            SubContact.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;



            FooterTable.AddCell(NameAO);
            FooterTable.AddCell(Contact);
            FooterTable.AddCell(SubName);
            FooterTable.AddCell(SubContact);


            PdfPCell NameAOData = new PdfPCell(new Phrase(AuthoirzedOfficer, fontFooterDetails));

            NameAOData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            NameAOData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            NameAOData.FixedHeight         = 20f;

            PdfPCell ContactData = new PdfPCell(new Phrase(AuthTelephone, fontFooterDetails));

            ContactData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            ContactData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            ContactData.FixedHeight         = 20f;

            PdfPCell SubNameData = new PdfPCell(new Phrase(Model.ClientContact_Name + "-" + Model.ClientContact_Designation, fontFooterDetails)); //CertificateHead.CustomerName1

            SubNameData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            SubNameData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            SubNameData.FixedHeight         = 20f;

            PdfPCell SubContactData = new PdfPCell(new Phrase(Model.ClientContact_Telephone, fontFooterDetails));//CertificateHead.Customer_Telephone

            SubContactData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            SubContactData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            SubContactData.FixedHeight         = 20f;



            FooterTable.AddCell(NameAOData);
            FooterTable.AddCell(ContactData);
            FooterTable.AddCell(SubNameData);
            FooterTable.AddCell(SubContactData);



            PdfPCell NCEDate = new PdfPCell(new Phrase("Date", fontFooterDetails));

            NCEDate.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell NCESignaA = new PdfPCell(new Phrase("Signature of Authorized Officer", fontFooterDetails));

            NCESignaA.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell SubDate = new PdfPCell(new Phrase("Date", fontFooterDetails));

            SubDate.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;

            PdfPCell CompGen = new PdfPCell(new Phrase("This is a computer generated document", fontFooterDetails));

            CompGen.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;
            CompGen.HorizontalAlignment = PdfPCell.ALIGN_CENTER;



            FooterTable.AddCell(NCEDate);
            FooterTable.AddCell(NCESignaA);
            FooterTable.AddCell(SubDate);
            FooterTable.AddCell(CompGen);


            PdfPCell NCEDateData = new PdfPCell(new Phrase(SignedDate, fontFooterDetails));//Date

            NCEDateData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            NCEDateData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            NCEDateData.FixedHeight         = 15f;

            PdfPCell NCESignaAData = new PdfPCell(new Phrase("", fontFooterDetails));

            NCESignaAData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            NCESignaAData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            NCESignaAData.FixedHeight         = 15f;

            PdfPCell SubDateData = new PdfPCell(new Phrase(Model.RequestDate.ToString("dd/MM/yyyy"), fontFooterDetails));//CertificateHead.RequestDate1.ToString("dd/MM/yyyy")

            SubDateData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            SubDateData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            SubDateData.FixedHeight         = 15f;

            PdfPCell CompGenData = new PdfPCell(new Phrase("No signature required", fontSmallBold));

            CompGenData.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER;
            CompGenData.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            CompGenData.FixedHeight         = 15f;



            FooterTable.AddCell(NCEDateData);
            FooterTable.AddCell(NCESignaAData);
            FooterTable.AddCell(SubDateData);
            FooterTable.AddCell(CompGenData);



            //------------------------------------------------------------

            document.Add(table);
            document.Add(FooterTable);
        }
Пример #15
0
        public static MemoryStream GetPdfOfAttestation(long id, DbContext context)
        {
            var memoryStream = new MemoryStream();
            var document     = new Document(PageSize.A4, MarginLeft, MarginRight, MarginTop, MarginBottom);

            document.AddTitle("Результаты аттестации");
            document.AddCreationDate();
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

            EncodingProvider encProvider = CodePagesEncodingProvider.Instance;

            Encoding.RegisterProvider(encProvider);
            string arial = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");

            BaseFont baseFont = BaseFont.CreateFont(arial, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            Font body     = new Font(baseFont, 10, Font.NORMAL, BaseColor.BLACK);
            Font boldBody = new Font(baseFont, 10, Font.BOLD, BaseColor.BLACK);
            Font head     = new Font(baseFont, 16, Font.NORMAL, BaseColor.BLACK);

            var attestation = context.Set <AttestationModel>().First(x => x.Id == id);

            context.Entry(attestation).Collection(x => x.AttestationAnswer).Load();

            foreach (var attestationAnswer in attestation.AttestationAnswer)
            {
                attestationAnswer.Answer = context.Set <AnswerModel>().Find(attestationAnswer.AnswerId);
            }

            attestation.AttestationAnswer = attestation.AttestationAnswer.Where(x => x.Answer.IsSkipped == false).OrderBy(x => x.Answer.NumberOfAsk).ToList();

            var testedCompetences = attestation.IdsTestedCompetences;

            List <CompetencesModel> competencesModels = new List <CompetencesModel>();

            if (testedCompetences == null)
            {
                testedCompetences = new List <long>();
            }

            foreach (var testedCompetence in testedCompetences)
            {
                competencesModels.Add(context.Set <CompetencesModel>().Find(testedCompetence));
            }

            var worker = context.Set <SpecificWorkerModel>().Find((int)attestation.WorkerId);

            document.Open();
            if (worker == null)
            {
                worker = new SpecificWorkerModel();
                document.Add(new Paragraph($"Аттестация удалённого работника", head));
                document.Add(new Paragraph(attestation.Date.ToString("d"), head));
                document.Add(new Paragraph(" ", body));
            }

            else
            {
                document.Add(new Paragraph($"{worker.FullName} - результаты аттестации", head));
                document.Add(new Paragraph(attestation.Date.ToString("d"), head));
                document.Add(new Paragraph(" ", body));
            }
            document.Add(new Paragraph("Техническое интервью", head));
            document.Add(new Paragraph(" ", body));
            document.Add(new Paragraph("Блоки компетенций:", boldBody));
            foreach (var competencesModel in competencesModels)
            {
                if (competencesModel == null)
                {
                    document.Add(new Paragraph($"  -   компетенция была удалена", body));
                }
                else
                {
                    document.Add(new Paragraph($"  -   {competencesModel.Competence}", body));
                }
            }

            document.Add(new Paragraph(" ", body));

            document.Add(new Paragraph("Выявлены пробелы в знаниях:", boldBody));
            document.Add(new Paragraph($"{attestation.Problems}", body));

            document.Add(new Paragraph(" ", body));

            document.Add(new Paragraph("Дальнейшие действия", head));
            document.Add(new Paragraph($"{attestation.NextMoves}", body));

            document.Add(new Paragraph(" ", body));

            document.Add(new Paragraph("Обратная связь от руководителя проекта:", boldBody));
            document.Add(new Paragraph($"{attestation.Feedback}", body));

            document.Add(new Paragraph(" ", body));

            PdfPTable table = new PdfPTable(4);

            table.TotalWidth  = document.PageSize.Width - 72f - 65f;
            table.LockedWidth = true;
            float[] widths1 = new float[] { 0.55f, 4f, 0.7f, 4f };
            table.SetWidths(widths1);
            table.HorizontalAlignment = 0;

            PdfPCell tablecell11 = new PdfPCell(new Phrase($"№", body));

            table.AddCell(tablecell11);

            PdfPCell tablecell12 = new PdfPCell(new Phrase($"Вопрос", body));

            table.AddCell(tablecell12);

            PdfPCell tablecell13 = new PdfPCell(new Phrase("Верно", body));

            table.AddCell(tablecell13);

            PdfPCell tablecell14 = new PdfPCell(new Phrase("Комментарий", body));

            table.AddCell(tablecell14);

            foreach (var answer in attestation.AttestationAnswer)
            {
                PdfPCell tablecellx1 = new PdfPCell(new Phrase($"{answer.Answer.NumberOfAsk}", body));
                tablecellx1.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx1);

                PdfPCell tablecellx2 = new PdfPCell(new Phrase($"{answer.Answer.Question}", body));
                tablecellx2.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx2);

                PdfPCell tablecellx3 = new PdfPCell();
                if (answer.Answer.IsRight)
                {
                    tablecellx3 = new PdfPCell(new Phrase("+", body));
                }
                else
                {
                    tablecellx3 = new PdfPCell(new Phrase("-", body));
                }
                tablecellx3.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx3);

                PdfPCell tablecellx4 = new PdfPCell(new Phrase($"{answer.Answer.Commentary}", body));
                tablecellx4.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx4);
            }
            document.Add(table);
            document.Close();

            byte[]       file = memoryStream.ToArray();
            MemoryStream ms   = new MemoryStream();

            ms.Write(file, 0, file.Length);
            ms.Position = 0;

            return(ms);
        }
Пример #16
0
        public void GeneratePDF(SupermarketDB sqlDbContext)
        {
            Console.WriteLine(GeneratingMsg);

            string path = PdfPath;

            Document   doc = new Document();
            FileStream fs  = File.Create(path);

            PdfWriter.GetInstance(doc, fs);

            doc.Open();

            PdfPTable table = new PdfPTable(5);

            table.WidthPercentage = 100;

            var colWidthPercentages = new[] { 70f, 20f, 20f, 70f, 20f };

            table.SetWidths(colWidthPercentages);

            var cell = new PdfPCell(new Phrase(TableHeader));

            cell.Colspan             = 5;
            cell.Padding             = 20;
            cell.HorizontalAlignment = 1;

            table.AddCell(cell);

            DateTime currentDate = DateTime.Now;
            decimal  sum         = -1;
            decimal  grandTotal  = 0;

            var query = sqlDbContext.Database
                        .SqlQuery <AggregatedReportModel>(@"select p.ProductName as Product,
                                                    sd.Quantity as Quantity,
                                                    sd.UnitPrice as UnitPrice,
                                                    s.StoreName as Location,
                                                    m.MeasureName as MeasureName,
                                                    sd.Sum as Sum, 
                                                    sd.Date as Date
                                                   from SaleByDates sd
                                                   join Products p on sd.ProductId = p.ID
                                                   join Measures m on m.ID = p.Measure_ID
                                                   join Supermarkets s on s.Id = sd.SupermarketId
                                                   group by sd.Date, p.ProductName, sd.Quantity, m.MeasureName,
                                                            sd.UnitPrice, s.StoreName, sd.Sum")
                        .ToList();

            foreach (var item in query)
            {
                if (item.Date != currentDate)
                {
                    currentDate = item.Date;
                    if (sum != -1)
                    {
                        var totalSumTextCell = new PdfPCell(new Phrase("Total sum for " + item.Date.ToString("d-MMM-yyyy", CultureInfo.CreateSpecificCulture("en-US")) + ":"));
                        totalSumTextCell.HorizontalAlignment = 2;
                        totalSumTextCell.Colspan             = 4;
                        table.AddCell(totalSumTextCell);

                        var totalSumCell = new PdfPCell(new Phrase(sum.ToString()));
                        table.AddCell(totalSumCell);

                        sum = -1;
                    }

                    var newDateCell = new PdfPCell(new Phrase("Date: " + item.Date.ToString("d-MMM-yyyy", CultureInfo.CreateSpecificCulture("en-US"))));
                    newDateCell.BackgroundColor = BaseColor.LIGHT_GRAY;
                    newDateCell.Colspan         = 5;
                    table.AddCell(newDateCell);

                    var product = new PdfPCell(new Phrase("Product"));
                    product.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(product);

                    var quantity = new PdfPCell(new Phrase("Quantity"));
                    quantity.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(quantity);

                    var unitPrice = new PdfPCell(new Phrase("Unit Price"));
                    unitPrice.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(unitPrice);

                    var location = new PdfPCell(new Phrase("Location"));
                    location.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(location);

                    var sumHeaderCell = new PdfPCell(new Phrase("Sum"));
                    sumHeaderCell.BackgroundColor = BaseColor.LIGHT_GRAY;
                    table.AddCell(sumHeaderCell);
                }

                table.AddCell(item.Product);
                table.AddCell(item.Quantity + " " + item.Measurename);
                table.AddCell(item.UnitPrice.ToString());
                table.AddCell(item.Location);
                table.AddCell(item.Sum.ToString());

                sum        += item.Sum;
                grandTotal += item.Sum;
            }

            var totalSumTextCellEnd = new PdfPCell(new Phrase("Total sum for " + currentDate.ToString("d-MMM-yyyy", CultureInfo.CreateSpecificCulture("en-US")) + ":"));

            totalSumTextCellEnd.HorizontalAlignment = 2;
            totalSumTextCellEnd.Colspan             = 4;
            table.AddCell(totalSumTextCellEnd);

            var totalSumCellEnd = new PdfPCell(new Phrase(sum.ToString()));

            table.AddCell(totalSumCellEnd);


            var grandTotalSumTextCellEnd = new PdfPCell(new Phrase("Grand Total:"));

            grandTotalSumTextCellEnd.HorizontalAlignment = 2;
            grandTotalSumTextCellEnd.Colspan             = 4;
            table.AddCell(grandTotalSumTextCellEnd);

            var grandTotalCell = new PdfPCell(new Phrase(grandTotal.ToString()));

            table.AddCell(grandTotalCell);

            doc.Add(table);
            doc.Close();
        }
Пример #17
0
        public static MemoryStream GetPdfofWorkers(List <long> ids, List <SpecificWorkerModel> workers)
        {
            var memoryStream = new MemoryStream();

            var document = new Document(PageSize.A4, MarginLeft, MarginRight, MarginTop, MarginBottom);

            document.AddTitle("Выгрузка работников");
            document.AddCreationDate();
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

            EncodingProvider encProvider = CodePagesEncodingProvider.Instance;

            Encoding.RegisterProvider(encProvider);
            string arial = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");

            BaseFont baseFont = BaseFont.CreateFont(arial, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            Font body = new Font(baseFont, 10, Font.NORMAL, BaseColor.BLACK);
            Font head = new Font(baseFont, 16, Font.NORMAL, BaseColor.BLACK);

            document.Open();

            workers = workers.Where(x => ids.Contains(x.Id)).ToList();

            document.Add(new Paragraph($"Работники", head));
            document.Add(new Paragraph($" ", body));

            PdfPTable table = new PdfPTable(5)
            {
                TotalWidth  = document.PageSize.Width - 72f - 65f,
                LockedWidth = true
            };

            float[] widths = new float[] { 2.7f, 4f, 4f, 1.5f, 2.5f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;

            PdfPCell tablecell10 = new PdfPCell(new Phrase($"ФИО", body));

            table.AddCell(tablecell10);
            PdfPCell tablecell11 = new PdfPCell(new Phrase($"Должность", body));

            table.AddCell(tablecell11);
            PdfPCell tablecell12 = new PdfPCell(new Phrase($"Компетенции", body));

            table.AddCell(tablecell12);
            PdfPCell tablecell13 = new PdfPCell(new Phrase("Опыт работы", body));

            table.AddCell(tablecell13);
            PdfPCell tablecell14 = new PdfPCell(new Phrase("Предыдущие места работы", body));

            table.AddCell(tablecell14);

            foreach (var worker in workers)
            {
                PdfPCell tablecellx0 = new PdfPCell(new Phrase($"{worker.Initials}", body));
                tablecellx0.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx0);

                PdfPCell tablecellx1 = new PdfPCell(new Phrase($"{worker.Position.Name}", body));
                tablecellx1.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx1);

                StringBuilder builder = new StringBuilder("");

                foreach (var competence in worker.SpecificWorkerCompetencesModels)
                {
                    builder.Append(competence.Competence.Competence + ", ");
                }

                if (builder.ToString() == "")
                {
                    builder.Append("Не обладает компетенциями");
                }
                else
                {
                    builder.Remove(builder.Length - 2, 2);
                }

                PdfPCell tablecellx2 = new PdfPCell(new Phrase($"{builder.ToString()}", body));
                tablecellx2.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx2);

                PdfPCell tablecellx3 = new PdfPCell();
                tablecellx3             = new PdfPCell(new Phrase($"{worker.Experience}", body));
                tablecellx3.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx3);

                PdfPCell tablecellx4 = new PdfPCell(new Phrase($"{worker.PreviousWorkPlaces}", body));
                tablecellx4.PaddingLeft = LeftPadding;
                table.AddCell(tablecellx4);
            }
            document.Add(table);

            document.Close();

            byte[]       file = memoryStream.ToArray();
            MemoryStream ms   = new MemoryStream();

            ms.Write(file, 0, file.Length);
            ms.Position = 0;

            return(ms);
        }
Пример #18
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font time = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 11f, Font.NORMAL);

            Image logo = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png"));

            logo.ScaleToFit(150f, 62f);

            Phrase p1Header = new Phrase("PROPUESTA TÉCNICO ECONÓMICA\n EXÁMENES MÉDICOS\n OCUPACIONALES", baseFontNormal);

            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            float[] width = { 100f, 320f, 100f };
            pdfTab.SetWidths(width);
            pdfTab.TotalWidth  = 520f;
            pdfTab.LockedWidth = true;


            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell(logo);
            PdfPCell pdfCell2 = new PdfPCell(p1Header);
            String   text     = "Página " + writer.PageNumber + " de ";


            //Add paging to header
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetTop(45));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                //Adds "12" in Page 1 of 12
                cb.AddTemplate(headerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetTop(45));
            }
            //Add paging to footer
            {
                Image logoSoftware = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png"));
                logoSoftware.ScaleToFit(140f, 50f);

                var leftCol  = new Paragraph("Mukesh Salaria\n" + "Software Engineer", time);
                var rightCol = new Paragraph("saluslaboris.com.pe\n", time);
                var phone    = new Paragraph("Teléfono: (511) 6407309", time);
                var address  = new Paragraph("     ESTE DOCUMENTO ES PROPIEDAD\n" + "      INTELECTUAL DE SALUS LABORIS", time);
                var fax      = new Paragraph("Av. Alfredo Benavides 4994\n Surco", time);

                leftCol.Alignment  = Element.ALIGN_LEFT;
                rightCol.Alignment = Element.ALIGN_RIGHT;
                fax.Alignment      = Element.ALIGN_RIGHT;
                phone.Alignment    = Element.ALIGN_LEFT;
                address.Alignment  = Element.ALIGN_CENTER;

                var footerTbl = new PdfPTable(3)
                {
                    TotalWidth = 520f, HorizontalAlignment = Element.ALIGN_CENTER, LockedWidth = true
                };
                float[] widths = { 150f, 220f, 150f };
                footerTbl.SetWidths(widths);
                var footerCell1 = new PdfPCell(logoSoftware);
                var footerCell2 = new PdfPCell();
                var footerCell3 = new PdfPCell(rightCol);
                var sep         = new PdfPCell();
                var footerCell4 = new PdfPCell(phone);
                var footerCell5 = new PdfPCell(address);
                var footerCell6 = new PdfPCell(fax);


                footerCell1.Border = 0;
                footerCell2.Border = 0;
                footerCell3.Border = 0;
                footerCell4.Border = 0;
                footerCell5.Border = 0;
                footerCell6.Border = 0;
                footerCell6.HorizontalAlignment = Element.ALIGN_RIGHT;
                sep.Border      = 0;
                sep.FixedHeight = 10f;
                footerCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                footerCell6.PaddingLeft         = 0;
                sep.Colspan = 3;

                footerTbl.AddCell(footerCell1);
                footerTbl.AddCell(footerCell2);
                footerTbl.AddCell(footerCell3);
                footerTbl.AddCell(sep);
                footerTbl.AddCell(footerCell4);
                footerTbl.AddCell(footerCell5);
                footerTbl.AddCell(footerCell6);
                footerTbl.WriteSelectedRows(0, -1, 40, 80, writer.DirectContent);
            }


            PdfPCell pdfCell3 = new PdfPCell();
            PdfPCell pdfCell4 = new PdfPCell();
            PdfPCell pdfCell5 = new PdfPCell(new Phrase(""));

            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
            pdfCell5.HorizontalAlignment = Element.ALIGN_RIGHT;

            pdfCell2.PaddingTop = 9f;
            pdfCell3.PaddingTop = 20f;
            pdfCell5.PaddingTop = 9f;

            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;

            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.AddCell(pdfCell4);
            pdfTab.AddCell(pdfCell5);

            pdfTab.TotalWidth  = 520f;
            pdfTab.LockedWidth = true;

            //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
            //first param is start row. -1 indicates there is no end row and all the rows to be included to write
            //Third and fourth param is x and y position to start writing
            pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);

            //Move the pointer and draw line to separate header section from rest of page
            cb.MoveTo(40, document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
            cb.Stroke();

            //Move the pointer and draw line to separate footer section from rest of page
            cb.MoveTo(40, document.PageSize.GetBottom(50));
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
            cb.Stroke();
        }
        private static void SetFooter(Document document, MemoGarmentPurchasingModel data, int offSet)
        {
            PdfPTable table = new PdfPTable(3)
            {
                WidthPercentage = 100
            };

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

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

            PdfPCell cellColspan2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Colspan             = 2
            };

            cellColspan2.Phrase        = new Phrase($"Keterangan : {data.Remarks}", _smallFont);
            cellColspan2.PaddingBottom = 10;
            table.AddCell(cellColspan2);
            cell.Phrase = new Phrase();
            table.AddCell(cell);

            //cellColspan2.Phrase = new Phrase("Nomor Memo Pusat :", _smallFont);
            //table.AddCell(cellColspan2);
            //cell.Phrase = new Phrase();
            //table.AddCell(cell);

            cell.Phrase = new Phrase();
            table.AddCell(cell);
            cell.Phrase = new Phrase();
            table.AddCell(cell);
            cell.Phrase = new Phrase();
            table.AddCell(cell);

            cell.Phrase = new Phrase("Mengetahui", _smallFont);
            table.AddCell(cell);
            cell.Phrase = new Phrase();
            table.AddCell(cell);
            cell.Phrase = new Phrase($"Solo, {DateTime.UtcNow.AddHours(offSet).ToString("dd MMMM yyyy", new CultureInfo("id-ID"))}", _smallFont);
            table.AddCell(cell);
            cell.Phrase = new Phrase("Kepala Pembukuan", _smallFont);
            table.AddCell(cell);
            cell.Phrase = new Phrase();
            table.AddCell(cell);
            cell.Phrase = new Phrase("Yang Membuat", _smallFont);
            table.AddCell(cell);

            for (var i = 0; i < 4; i++)
            {
                cell.Phrase = new Phrase();
                table.AddCell(cell);
                cell.Phrase = new Phrase();
                table.AddCell(cell);
                cell.Phrase = new Phrase();
                table.AddCell(cell);
            }

            cell.Phrase = new Phrase("(..................)", _smallFont);
            table.AddCell(cell);
            cell.Phrase = new Phrase();
            table.AddCell(cell);
            cell.Phrase = new Phrase($"( {data.CreatedBy} )", _smallFont);
            table.AddCell(cell);

            document.Add(table);
        }
Пример #20
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");

            var document = new Document(PageSize.LETTER);

            document.SetMargins(36f, 36f, 33f, 36f);
            var w = PdfWriter.GetInstance(document, Response.OutputStream);

            document.Open();
            dc = w.DirectContent;

            var cols = new float[3 * 2 - 1];
            var twid = 0f;
            var t    = new PdfPTable(cols.Length);

            for (var i = 0; i < cols.Length; i++)
            {
                if (i % 2 == 1)
                {
                    cols[i] = GAP * 72f;
                }
                else
                {
                    cols[i] = W * 72f;
                }
            }
            foreach (var wid in cols)
            {
                twid += wid;
            }

            t.TotalWidth = twid;
            t.SetWidths(cols);
            t.HorizontalAlignment = Element.ALIGN_CENTER;
            t.LockedWidth         = true;
            t.DefaultCell.Border  = PdfPCell.NO_BORDER;

            var q  = DbUtil.Db.PeopleQuery(qid);
            var q2 = from p in q
                     orderby p.Name2
                     select new
            {
                First    = p.PreferredName,
                Last     = p.LastName,
                PeopleId = p.PeopleId,
                Phone    = p.CellPhone ?? p.HomePhone
            };

            if (!q2.Any())
            {
                document.Add(new Phrase("no data"));
            }
            else
            {
                foreach (var m in q2)
                {
                    AddRow(t, m.First, m.Last, m.Phone, m.PeopleId);
                }
            }
            document.Add(t);

            document.Close();
        }
        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, 60);
            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("UNIT", 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[] { 2f, 2f, 2f, 2f, 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(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: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);
        }
Пример #22
0
        public static void Export(string start, string end)
        {
            using (Document pdfReport = new Document())
            {
                var startDate = DateTime.Parse(start);
                var endDate   = DateTime.Parse(end);

                FileStream file = File.Create("D:\\GirlsReport.pdf");
                PdfWriter.GetInstance(pdfReport, file);
                pdfReport.Open();

                iTextSharp.text.Image girlsImg = iTextSharp.text.Image.GetInstance("../../../girlsIcon.png");
                girlsImg.ScaleToFit(200f, 200f);

                // girlsImg.SetAbsolutePosition(pdfReport.PageSize.Width  - 100f, pdfReport.PageSize.Height - 50f );

                pdfReport.Add(girlsImg);

                //set table
                PdfPTable table = new PdfPTable(5);
                table.TotalWidth  = 550f;
                table.LockedWidth = true;
                float[] widths = new float[] { 150f, 80f, 80f, 150f, 90f };
                table.SetWidths(widths);

                PdfPCell header = new PdfPCell(new Phrase("Aggregated Girls Orders Report"))
                {
                    Colspan             = 5,
                    HorizontalAlignment = 1,
                    BackgroundColor     = new BaseColor(135, 196, 28),
                    PaddingTop          = 10f,
                    PaddingBottom       = 10f
                };

                table.AddCell(header);

                decimal grandSum = 0;

                using (var context = new GirlsAgencyContext())
                {
                    var orderDates = context.Orders
                                     .Where(o => o.Date >= startDate && o.Date <= endDate)
                                     .Select(o => o.Date)
                                     .Distinct()
                                     .ToList();

                    foreach (var date in orderDates)
                    {
                        DisplayHeaderDates(table, date);

                        var orders = context.Orders
                                     .Where(o => o.Date == date)
                                     .Select(o => new
                        {
                            GirlName = o.Girl.FirstName + " " + o.Girl.LastName,
                            o.Duration,
                            PricePerHour = o.Girl.PricePerHour,
                            Client       = o.Customer.FirstName + " " + o.Customer.LastName,
                            Sum          = o.Duration * o.Girl.PricePerHour
                        })
                                     .ToList();

                        foreach (var order in orders)
                        {
                            DisplayColumn(table, order.GirlName);
                            DisplayColumn(table, order.Duration.ToString("F2"));
                            DisplayColumn(table, order.PricePerHour.ToString("F2"));
                            DisplayColumn(table, order.Client);
                            DisplayColumn(table, order.Sum.ToString("F2"));
                        }

                        var totalDateSum = orders.Sum(o => o.Sum);
                        DisplayDateFooter(table, date, totalDateSum);

                        grandSum += totalDateSum;
                    }
                }

                DisplayGrandSumFooter(table, grandSum);

                pdfReport.Add(table);
                pdfReport.Close();
            }
        }
Пример #23
0
        public override void ExecuteResult(ControllerContext context)
        {
            var Response = context.HttpContext.Response;

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "filename=foo.pdf");
            var doc = new Document(PageSize.LETTER, 36, 36, 36, 42);
            var w   = PdfWriter.GetInstance(doc, Response.OutputStream);

            string divtext = "", subdivtext = "";

            divtext    = DbUtil.Db.Programs.Single(p => p.Id == model.prog).Name;
            subdivtext = DbUtil.Db.Divisions.Where(p => p.Id == model.div).Select(p => p.Name).SingleOrDefault();

            string scheduletext = String.Empty;
            var    sdt          = CmsData.Organization.GetDateFromScheduleId(model.schedule);

            if (sdt.HasValue)
            {
                scheduletext = sdt.Value.ToString("dddd h:mm tt");
            }

            var headtext = "Enrollment Control for {0}:{1} {2}".Fmt(divtext, subdivtext, scheduletext);

            w.PageEvent = new HeadFoot(headtext);


            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8);

            doc.Open();

            var t = new PdfPTable(4);

            t.HeaderRows      = 1;
            t.WidthPercentage = 100;
            t.SetWidths(new int[] { 20, 30, 10, 15 });

            var font = FontFactory.GetFont(FontFactory.HELVETICA, 8);

            t.AddCell(new Phrase("Name", boldfont));
            t.AddCell(new Phrase("Organization", boldfont));
            t.AddCell(new Phrase("Location", boldfont));
            t.AddCell(new Phrase("Member Type", boldfont));

            foreach (var m in model.list())
            {
                t.AddCell(new Phrase(m.Name, font));
                t.AddCell(new Phrase(m.Organization, font));
                t.AddCell(new Phrase(m.Location, font));
                t.AddCell(new Phrase(m.MemberType, font));
            }
            if (t.Rows.Count > 1)
            {
                doc.Add(t);
            }
            else
            {
                doc.Add(new Phrase("no data"));
            }
            doc.Close();
        }
Пример #24
0
        public byte[] GeneratePDF(int EventBookingID)
        {
            MemoryStream memoryStream = new MemoryStream();
            Document     document     = new Document(PageSize.A5, 0, 0, 0, 0);
            PdfWriter    writer       = PdfWriter.GetInstance(document, memoryStream);

            document.Open();

            BookEvent bookEvent = new BookEvent();

            bookEvent = db.BookEvents.Find(EventBookingID);
            var userName = User.Identity.GetUserName();
            var student  = db.students.Where(x => x.StudentEmail == userName).FirstOrDefault();

            iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.RED);
            iTextSharp.text.Font font_body      = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, iTextSharp.text.Color.BLUE);

            // Create the heading paragraph with the headig font
            PdfPTable table1 = new PdfPTable(1);
            PdfPTable table2 = new PdfPTable(5);
            PdfPTable table3 = new PdfPTable(1);

            iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator();
            seperator.Offset = -6f;
            // Remove table cell
            table1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

            table1.WidthPercentage = 80;
            table1.SetWidths(new float[] { 100 });
            table2.WidthPercentage = 80;
            table3.SetWidths(new float[] { 100 });
            table3.WidthPercentage = 80;

            PdfPCell cell = new PdfPCell(new Phrase(""));

            cell.Colspan = 3;
            table1.AddCell("\n");
            table1.AddCell(cell);
            table1.AddCell("\n\n");
            table1.AddCell(
                "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" +
                "Blue Sky Car Rental \n" +
                "Email :[email protected]" + "\n" +
                "\n" + "\n");
            table1.AddCell("------------Personal Details--------------!");

            table1.AddCell("First Name : \t" + student.StudentName);
            table1.AddCell("Last Name : \t" + student.StudentSurname);
            table1.AddCell("Email : \t" + student.StudentEmail);
            table1.AddCell("Phone Number : \t" + student.StudentContact);
            table1.AddCell("Gender : \t" + student.StudentGender);
            table1.AddCell("Address : \t" + student.StudentAddress);

            table1.AddCell("\n------------Rental details--------------!\n");

            table1.AddCell("Booking Ref. # : \t" + bookEvent.RefNum);
            table1.AddCell("Date Booked : \t" + bookEvent.DateBookinFor.ToShortDateString());
            //table1.AddCell("Number Of days : \t" + @event.Duration);
            //table1.AddCell("Total Rental Cost Due: \t" + @event.Amount.ToString("C"));
            //table1.AddCell("Amount Paid: \t" + @event.AmountPaid.ToString("C"));
            //table1.AddCell("Status : \t" + @event.Status);
            //table1.AddCell("Deposit Payed date : \t" + DateTime.Now);

            table1.AddCell("\n");

            table3.AddCell("------------Looking forward to hear from you soon--------------!");

            //////Intergrate information into 1 document
            //var qrCode = iTextSharp.text.Image.GetInstance(reservation.QrCodeImage);
            //qrCode.ScaleToFit(200, 200);
            table1.AddCell(cell);
            document.Add(table1);
            //document.Add(qrCode);
            document.Add(table3);
            document.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            return(bytes);
        }
Пример #25
0
        protected void imbtnPDFButton_Click(object sender, EventArgs e)
        {
            try
            {
                string text  = Session[ApplicationSession.OrganisationName].ToString();
                string text1 = Session[ApplicationSession.OrganisationAddress].ToString();
                string text2 = "BreakDown Maintainance Report";

                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<div align='center' style='font-size:16px;font-weight:bold;color:Black;'>");
                        sb.Append(text);
                        sb.Append("</div>");
                        sb.Append("<br/>");
                        sb.Append("<div align='center' style='font-size:13px;font-weight:bold;color:Black;'>");
                        sb.Append(text1);
                        sb.Append("</div>");
                        sb.Append("<br/>");
                        sb.Append("<div align='center' style='font-size:26px;color:Maroon;'><b>");
                        sb.Append(text2);
                        sb.Append("</b></div>");
                        sb.Append("<br/>");

                        sb.Append("<br/>");

                        PdfPTable pdfPTable = new PdfPTable(gvBreakdownMaintainance.HeaderRow.Cells.Count);

                        //TableCell headerCell = new TableCell();

                        PdfPCell headerCell = new PdfPCell(new Phrase("Sr No."));
                        headerCell.Padding             = 5;
                        headerCell.BorderWidth         = 1.5f;
                        headerCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell);

                        PdfPCell headerCell1 = new PdfPCell(new Phrase("Maintainance Date"));
                        headerCell1.Padding             = 5;
                        headerCell1.BorderWidth         = 1.5f;
                        headerCell1.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell1.VerticalAlignment   = Element.ALIGN_MIDDLE;

                        pdfPTable.AddCell(headerCell1);


                        PdfPCell headerCell2 = new PdfPCell(new Phrase("Start Time"));
                        headerCell2.Padding             = 5;
                        headerCell2.BorderWidth         = 1.5f;
                        headerCell2.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell2);

                        PdfPCell headerCell3 = new PdfPCell(new Phrase("End Time"));
                        headerCell3.Padding             = 5;
                        headerCell3.BorderWidth         = 1.5f;
                        headerCell3.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell3.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell3);

                        PdfPCell headerCell4 = new PdfPCell(new Phrase("Equipment Tag No"));
                        headerCell4.Padding             = 5;
                        headerCell4.BorderWidth         = 1.5f;
                        headerCell4.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell4.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell4);

                        PdfPCell headerCell5 = new PdfPCell(new Phrase("Equipment Name"));
                        headerCell5.Padding             = 5;
                        headerCell5.BorderWidth         = 1.5f;
                        headerCell5.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell5.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell5);

                        PdfPCell headerCell6 = new PdfPCell(new Phrase("Part No"));
                        headerCell6.Padding             = 5;
                        headerCell6.BorderWidth         = 1.5f;
                        headerCell6.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell6.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell6);

                        PdfPCell headerCell7 = new PdfPCell(new Phrase("Part Name"));
                        headerCell7.Padding             = 5;
                        headerCell7.BorderWidth         = 1.5f;
                        headerCell7.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell7.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell7);

                        PdfPCell headerCell8 = new PdfPCell(new Phrase("Area"));
                        headerCell8.Padding             = 5;
                        headerCell8.BorderWidth         = 1.5f;
                        headerCell8.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell8.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell8);

                        PdfPCell headerCell9 = new PdfPCell(new Phrase("Dept."));
                        headerCell9.Padding             = 5;
                        headerCell9.BorderWidth         = 1.5f;
                        headerCell9.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell9.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell9);

                        PdfPCell headerCell10 = new PdfPCell(new Phrase("Section"));
                        headerCell10.Padding             = 5;
                        headerCell10.BorderWidth         = 1.5f;
                        headerCell10.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell10.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell10);

                        PdfPCell headerCell11 = new PdfPCell(new Phrase("Cause"));
                        headerCell11.Padding             = 5;
                        headerCell11.BorderWidth         = 1.5f;
                        headerCell11.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell11.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell11);

                        PdfPCell headerCell12 = new PdfPCell(new Phrase("Details of breakdown"));
                        headerCell12.Padding             = 5;
                        headerCell12.BorderWidth         = 1.5f;
                        headerCell12.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell12.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell12);

                        PdfPCell headerCell13 = new PdfPCell(new Phrase("Action Taken"));
                        headerCell13.Padding             = 5;
                        headerCell13.BorderWidth         = 1.5f;
                        headerCell13.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell13.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell13);

                        PdfPCell headerCell14 = new PdfPCell(new Phrase("Rectified By"));
                        headerCell14.Padding             = 5;
                        headerCell14.BorderWidth         = 1.5f;
                        headerCell14.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell14.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell14);

                        PdfPCell headerCel15 = new PdfPCell(new Phrase("Remark"));
                        headerCel15.Padding             = 5;
                        headerCel15.BorderWidth         = 1.5f;
                        headerCel15.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCel15.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCel15);

                        PdfPCell headerCell16 = new PdfPCell(new Phrase("UserName"));
                        headerCell16.Padding             = 5;
                        headerCell16.BorderWidth         = 1.5f;
                        headerCell16.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell16.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell16);

                        PdfPCell headerCell17 = new PdfPCell(new Phrase("Status"));
                        headerCell17.Padding             = 5;
                        headerCell17.BorderWidth         = 1.5f;
                        headerCell17.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell17.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell17);

                        PdfPCell headerCell18 = new PdfPCell(new Phrase("Change Status"));
                        headerCell18.Padding             = 5;
                        headerCell18.BorderWidth         = 1.5f;
                        headerCell18.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell18.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell18);

                        PdfPCell headerCell19 = new PdfPCell(new Phrase("Edit"));
                        headerCell19.Padding             = 5;
                        headerCell19.BorderWidth         = 1.5f;
                        headerCell19.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell19.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell19);

                        PdfPCell headerCell20 = new PdfPCell(new Phrase("Delete"));
                        headerCell20.Padding             = 5;
                        headerCell20.BorderWidth         = 1.5f;
                        headerCell20.HorizontalAlignment = Element.ALIGN_CENTER;
                        headerCell20.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(headerCell20);


                        float[] widthsTAS = { 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f, 300f };
                        pdfPTable.SetWidths(widthsTAS);

                        for (int i = 0; i < gvBreakdownMaintainance.Rows.Count; i++)
                        {
                            if (gvBreakdownMaintainance.Rows[i].RowType == DataControlRowType.DataRow)
                            {
                                for (int j = 0; j < gvBreakdownMaintainance.Columns.Count; j++)
                                {
                                    string cellText = Server.HtmlDecode(gvBreakdownMaintainance.Rows[i].Cells[j].Text);
                                    gvBreakdownMaintainance.Columns[1].Visible = false;
                                    DateTime dDate;
                                    double   dbvalue;
                                    int      intvalue;

                                    if (DateTime.TryParse(cellText, out dDate))
                                    {
                                        PdfPCell CellTwoHdr = new PdfPCell(new Phrase(cellText));
                                        CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
                                        CellTwoHdr.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                        CellTwoHdr.Padding             = 5;
                                        pdfPTable.AddCell(CellTwoHdr);
                                    }
                                    else if (double.TryParse(cellText, out dbvalue) || Int32.TryParse(cellText, out intvalue))
                                    {
                                        PdfPCell CellTwoHdr = new PdfPCell(new Phrase(cellText));
                                        CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
                                        CellTwoHdr.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                        CellTwoHdr.Padding             = 5;
                                        pdfPTable.AddCell(CellTwoHdr);
                                    }
                                    else
                                    {
                                        PdfPCell CellTwoHdr = new PdfPCell(new Phrase(cellText));
                                        CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
                                        CellTwoHdr.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                        CellTwoHdr.Padding             = 5;
                                        pdfPTable.AddCell(CellTwoHdr);
                                    }
                                }
                                pdfPTable.HeaderRows = 1;
                            }
                        }


                        var imageURL = Server.MapPath("\\images") + "\\GEAProcess_large_20122024.jpg";
                        iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);

                        jpg.Alignment = Element.ALIGN_CENTER;
                        jpg.SetAbsolutePosition(30, 1060);

                        //For IDMC Logo
                        var imageURL1 = Server.MapPath("\\images") + "\\GEAProcess_large_20122024.jpg";
                        iTextSharp.text.Image jpg1 = iTextSharp.text.Image.GetInstance(imageURL1);

                        jpg1.Alignment = Element.ALIGN_RIGHT;
                        jpg1.SetAbsolutePosition(700, 1060);

                        StringReader sr = new StringReader(sb.ToString());
                        //StringReader sr1 = new StringReader(sb1.ToString());
                        Document pdfDoc = new Document(PageSize.A1, -150f, -150f, 10f, 0f);

                        HTMLWorker          htmlparser      = new HTMLWorker(pdfDoc);
                        PdfWriter           writer          = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                        PDFBackgroundHelper pageEventHelper = new PDFBackgroundHelper();
                        writer.PageEvent = pageEventHelper;
                        pdfDoc.Open();
                        htmlparser.Parse(sr);
                        pdfDoc.Add(jpg);
                        pdfDoc.Add(jpg1);
                        pdfDoc.Add(pdfPTable);
                        //htmlparser.Parse(sr1);

                        //----------- FOOTER -----------
                        PdfPTable footer        = new PdfPTable(2);
                        PdfPTable footer2       = new PdfPTable(2);
                        PdfPCell  footer_Cell1  = new PdfPCell(new Phrase("Shift"));
                        PdfPCell  footer2_Cell1 = new PdfPCell(new Phrase("Shift Incharge"));
                        PdfPCell  common_Cell   = new PdfPCell(new Phrase(": ____________________"));

                        float[] cols = new float[] { 100, 300 };

                        footer.SetWidthPercentage(cols, PageSize.A3);
                        footer2.SetWidthPercentage(cols, PageSize.A3);
                        footer_Cell1.Border  = 0;
                        footer2_Cell1.Border = 0;
                        common_Cell.Border   = 0;
                        footer.AddCell(footer_Cell1);
                        footer.AddCell(common_Cell);
                        footer2.AddCell(footer2_Cell1);
                        footer2.AddCell(common_Cell);
                        footer.WriteSelectedRows(0, -1, pdfDoc.LeftMargin + 125, 90, writer.DirectContent);
                        footer2.WriteSelectedRows(0, -1, pdfDoc.LeftMargin + 125, 70, writer.DirectContent);
                        //----------- /FOOTER -----------

                        pdfDoc.Close();
                        Response.ContentType = "application/pdf";

                        Response.AddHeader("content-disposition", "attachment;" + "filename=BreakDownMaintainanceReport" + DateTime.Now.Date.ToString("dd-MM-yyyy") + ".pdf");
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.Write(pdfDoc);
                        Response.Flush();
                        Response.Clear();
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Error", ex);
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp",
                                                   "<script>alert('Oops! There is some technical Problem. Contact to your Administrator.');</script>");
            }
        }
Пример #26
0
    public byte[] PrintAppointmentInvoice(string invoiceId, string appointmentToken, string doctorName,
                                          string appointmentDate, string appointmentTime)
    {
        Document document   = new Document(PageSize.A4);
        Font     NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);

        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer    = PdfWriter.GetInstance(document, memoryStream);
            PdfPTable table     = null;
            Phrase    phrase    = null;
            PdfPCell  cell      = null;
            Paragraph paragraph = null;
            Color     color     = null;

            document.Open();

            table = new PdfPTable(2);
            float[] widths = new float[] { 5f, 10f };
            table.SetWidths(widths);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("../images/logo.png"));
            image.ScaleAbsolute(80, 80);
            cell        = new PdfPCell(image);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("ABC Hospital\n\n", FontFactory.GetFont("Arial", 18, Font.BOLD, Color.RED)));
            phrase.Add(new Chunk("123, Bodakdev\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ahmedabad 380015\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("INDIA\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ph:- 9543289345\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Website:- http://www.abchospital.com\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));

            cell        = new PdfPCell(phrase);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            color = new Color(System.Drawing.ColorTranslator.FromHtml("#000000"));
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);

            phrase = new Phrase();
            phrase.Add(new Chunk("APPOINTMENT INVOICE\n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.BLACK)));

            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment     = Element.ALIGN_CENTER;
            paragraph.SpacingBefore = 50;
            paragraph.SpacingAfter  = 30;

            document.Add(table);
            document.Add(paragraph);

            table  = new PdfPTable(2);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice ID", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(invoiceId, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(DateTime.Now.ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Token", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentToken, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Doctor", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(doctorName, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentDate, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Time", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentTime, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            document.Add(table);

            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);
            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);

            document.Close();
            byte[] bytes = memoryStream.ToArray();
            using (FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath("../Invoice/Appointments/" + invoiceId + ".pdf")))
            {
                fs.Write(bytes, 0, (int)bytes.Length);
            }
            memoryStream.Close();
            return(bytes);
        }
    }
Пример #27
0
        public ActionResult DisbursementSummaryReport(String StartDate, String EndDate, String CompanyId, String BranchId)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // =====
            // Fonts
            // =====
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Company).FirstOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.ContactNumber).FirstOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Disbursement Summary Report", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Date From " + Convert.ToDateTime(StartDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " to " + Convert.ToDateTime(EndDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);
            document.Add(line);

            // ===================
            // Data (Disbursement)
            // ===================
            var disbursements = from d in db.TrnDisbursements
                                where d.CVDate >= Convert.ToDateTime(StartDate) &&
                                d.CVDate <= Convert.ToDateTime(EndDate) &&
                                d.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                d.BranchId == Convert.ToInt32(BranchId) &&
                                d.IsLocked == true
                                select new
            {
                Id          = d.Id,
                Branch      = d.MstBranch.Branch,
                CVNumber    = d.CVNumber,
                CVDate      = d.CVDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture),
                Supplier    = d.MstArticle.Article,
                Particulars = d.Particulars,
                BankId      = d.BankId,
                Bank        = d.MstArticle1.Article,
                CheckNumber = d.CheckNumber,
                Amount      = d.Amount
            };

            if (disbursements.Any())
            {
                // ============
                // Branch Title
                // ============
                PdfPTable branchTitle           = new PdfPTable(1);
                float[]   widthCellsBranchTitle = new float[] { 100f };
                branchTitle.SetWidths(widthCellsBranchTitle);
                branchTitle.WidthPercentage = 100;
                PdfPCell branchHeaderColspan = (new PdfPCell(new Phrase(branch, fontArial12Bold))
                {
                    HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 14f, Border = 0
                });
                branchTitle.AddCell(branchHeaderColspan);
                document.Add(branchTitle);

                // ====
                // Data
                // ====
                PdfPTable data            = new PdfPTable(7);
                float[]   widthsCellsData = new float[] { 15f, 11f, 25f, 25f, 20f, 20f, 20f };
                data.SetWidths(widthsCellsData);
                data.WidthPercentage = 100;
                data.AddCell(new PdfPCell(new Phrase("CV Number", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("CV Date", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Supplier", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Particulars", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Bank", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("CheckNumber", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Amount", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });

                Decimal total = 0;
                foreach (var disbursement in disbursements)
                {
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CVNumber, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CVDate, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Supplier, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Particulars, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Bank, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CheckNumber, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Amount.ToString("#,##0.00"), fontArial10))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    total += disbursement.Amount;
                }

                // =====
                // Total
                // =====
                data.AddCell(new PdfPCell(new Phrase("Total", fontArial10Bold))
                {
                    Colspan = 6, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 10f, PaddingLeft = 10f
                });
                data.AddCell(new PdfPCell(new Phrase(total.ToString("#,##0.00"), fontArial10Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                });
                document.Add(data);
            }

            // Document End
            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Пример #28
0
        public MemoryStream GeneratePdfTemplate(CostCalculationGarmentViewModel viewModel, int timeoffset)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 6);
            Font     bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 6);
            DateTime now         = DateTime.Now;

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

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

            float    margin          = 10;
            float    printedOnHeight = 10;
            float    startY          = 840 - margin;
            PdfPCell cell_colon      = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Phrase = new Phrase(":", normal_font)
            };

            #region Header
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. DAN LIRIS", 10, 820, 0);
            cb.SetFontAndSize(bf_bold, 12);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BUDGET EXPORT GARMENT" + (viewModel.IsPosted ? "" : " (DRAFT)"), 10, 805, 0);
            cb.EndText();
            #endregion

            #region Detail 1 (Top)
            PdfPTable table_detail1 = new PdfPTable(9);
            table_detail1.TotalWidth = 570f;

            float[] detail1_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1.5f, 0.1f, 2f };
            table_detail1.SetWidths(detail1_widths);

            PdfPCell cell_detail1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2
            };

            cell_detail1.Phrase = new Phrase("RO", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.RO_Number}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("SECTION", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.Section}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("CONFIRM ORDER", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.ConfirmDate.AddHours(timeoffset).ToString("dd/MM/yyyy")}", normal_font);
            table_detail1.AddCell(cell_detail1);
            #endregion

            #region Draw Detail 1
            float row1Y = 800;
            table_detail1.WriteSelectedRows(0, -1, 10, row1Y, cb);
            #endregion

            bool isDollar = viewModel.Rate.Id != 0;

            #region Detail 2 (Bottom, Column 1)
            PdfPTable table_detail2 = new PdfPTable(2);
            table_detail2.TotalWidth = 230f;

            float[] detail2_widths = new float[] { 2f, 5f };
            table_detail2.SetWidths(detail2_widths);

            PdfPCell cell_detail2 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };

            cell_detail2.Phrase = new Phrase("BUYER AGENT", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Buyer.Code}" + " - " + $"{viewModel.Buyer.Name}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("BUYER BRAND", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.BuyerBrand.Code}" + " - " + $"{viewModel.BuyerBrand.Name}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("ARTICLE", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Article}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("DESCRIPTION", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.CommodityDescription}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("QTY", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Quantity} PCS", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("DELIVERY", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.DeliveryDate.AddHours(timeoffset).ToString("dd/MM/yyyy")}", normal_font);
            table_detail2.AddCell(cell_detail2);
            #endregion

            #region Detail 3 (Bottom, Column 2)
            PdfPTable table_detail3 = new PdfPTable(8);
            table_detail3.TotalWidth = 330f;

            float[] detail3_widths = new float[] { 3.25f, 4.75f, 1.9f, 0.2f, 1.9f, 1.9f, 0.2f, 1.9f };
            table_detail3.SetWidths(detail3_widths);

            double   budgetCost   = isDollar ? viewModel.ConfirmPrice * viewModel.Rate.Value ?? 0 : viewModel.ConfirmPrice ?? 0;
            double   totalBudget  = budgetCost * viewModel.Quantity ?? 0;
            PdfPCell cell_detail3 = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_right = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_colspan6 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 6
            };
            PdfPCell cell_detail3_colspan8 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 8
            };

            cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("TOTAL BUDGET", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiah(totalBudget)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3_colspan6.Phrase = new Phrase("STANDARD MINUTE VALUE", normal_font);
            table_detail3.AddCell(cell_detail3_colspan6);

            double freightCost = 0;
            foreach (CostCalculationGarment_MaterialViewModel item in viewModel.CostCalculationGarment_Materials)
            {
                freightCost += item.TotalShippingFee * viewModel.Quantity.GetValueOrDefault();
            }

            cell_detail3.Border = Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("BEA ANGKUT", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiah(freightCost)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. CUT", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.NO_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Cutting}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.NO_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. SEW", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Sewing}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase("", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. FIN", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Finishing}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. TOT", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Total}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3_colspan8.Phrase = new Phrase("BUDGET COST / PCS" + "".PadRight(5) + $"{Number.ToRupiah(budgetCost)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan8);
            //cell_detail3_colspan8.Phrase = isDollar ? new Phrase($"US$ 1 = {Number.ToRupiah(viewModel.Rate.Value)}" + "".PadRight(10) + $"CONFIRM PRICE : {Number.ToDollar(viewModel.ConfirmPrice)} / PCS", normal_font) : new Phrase($"CONFIRM PRICE : {Number.ToRupiah(viewModel.ConfirmPrice)} / PCS", normal_font);
            cell_detail3_colspan8.Phrase = isDollar ? new Phrase($"CONFIRM PRICE : {Number.ToRupiah(viewModel.ConfirmPrice)} / PCS", normal_font) : new Phrase($"CONFIRM PRICE : {Number.ToDollar(viewModel.ConfirmPrice)} / PCS", normal_font);
            table_detail3.AddCell(cell_detail3_colspan8);
            cell_detail3_colspan8.Border = Rectangle.NO_BORDER;
            cell_detail3_colspan8.HorizontalAlignment = Element.ALIGN_CENTER;
            cell_detail3_colspan8.Phrase = new Phrase($"ALLOWANCE >> FABRIC = {viewModel.FabricAllowance}%, ACC = {viewModel.AccessoriesAllowance}%", normal_font);
            table_detail3.AddCell(cell_detail3_colspan8);
            #endregion

            #region Signature
            PdfPTable table_signature = new PdfPTable(5);
            table_signature.TotalWidth = 570f;

            float[] signature_widths = new float[] { 1f, 1f, 1f, 1f, 1f };
            table_signature.SetWidths(signature_widths);

            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_signature.Phrase = new Phrase("Yg Membuat,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Mengetahui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Menyetujui,", normal_font);
            table_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);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);

            var AssignmentKabag = "";
            var AssignmentPurch = "";
            var AssignmentIE    = "";

            if (viewModel.ApprovalMD.IsApproved)
            {
                AssignmentKabag = viewModel.ApprovalMD.ApprovedBy;
            }
            else
            {
                AssignmentKabag = " ____________________ ";
            }

            if (viewModel.ApprovalPurchasing.IsApproved)
            {
                AssignmentPurch = viewModel.ApprovalPurchasing.ApprovedBy;
            }
            else
            {
                AssignmentPurch = " ____________________ ";
            }

            if (viewModel.ApprovalIE.IsApproved)
            {
                AssignmentIE = viewModel.ApprovalIE.ApprovedBy;
            }
            else
            {
                AssignmentIE = " ____________________ ";
            }

            string AssignMD = viewModel.IsPosted ? viewModel.CreatedBy : " ";

            cell_signature.Phrase = new Phrase("(  " + AssignMD + "  )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(  " + AssignmentIE + "  )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(  " + AssignmentKabag + "  )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(  " + AssignmentPurch + "  )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("( Haenis Gunarto )", normal_font);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie IE", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie Pembelian", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Direktur Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            #endregion

            #region Cost Calculation Material
            PdfPTable table_ccm = new PdfPTable(11);
            table_ccm.TotalWidth = 570f;

            float[] ccm_widths = new float[] { 1f, 3f, 2f, 6f, 2f, 3f, 2f, 2f, 3f, 3f, 3f };
            table_ccm.SetWidths(ccm_widths);

            PdfPCell cell_ccm = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_ccm.Phrase = new Phrase("NO", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("CATEGORIES", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("KODE", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("USAGE", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("PRICE", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("QTY", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("UNIT", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("AMOUNT", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("PO NUMBER", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("BEA KIRIM", bold_font);
            table_ccm.AddCell(cell_ccm);

            float row2Y               = row1Y - table_detail1.TotalHeight - 5;
            float row3Height          = table_detail2.TotalHeight > table_detail3.TotalHeight ? table_detail2.TotalHeight : table_detail3.TotalHeight;
            float row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
            float row2AllowedHeight   = row2Y - printedOnHeight - margin;

            for (int i = 0; i < viewModel.CostCalculationGarment_Materials.Count; i++)
            {
                //NO
                cell_ccm.Phrase = new Phrase((i + 1).ToString(), normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_LEFT;

                //CATEGORY
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Category.name, normal_font);
                table_ccm.AddCell(cell_ccm);

                //KODE PRODUK
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Product.Code, normal_font);
                table_ccm.AddCell(cell_ccm);

                //DESCRIPTION
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Description, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;

                double usage = viewModel.CostCalculationGarment_Materials[i].Quantity ?? 0;
                cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(usage), normal_font);
                table_ccm.AddCell(cell_ccm);

                double price = viewModel.CostCalculationGarment_Materials[i].Price ?? 0;
                cell_ccm.Phrase = new Phrase(String.Format("{0}/{1}", Number.ToRupiahWithoutSymbol(price), viewModel.CostCalculationGarment_Materials[i].UOMPrice.Unit), normal_font);
                table_ccm.AddCell(cell_ccm);

                double factor;
                if (viewModel.CostCalculationGarment_Materials[i].Category.name == "FABRIC")
                {
                    factor = viewModel.FabricAllowance ?? 0;
                }
                else
                {
                    factor = viewModel.AccessoriesAllowance ?? 0;
                }
                double totalQuantity  = viewModel.Quantity ?? 0;
                double quantity       = (100 + factor) / 100 * usage * totalQuantity;
                var    budgetQuantity = Number.ToRupiahWithoutSymbol(Math.Ceiling(viewModel.CostCalculationGarment_Materials[i].BudgetQuantity));
                cell_ccm.Phrase = new Phrase(budgetQuantity.Substring(0, budgetQuantity.Length - 3), normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER;
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].UOMQuantity.Unit, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;

                if (viewModel.CostCalculationGarment_Materials[i].isFabricCM == true)
                {
                    cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(0), normal_font);
                    table_ccm.AddCell(cell_ccm);
                }
                else
                {
                    double amount = viewModel.CostCalculationGarment_Materials[i].BudgetQuantity * price;
                    cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(amount), normal_font);
                    table_ccm.AddCell(cell_ccm);
                }


                cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER;
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].PO_SerialNumber, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;
                var beaKirim = Number.ToRupiahWithoutSymbol(Math.Ceiling(viewModel.CostCalculationGarment_Materials[i].TotalShippingFee * viewModel.Quantity.GetValueOrDefault()));
                cell_ccm.Phrase = new Phrase(beaKirim.Substring(0, beaKirim.Length - 3), normal_font);
                table_ccm.AddCell(cell_ccm);

                float currentHeight = table_ccm.TotalHeight;
                if (currentHeight / row2RemainingHeight > 1)
                {
                    if (currentHeight / row2AllowedHeight > 1)
                    {
                        PdfPRow headerRow = table_ccm.GetRow(0);
                        PdfPRow lastRow   = table_ccm.GetRow(table_ccm.Rows.Count - 1);
                        table_ccm.DeleteLastRow();
                        table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);
                        table_ccm.DeleteBodyRows();
                        this.DrawPrintedOn(now, bf, cb);
                        document.NewPage();
                        table_ccm.Rows.Add(headerRow);
                        table_ccm.Rows.Add(lastRow);
                        table_ccm.CalculateHeightsFast();
                        row2Y = startY;
                        row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
                        row2AllowedHeight   = row2Y - printedOnHeight - margin;
                    }
                }
            }
            #endregion

            #region Draw Others
            table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);

            float row3Y = row2Y - table_ccm.TotalHeight - 5;
            float row3RemainigHeight = row3Y - printedOnHeight - margin;
            if (row3RemainigHeight < row3Height)
            {
                this.DrawPrintedOn(now, bf, cb);
                row3Y = startY;
                document.NewPage();
            }

            table_detail2.WriteSelectedRows(0, -1, margin, row3Y, cb);

            table_detail3.WriteSelectedRows(0, -1, margin + table_detail2.TotalWidth + 10, row3Y, cb);

            float signatureY = row3Y - row3Height - 10;
            float signatureRemainingHeight = signatureY - printedOnHeight - margin;
            if (signatureRemainingHeight < table_signature.TotalHeight)
            {
                this.DrawPrintedOn(now, bf, cb);
                signatureY = startY;
                document.NewPage();
            }
            table_signature.WriteSelectedRows(0, -1, margin, signatureY, cb);

            this.DrawPrintedOn(now, bf, cb);
            #endregion

            document.Close();

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

            return(stream);
        }
        public void PrintCollectionSchedule(List <GetPrintScheduleByDID_Result> results, ReportBuilderModel model)
        {
            MemoryStream workStream = new MemoryStream();
            Document     document   = new Document();

            PdfWriter.GetInstance(document, workStream).CloseStream = false;
            PdfPTable table = new PdfPTable(8);

            table.TotalWidth = 550f;
            //fix the absolute width of the table
            table.LockedWidth = true;
            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 7f, 4f, 2f, 3f, 3f, 3f, 3f, 4f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            //leave a gap before and after the table
            table.SpacingBefore = 10f;
            table.SpacingAfter  = 10f;
            Font     bold = new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            Phrase   p    = new Phrase(model.ReportHeading, bold);
            PdfPCell cell = new PdfPCell(p);

            cell.BackgroundColor     = new iTextSharp.text.BaseColor(51, 192, 192);
            cell.Colspan             = 8;
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment   = 1;
            table.AddCell(cell);

            Font     b             = new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
            Phrase   reportSummary = new Phrase(string.Format("Collection Schedule on : {0}", DateTime.Now.Date.ToShortDateString()), b);
            PdfPCell cellHeading   = new PdfPCell(reportSummary);

            cellHeading.BackgroundColor     = new iTextSharp.text.BaseColor(192, 192, 192);
            cellHeading.Colspan             = 8;
            cellHeading.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            cellHeading.VerticalAlignment   = 1;
            table.AddCell(cellHeading);

            //Add Branch and Total Amount
            Phrase   branchSummary = new Phrase(string.Format("Branch: {0} Schedule Date : {1} Actual Paid : {2}", model.BranchName, model.ScheduleDate, model.ActualPaid), b);
            PdfPCell cellHeading1  = new PdfPCell(branchSummary);

            cellHeading1.BackgroundColor     = new iTextSharp.text.BaseColor(192, 192, 192);
            cellHeading1.Colspan             = 8;
            cellHeading1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            cellHeading1.VerticalAlignment   = 1;
            table.AddCell(cellHeading1);

            PdfPCell cellBranchName = new PdfPCell(new Phrase("CL Code/Name"));

            cellBranchName.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellBranchName);

            PdfPCell cellClientName = new PdfPCell(new Phrase("EMI Date"));

            cellClientName.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellClientName);

            PdfPCell cellAmountPaid = new PdfPCell(new Phrase("EMI"));

            cellAmountPaid.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellAmountPaid);

            PdfPCell cellPaymentDate = new PdfPCell(new Phrase("InstallNo"));

            cellPaymentDate.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellPaymentDate);

            PdfPCell cellPrincipleAmount = new PdfPCell(new Phrase("Amt Paid"));

            cellPrincipleAmount.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellPrincipleAmount);

            PdfPCell cellInterestAmount = new PdfPCell(new Phrase("Balance"));

            cellInterestAmount.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellInterestAmount);


            PdfPCell cellSignature = new PdfPCell(new Phrase("Sign"));

            cellSignature.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellSignature);

            PdfPCell cellAdditonalRemark = new PdfPCell(new Phrase("Remark"));

            cellAdditonalRemark.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellAdditonalRemark);


            long?totalInstallment            = results.Max(x => x.EMINumber);
            GetPrintScheduleByDID_Result row = results.FirstOrDefault(x => x.ActualPaidAmount != 0);
            decimal?balance           = row.ActualPaidAmount;
            decimal?amountPaidTillNow = 0;
            decimal remainBalanceAll  = 0;

            foreach (Data.GetPrintScheduleByDID_Result item in results.ToList())
            {
                table.AddCell(item.ClientCode + " / " + item.ClientName);

                table.AddCell(item.EMIDate.Value.ToShortDateString());

                table.AddCell(item.EMI.ToString());

                table.AddCell(item.EMINumber.ToString() + " / " + totalInstallment);

                table.AddCell(item.AmountPaid.ToString());

                amountPaidTillNow += item.AmountPaid;
                decimal remainBalance = balance.Value - amountPaidTillNow.Value;
                remainBalanceAll = remainBalance;
                table.AddCell(remainBalance.ToString());

                table.AddCell(".............");

                table.AddCell(".............");
            }


            //Final Row summary
            table.AddCell(" ");

            table.AddCell(" ");

            table.AddCell("Total");

            table.AddCell(" - ");

            table.AddCell(amountPaidTillNow.ToString());

            table.AddCell(remainBalanceAll.ToString());

            table.AddCell(" ");

            table.AddCell(" ");


            document.Open();
            document.Add(table);
            document.Add(new Paragraph(DateTime.Now.ToString()));
            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;
            Response.Buffer     = true;
            Response.AddHeader("Content-Disposition", "attachment; filename= " + Server.HtmlEncode(string.Format("CollectionSchedule_{0}.pdf", DateTime.Now.Date.ToShortDateString())));
            Response.ContentType = "APPLICATION/pdf";
            Response.BinaryWrite(byteInfo);
        }
Пример #30
0
        private void CreatePDF(string fileName, List <Ticket_Group> Tickets, List <MainContract> msc, string Account_date, string MadeBillDate, string payDate)
        {
            int colspan = 3;

            PDFDoc = new Document(PageSize.A4);
            PDFWri = PdfWriter.GetInstance(PDFDoc, new FileStream(fileName, FileMode.Create));
            float[] widths = new float[] { 100f, 70f, 120f };
            //if (HeadFooter.is_head || HeadFooter.is_foot)
            PDFWri.PageEvent = HeadFooter;
            PDFDoc.Open();
            PdfContentByte canvas = PDFWri.DirectContent;

            PDFWri.CompressionLevel = 0;
            foreach (MainContract mc in msc)
            {
                PdfPTable tab = new PdfPTable(3);
                tab.TotalWidth = PDFDoc.PageSize.Width - 50;
                tab.SetWidths(widths);
                BaseFont bfont    = BaseFont.CreateFont(@"C:\Windows\Fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font     headFont = new Font(bfont, 16, Font.BOLD);
                foreach (PdfPCell p in GetContantHead(mc, Account_date, 3, headFont))
                {
                    tab.AddCell(p);
                }
                foreach (PdfPCell p in GetContantBill(mc, Tickets, 3, contrant_font))
                {
                    tab.AddCell(p);
                }
                foreach (PdfPCell c in GetContantTail(payDate, colspan))
                {
                    tab.AddCell(c);
                }
                tab.WriteSelectedRows(0, -1, 30, PDFDoc.Top - 20, canvas);

                PdfPTable tab1 = new PdfPTable(3); tab1.TotalWidth = PDFDoc.PageSize.Width - 50; tab1.SetWidths(widths);
                foreach (PdfPCell c in GetContantTail_buttom("", MadeBillDate, colspan))
                {
                    tab1.AddCell(c);
                }
                tab1.WriteSelectedRows(0, -1, 30, PDFDoc.Bottom + 50, canvas);

                PDFDoc.NewPage();
            }
            PDFDoc.Close();
        }