Ejemplo n.º 1
0
        public PlanOs2DetailsReport(PlanOs2View plan, Pedagog pedagog)
        {
            Document pdfDokument = new Document(
                PageSize.A4.Rotate(), 50, 50, 20, 50);

            MemoryStream memStream = new MemoryStream();

            PdfWriter.GetInstance(pdfDokument, memStream).
            CloseStream = false;
            pdfDokument.Open();
            BaseFont font = BaseFont.CreateFont(BaseFont.HELVETICA,
                                                BaseFont.CP1250, false);
            Font header   = new Font(font, 12, Font.NORMAL, BaseColor.DARK_GRAY);
            Font naslov   = new Font(font, 14, Font.BOLDITALIC, BaseColor.BLACK);
            Font tekst    = new Font(font, 10, Font.NORMAL, BaseColor.BLACK);
            Font bold     = new Font(font, 9, Font.BOLD, BaseColor.BLACK);
            Font blueBold = new Font(font, 9, Font.BOLD, BaseColor.BLUE);

            Paragraph p = new Paragraph(pedagog.Ime + " " + pedagog.Prezime + ", " + pedagog.Titula, header);

            pdfDokument.Add(p);
            p = new Paragraph("Naziv plana: " + plan.OsPlan2.Naziv, header);
            pdfDokument.Add(p);

            p               = new Paragraph("Godišnji plan i program rada stručnog suradnika pedagoga za osnovnu školu u šk.god. " + plan.OsPlan2.Ak_godina, naslov);
            p.Alignment     = Element.ALIGN_CENTER;
            p.SpacingBefore = 30;
            p.SpacingAfter  = 30;
            pdfDokument.Add(p);

            PdfPTable t = new PdfPTable(8);

            t.WidthPercentage = 100;
            t.SetWidths(new float[] { 1, 5, 3, 3, 3, 3, 2, 1 });

            t.AddCell(VratiCeliju2("R.br.", bold, true, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("POSLOVI I ZADACI", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("CILJEVI", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("ZADACI", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("SUBJEKTI", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("OBLICI I METODE RADA", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("VRIJEME REALIZACIJE", bold, false, BaseColor.CYAN));
            t.AddCell(VratiCeliju2("SATI", bold, false, BaseColor.CYAN));

            int a = 0;

            foreach (var podrucje in plan.OsPlan2Podrucja)
            {
                a++;
                List <OS_Plan_2_aktivnost> aktivnost = new List <OS_Plan_2_aktivnost>();
                aktivnost = plan.OsPlan2Aktivnosti.Where(w => w.Id_podrucje == podrucje.Id_plan).ToList();
                aktivnost = aktivnost.OrderBy(o => o.Red_br_aktivnost).ToList();

                t.AddCell(VratiCeliju(a.ToString(), blueBold, false, BaseColor.WHITE));
                t.AddCell(VratiCeliju(podrucje.Opis_podrucje, blueBold, false, BaseColor.WHITE));

                List <OS_Plan_2_akcija> listaAkcija = new List <OS_Plan_2_akcija>();

                foreach (var item in aktivnost)
                {
                    listaAkcija.AddRange(plan.OsPlan2Akcije.Where(w => w.Id_aktivnost == item.Id_plan));
                }
                int      spoji = aktivnost.Count + listaAkcija.Count + 1;
                PdfPCell cell  = new PdfPCell(new Phrase(plan.Ciljevi.Single(s => s.ID_cilj == podrucje.Cilj).Naziv, tekst));
                cell.BackgroundColor     = BaseColor.WHITE;
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.Padding             = 5;
                cell.NoWrap  = false;
                cell.Rowspan = spoji;
                t.AddCell(cell);

                cell = new PdfPCell(new Phrase(plan.Zadaci.Single(s => s.ID_zadatak == podrucje.Zadaci).Naziv, tekst));
                cell.BackgroundColor     = BaseColor.WHITE;
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.Padding             = 5;
                cell.NoWrap  = false;
                cell.Rowspan = spoji;
                t.AddCell(cell);

                cell = new PdfPCell(new Phrase(plan.Subjekti.Single(s => s.ID_subjekt == podrucje.Subjekti).Naziv, tekst));
                cell.BackgroundColor     = BaseColor.WHITE;
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.Padding             = 5;
                cell.NoWrap  = false;
                cell.Rowspan = spoji;
                t.AddCell(cell);

                cell = new PdfPCell(new Phrase(plan.Oblici.Single(s => s.Id_oblici == podrucje.Oblici).Naziv, tekst));
                cell.BackgroundColor     = BaseColor.WHITE;
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.Padding             = 5;
                cell.NoWrap  = false;
                cell.Rowspan = spoji;
                t.AddCell(cell);

                cell = new PdfPCell(new Phrase(podrucje.Vrijeme, tekst));
                cell.BackgroundColor     = BaseColor.WHITE;
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.Padding             = 5;
                cell.NoWrap  = false;
                cell.Rowspan = spoji;
                t.AddCell(cell);

                t.AddCell(VratiCeliju(podrucje.Sati.ToString(), blueBold, false, BaseColor.WHITE));

                int b = 0;
                foreach (var akt in aktivnost)
                {
                    b++;
                    t.AddCell(VratiCeliju(a + "." + b, bold, false, BaseColor.WHITE));
                    t.AddCell(VratiCeliju(akt.Opis_aktivnost, bold, false, BaseColor.WHITE));
                    t.AddCell(VratiCeliju(akt.Sati.ToString(), bold, false, BaseColor.WHITE));

                    List <OS_Plan_2_akcija> akcije = new List <OS_Plan_2_akcija>();
                    akcije = plan.OsPlan2Akcije.Where(w => w.Id_aktivnost == akt.Id_plan).ToList();
                    akcije = akcije.OrderBy(o => o.Red_br_akcija).ToList();

                    int c = 0;
                    foreach (var ac in akcije)
                    {
                        c++;
                        t.AddCell(VratiCeliju(a + "." + b + "." + c, tekst, false, BaseColor.WHITE));
                        t.AddCell(VratiCeliju(ac.Opis_akcija, tekst, false, BaseColor.WHITE));
                        t.AddCell(VratiCeliju(ac.Sati.ToString(), tekst, false, BaseColor.WHITE));
                    }
                }
            }

            pdfDokument.Add(t);

            pdfDokument.Close();
            Podaci = memStream.ToArray();
        }
Ejemplo n.º 2
0
        private static void SetReportTableHeader(PdfPTable table)
        {
            var cell = new PdfPCell()
            {
                BackgroundColor     = new BaseColor(23, 50, 80),
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            var cellColspan5 = new PdfPCell()
            {
                BackgroundColor     = new BaseColor(23, 50, 80),
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Colspan             = 5
            };

            var cellColspan2 = new PdfPCell()
            {
                BackgroundColor     = new BaseColor(23, 50, 80),
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Colspan             = 2
            };

            var cellRowspan2 = new PdfPCell()
            {
                BackgroundColor     = new BaseColor(23, 50, 80),
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Rowspan             = 2
            };

            cellRowspan2.Phrase = new Phrase("Tanggal", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("Kode Supplier", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("Supplier", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("Keterangan", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            //cellRowspan2.Phrase = new Phrase("No. PO", _smallerFont);
            //table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("No. Bon Penerimaan", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            //cellRowspan2.Phrase = new Phrase("No. Surat Jalan", _smallerFont);
            //table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("No. Inv.", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("No. Faktur Pajak", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("No. SPB/NI", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("Kategori", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellRowspan2.Phrase = new Phrase("Unit", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellColspan5.Phrase = new Phrase("Pembelian", _smallerBoldWhiteFont);
            table.AddCell(cellColspan5);

            cellRowspan2.Phrase = new Phrase("Total (IDR)", _smallerBoldWhiteFont);
            table.AddCell(cellRowspan2);

            cellColspan2.Phrase = new Phrase("DPP Valas", _smallerBoldWhiteFont);
            table.AddCell(cellColspan2);

            //cell.Phrase = new Phrase("Kurs BP", _smallerFont);
            //table.AddCell(cell);

            cell.Phrase = new Phrase("DPP (IDR)", _smallerBoldWhiteFont);
            table.AddCell(cell);

            cell.Phrase = new Phrase("PPN (IDR)", _smallerBoldWhiteFont);
            table.AddCell(cell);

            cell.Phrase = new Phrase("PPH (IDR)", _smallerBoldWhiteFont);
            table.AddCell(cell);
        }
Ejemplo n.º 3
0
        protected virtual async Task <PdfPTable> PreparePackagingSlipsAddress(Order order, Shipment shipment, Language language)
        {
            var font      = PdfExtensions.GetFont(_pdfSettings.FontFileName);
            var titleFont = PdfExtensions.PrepareTitleFont(_pdfSettings.FontFileName);

            var addressTable = new PdfPTable(1);

            if (language.Rtl)
            {
                addressTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            }
            addressTable.DefaultCell.Border = Rectangle.NO_BORDER;
            addressTable.WidthPercentage    = 100f;

            addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Shipment", language.Id), shipment.ShipmentNumber), titleFont));
            addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Order", language.Id), order.OrderNumber), titleFont));

            if (!order.PickUpInStore)
            {
                if (order.ShippingAddress == null)
                {
                    throw new GrandException(string.Format("Shipping is required, but address is not available. Order ID = {0}", order.Id));
                }

                if (_addressSettings.CompanyEnabled && !String.IsNullOrEmpty(order.ShippingAddress.Company))
                {
                    addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Company", language.Id),
                                                                     order.ShippingAddress.Company), font));
                }

                addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Name", language.Id),
                                                                 order.ShippingAddress.FirstName + " " + order.ShippingAddress.LastName), font));
                if (_addressSettings.PhoneEnabled)
                {
                    addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Phone", language.Id),
                                                                     order.ShippingAddress.PhoneNumber), font));
                }
                if (_addressSettings.StreetAddressEnabled)
                {
                    addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Address", language.Id),
                                                                     order.ShippingAddress.Address1), font));
                }

                if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.ShippingAddress.Address2))
                {
                    addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.Address2", language.Id),
                                                                     order.ShippingAddress.Address2), font));
                }

                if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled)
                {
                    addressTable.AddCell(new Paragraph(String.Format("{0}, {1} {2}", order.ShippingAddress.City, !String.IsNullOrEmpty(order.ShippingAddress.StateProvinceId)
                                    ? (await _serviceProvider.GetRequiredService <IStateProvinceService>().GetStateProvinceById(order.ShippingAddress.StateProvinceId)).GetLocalized(x => x.Name, language.Id)
                                    : "", order.ShippingAddress.ZipPostalCode), font));
                }

                if (_addressSettings.CountryEnabled && !String.IsNullOrEmpty(order.ShippingAddress.CountryId))
                {
                    addressTable.AddCell(new Paragraph(String.Format("{0}", !String.IsNullOrEmpty(order.ShippingAddress.CountryId)
                                    ? (await _serviceProvider.GetRequiredService <ICountryService>().GetCountryById(order.ShippingAddress.CountryId)).GetLocalized(x => x.Name, language.Id)
                                    : ""), font));
                }

                //custom attributes
                var customShippingAddressAttributes = await _addressAttributeFormatter.FormatAttributes(order.ShippingAddress.CustomAttributes);

                if (!String.IsNullOrEmpty(customShippingAddressAttributes))
                {
                    addressTable.AddCell(new Paragraph(HtmlHelper.ConvertHtmlToPlainText(customShippingAddressAttributes, true, true), font));
                }
            }
            else
            if (order.PickupPoint != null)
            {
                if (order.PickupPoint.Address != null)
                {
                    addressTable.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.Pickup", language.Id), titleFont));
                    if (!string.IsNullOrEmpty(order.PickupPoint.Address.Address1))
                    {
                        addressTable.AddCell(new Paragraph(string.Format("   {0}", string.Format(_localizationService.GetResource("PDFInvoice.Address", language.Id), order.PickupPoint.Address.Address1)), font));
                    }
                    if (!string.IsNullOrEmpty(order.PickupPoint.Address.City))
                    {
                        addressTable.AddCell(new Paragraph(string.Format("   {0}", order.PickupPoint.Address.City), font));
                    }
                    if (!string.IsNullOrEmpty(order.PickupPoint.Address.CountryId))
                    {
                        var country = await _serviceProvider.GetRequiredService <ICountryService>().GetCountryById(order.PickupPoint.Address.CountryId);

                        if (country != null)
                        {
                            addressTable.AddCell(new Paragraph(string.Format("   {0}", country.Name), font));
                        }
                    }
                    if (!string.IsNullOrEmpty(order.PickupPoint.Address.ZipPostalCode))
                    {
                        addressTable.AddCell(new Paragraph(string.Format("   {0}", order.PickupPoint.Address.ZipPostalCode), font));
                    }
                    addressTable.AddCell(new Paragraph(" "));
                }
            }

            addressTable.AddCell(new Paragraph(" "));

            addressTable.AddCell(new Paragraph(String.Format(_localizationService.GetResource("PDFPackagingSlip.ShippingMethod", language.Id), order.ShippingMethod), font));
            addressTable.AddCell(new Paragraph(" "));

            return(addressTable);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Exporttopdf
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool ExportToPdf(DataSet ds, string fileName, ExperimentsInfo expInfo)
        {
            ///设置导出字体
            string FontPath = "C://WINDOWS//Fonts//simsun.ttc,1";
            int    FontSize = 8;

            Boolean result = true;
            //竖排模式,大小为A4,四周边距均为25
            Document document = new Document(PageSize.A4, 10, 10, 10, 10);

            //调用PDF的写入方法流
            //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

            //创建PDF文档中的字体
            BaseFont baseFont = BaseFont.CreateFont(
                FontPath,
                BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);

            //根据字体路径和字体大小属性创建字体
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);

            iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(baseFont, 9);

            iTextSharp.text.Font fontWanTag = new iTextSharp.text.Font(baseFont, 14);
            fontWanTag.IsBold();

            DateTime dTime = DateTime.Now;

            HeaderFooter footer = new HeaderFooter(new Phrase(dTime.ToString("yyyy/MM/dd HH:mm:ss") + "    Page: "), true);

            footer.Border    = Rectangle.NO_BORDER;
            footer.Alignment = Element.ALIGN_RIGHT;
            document.Footer  = footer;

            //HeaderFooter Header = new HeaderFooter(new Phrase("WanTag 实验报告"),false);
            //Header.Border = Rectangle.NO_BORDER;
            //Header.Alignment = Element.ALIGN_CENTER;
            //document.Header = Header;

            //打开目标文档对象
            document.Open();

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

            Paragraph p_WanTag = new Paragraph("WanTag 实验报告", fontWanTag);

            p_WanTag.Alignment = 1;
            document.Add(p_WanTag);

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

            Paragraph p_expName = new Paragraph("            实验名称:" + expInfo.ExperimentName, fontTitle);

            //p_expName.Alignment = 1;
            document.Add(p_expName);

            Paragraph p_expLoginName = new Paragraph("            操 作 员:" + expInfo.LoginName, fontTitle);

            //p_expName.Alignment = 1;
            document.Add(p_expLoginName);

            Paragraph p_expStartDate = new Paragraph("            开始时间:" + expInfo.StartTime.ToString("yyyy/MM/dd HH:mm:ss"), fontTitle);

            //p_expName.Alignment = 1;
            document.Add(p_expStartDate);

            Paragraph p_expEndDate = new Paragraph("            结束时间:" + Convert.ToDateTime(expInfo.EndTime).ToString("yyyy/MM/dd HH:mm:ss"), fontTitle);

            //p_expName.Alignment = 1;
            document.Add(p_expEndDate);
            document.Add(new Paragraph("\n"));

            for (int k = 0; k < ds.Tables.Count; k++)
            {
                if (k > 0)
                {
                    document.NewPage();
                }

                string tableName = ds.Tables[k].TableName;

                if (ds.Tables[k].Rows[0]["检测结果"].ToString() == "重新测定" || ds.Tables[k].Rows[1]["检测结果"].ToString() == "重新测定")
                {
                    tableName += "  质控品结果不符合标准,实验结果无效";
                }

                Paragraph p_Name = new Paragraph(tableName, fontTitle);
                document.Add(p_Name);
                document.Add(new Paragraph("\n"));

                //根据数据表内容创建一个PDF格式的表
                PdfPTable table = new PdfPTable(ds.Tables[k].Columns.Count - 1);
                table.SetTotalWidth(new float[] { 5, 10, 12, 10, 8, 6, 12, 6, 13, 20 });
                // 添加表头,每一页都有表头
                for (int j = 0; j < ds.Tables[k].Columns.Count - 1; j++)
                {
                    string cellName = ds.Tables[k].Columns[j].ColumnName;
                    cellName = cellName.Replace("BarCode", "条码").Replace("Position", "孔位");
                    PdfPCell cell = new PdfPCell(new Phrase(cellName, font));
                    cell.UseAscender         = true;
                    cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.BackgroundColor     = new Color(220, 220, 220);
                    table.AddCell(cell);
                }

                // 告诉程序这行是表头,这样页数大于1时程序会自动为你加上表头。
                table.HeaderRows = 1;

                //遍历原datatable的数据行
                for (int i = 0; i < ds.Tables[k].Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Tables[k].Columns.Count - 1; j++)
                    {
                        try
                        {
                            PdfPCell             cell  = new PdfPCell(new Phrase(ds.Tables[k].Rows[i][j].ToString(), font));
                            System.Drawing.Color Color = System.Drawing.ColorTranslator.FromHtml(ds.Tables[k].Rows[i]["Color"].ToString());
                            cell.BackgroundColor = new iTextSharp.text.Color(Color);
                            table.AddCell(cell);

                            // table.AddCell(new Phrase(ds.Tables[k].Rows[i][j].ToString(), font));
                        }
                        catch (Exception e)
                        {
                            result = false;
                        }
                    }
                }

                //在目标文档中添加转化后的表数据
                document.Add(table);
            }


            //关闭目标文件
            document.Close();

            //关闭写入流
            writer.Close();
            return(result);
        }
Ejemplo n.º 5
0
        private PdfPTable GetSignatureSection(NewShipmentDocumentModel model, int timeoffset)
        {
            PdfPTable table = new PdfPTable(4)
            {
                WidthPercentage = 100
            };

            float[] widths = new float[] { 1f, 1f, 1f, 1f };
            table.SetWidths(widths);
            PdfPCell cell = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
            };

            cell.Phrase = new Phrase("Mengetahui", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase("", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase("", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase($"Sukoharjo, {model.CreatedUtc.AddHours(timeoffset).ToString("dd MMMM yyyy")}", TEXT_FONT);
            table.AddCell(cell);

            cell.Phrase = new Phrase("Kasubsie Gudang Jadi", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase("", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase("", TEXT_FONT);
            table.AddCell(cell);
            cell.Phrase = new Phrase("Petugas Gudang", TEXT_FONT);
            table.AddCell(cell);

            for (var i = 0; i < 11; i++)
            {
                cell.Phrase = new Phrase("", TEXT_FONT);
                table.AddCell(cell);
                cell.Phrase = new Phrase("", TEXT_FONT);
                table.AddCell(cell);
                cell.Phrase = new Phrase("", TEXT_FONT);
                table.AddCell(cell);
                cell.Phrase = new Phrase("", TEXT_FONT);
                table.AddCell(cell);
            }

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



            return(table);
        }
        private void ImprimeRodape(PdfWriter writer, Document doc)
        {
            #region Dados do Rodapé
            if (ImprimirRodapePadrao)
            {
                BaseColor preto   = new BaseColor(0, 0, 0);
                Font      font    = FontFactory.GetFont("Verdana", 8, Font.NORMAL, preto);
                Font      negrito = FontFactory.GetFont("Verdana", 8, Font.BOLD, preto);
                float[]   sizes   = new float[] { 1.0f, 3.5f, 1f };

                PdfPTable table = new PdfPTable(3);
                table.TotalWidth = doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin);
                table.SetWidths(sizes);

                #region Coluna TNE
                Image foot = Image.GetInstance(BasePath + @"\Content\tne_mascote.png");
                foot.ScalePercent(60);

                PdfPCell cell = new PdfPCell(foot);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingLeft    = 10f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);

                PdfPTable micros = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase("TNE", negrito));
                cell.Border = 0;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Treta never ends", font));
                cell.Border = 0;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase("www.montadorappmvc.com.br", font));
                cell.Border = 0;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);
                #endregion

                #region Página
                micros      = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase(DateTime.Today.ToString("dd/MM/yyyy"), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase(DateTime.Now.ToString("HH:mm:ss"), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border         = 0;
                cell.BorderWidthTop = 1.5f;
                cell.PaddingTop     = 10f;
                table.AddCell(cell);
                #endregion

                table.WriteSelectedRows(0, -1, doc.LeftMargin, 70, writer.DirectContent);
            }
            #endregion
        }
Ejemplo n.º 7
0
        void pdf()
        {
            try
            {
                SaveFileDialog fichero = new SaveFileDialog();
                fichero.FileName = "Grafico de votantes";
                fichero.Filter   = "Pdf(*.pdf)|*.pdf";
                if (fichero.ShowDialog() == DialogResult.OK)
                {
                    Document  doc = new Document(PageSize.LETTER, 20, 20, 20, 20);
                    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(fichero.FileName, FileMode.Create));
                    doc.Open();
                    PdfPTable encabezado = new PdfPTable(3);
                    var       chartimage = new MemoryStream();
                    encabezado.SetWidthPercentage(new float[] { 170, 170, 170 }, PageSize.LETTER);
                    encabezado.AddCell(iTextSharp.text.Image.GetInstance("imagenes/Logo.png"));
                    encabezado.AddCell(new Paragraph("E-Lectonic Inc. \n \nPartidos", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL)));
                    encabezado.AddCell(new Paragraph("Partidos\n Voto Electronico\n", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL)));
                    foreach (PdfPCell celda in encabezado.Rows[0].GetCells())
                    {
                        celda.BackgroundColor     = BaseColor.WHITE;
                        celda.HorizontalAlignment = 5;
                        celda.VerticalAlignment   = 5;
                        celda.Border            = 0;
                        celda.BorderWidthBottom = 4f;
                        celda.BorderWidthTop    = 4f;
                        celda.BorderColorBottom = new BaseColor(80, 80, 80);
                        celda.BorderColorTop    = new BaseColor(80, 80, 80);
                    }
                    doc.Add(encabezado);
                    doc.Add(new Paragraph(" "));
                    iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                    PdfPTable            table     = new PdfPTable(dataGridView1.Columns.Count);
                    table.DefaultCell.Phrase = new Phrase()
                    {
                        Font = fontTable
                    };
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, fontTable));
                        table.SetWidthPercentage(new float[] { 100, 100, 100 }, PageSize.LETTER);
                    }
                    table.HeaderRows = 1;

                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        foreach (PdfPCell celdas in table.Rows[i].GetCells())
                        {
                            celdas.BorderWidth = 1f;
                            celdas.BorderColor = new BaseColor(80, 80, 80);
                        }
                        foreach (PdfPCell celdas in table.Rows[0].GetCells())
                        {
                            celdas.BorderWidth     = 1f;
                            celdas.BackgroundColor = new BaseColor(129, 211, 255);
                        }
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (dataGridView1[k, i].Value != null)
                            {
                                table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), fontTable));
                            }
                        }
                    }
                    doc.Add(table);
                    doc.Add(new Paragraph(" "));
                    chart1.SaveImage(chartimage, ChartImageFormat.Png);
                    iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(chartimage.GetBuffer());
                    image1.Alignment = Element.ALIGN_CENTER;
                    doc.Add(image1);
                    Paragraph pie = new Paragraph("¡Gracias por utilizar nuestro sistema!", FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.BOLDITALIC));
                    pie.Alignment = Element.ALIGN_CENTER;
                    doc.Add(pie);
                    doc.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error al exportar la informacion debido a: " + e.ToString());
            }
        }
Ejemplo n.º 8
0
        public byte[] Generate()
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                Document  document = new Document(PageSize.A4, 25, 25, 30, 30);
                PdfWriter writer   = PdfWriter.GetInstance(document, memStream);
                document.Open();

                PdfPTable topSection = new PdfPTable(2);
                topSection.DefaultCell.Border = Rectangle.NO_BORDER;

                // Full Name
                var fullNamePhrase = new Phrase();
                topSection.DefaultCell.Border = Rectangle.NO_BORDER;
                fullNamePhrase.Add(new Chunk("Name: ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16)));
                fullNamePhrase.Add(new Chunk(FullName, FontFactory.GetFont(FontFactory.HELVETICA, 16)));
                PdfPCell fullNameCell = new PdfPCell(fullNamePhrase);
                fullNameCell.Border = Rectangle.NO_BORDER;
                topSection.AddCell(fullNameCell);

                // Base Salary
                var annualSalaryPhrase = new Phrase();
                annualSalaryPhrase.Add(new Chunk("Base Salary: ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16)));
                annualSalaryPhrase.Add(new Chunk("$" + AnnualSalary.ToString("f2"), FontFactory.GetFont(FontFactory.HELVETICA, 16)));
                PdfPCell baseSalaryCell = new PdfPCell(annualSalaryPhrase);
                baseSalaryCell.Border = Rectangle.NO_BORDER;
                topSection.AddCell(baseSalaryCell);

                document.Add(topSection);

                PdfPTable dependentSection = new PdfPTable(1);
                dependentSection.SpacingBefore      = 20f;
                dependentSection.DefaultCell.Border = Rectangle.NO_BORDER;
                PdfPCell headerLabel = new PdfPCell(new Phrase(new Chunk("Dependents", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16))));
                headerLabel.Border = Rectangle.NO_BORDER;
                dependentSection.AddCell(headerLabel);

                foreach (var dependent in Dependents.Where(x => !string.IsNullOrEmpty(x)))
                {
                    PdfPCell dependentCell = new PdfPCell(new Phrase(new Chunk("-" + dependent, FontFactory.GetFont(FontFactory.HELVETICA, 14))));
                    dependentCell.Border = Rectangle.NO_BORDER;
                    dependentSection.AddCell(dependentCell);
                }

                document.Add(dependentSection);

                PdfPTable bottomSection = new PdfPTable(1);
                bottomSection.SpacingBefore      = 40f;
                bottomSection.DefaultCell.Border = Rectangle.NO_BORDER;

                PdfPTable detailsTable = new PdfPTable(2);
                detailsTable.DefaultCell.Border = Rectangle.NO_BORDER;
                PdfPCell discountHeaderCell = new PdfPCell(new Phrase(new Chunk("Dependents", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14))));
                discountHeaderCell.Colspan = 2;
                detailsTable.AddCell(discountHeaderCell);

                foreach (var discount in Discounts)
                {
                    PdfPCell discountItemCell = new PdfPCell(new Phrase(new Chunk(discount, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12))));
                    discountItemCell.Colspan = 2;
                    detailsTable.AddCell(discountItemCell);
                }

                detailsTable.AddCell(new PdfPCell(new Phrase(new Chunk("Total: ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)))));
                detailsTable.AddCell(new PdfPCell(new Phrase(new Chunk(Total.ToString("f2"), FontFactory.GetFont(FontFactory.HELVETICA, 14)))));
                detailsTable.AddCell(new PdfPCell(new Phrase(new Chunk("Total Per Check: ", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)))));
                detailsTable.AddCell(new PdfPCell(new Phrase(new Chunk(TotalPerCheck.ToString("f2"), FontFactory.GetFont(FontFactory.HELVETICA, 14)))));
                bottomSection.AddCell(new PdfPCell(detailsTable));
                document.Add(bottomSection);

                PdfContentByte canvas   = writer.DirectContent;
                PieChart       pieChart = new PieChart(new double[] { Total, TotalEmployeeBenefitCost, TotalDependentsBenefitCost },
                                                       new[] { "Total After Benefits", "Employee Benefits", "Employee Dependent Benefits" });

                canvas.DrawPieChart(pieChart, 300, 300, 100);

                document.Close();
                return(memStream.ToArray());
            }
        }
Ejemplo n.º 9
0
        private void Bind1()
        {
            #region
            main1.Columns.Add("Client Name", typeof(string));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                main1.Columns.Add(dt.Rows[i]["productname"].ToString());
            }
            main1.Columns.Add("Total", typeof(string));
            Double[] endtotal = new Double[main1.Columns.Count];

            DataTable dtdept = new DataTable();
            dtdept = cl.getdataset("select * from DepartmentMaster");

            label3.Text = "Department:" + dtdept.Rows[0][1].ToString();
            //  main1.Rows.Add();
            main1.Rows.Add(label3.Text);

            for (int j = 0; j < dt1.Rows.Count; j++)
            {
                Double  sum = 0;
                DataRow dr  = main1.NewRow();
                dr["Client Name"] = dt1.Rows[j]["AccountName"].ToString();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string qty = cl.ExecuteScalar("select po.qty from purchaseorderproductmaster po inner join productmaster p on p.Product_Name = po.ProductName where po.isactive=1 and p.DepartmentId='" + dtdept.Rows[0][0].ToString() + "' and po.productname='" + dt.Rows[i]["productname"].ToString() + "'");
                    // string qty = conn.ExecuteScalar("select qty from purchaseorderproductmaster where isactive=1 and  productname='" + dt.Rows[i]["productname"].ToString() + "' and Vchno='" + dt1.Rows[j]["Vchno"].ToString() + "'");
                    if (qty == "")
                    {
                        qty = "0";
                    }
                    dr[dt.Rows[i]["ProductName"].ToString()] = qty;
                    sum             += Convert.ToDouble(qty);
                    endtotal[i + 1] += Convert.ToDouble(qty);
                }
                dr["Total"] = sum;
                if (sum > 0)
                {
                    main1.Rows.Add(dr.ItemArray);
                }
            }


            double  total  = 0;
            DataRow lastdr = main1.NewRow();
            for (int i = 0; i < endtotal.Length; i++)
            {
                if (i == 0)
                {
                    lastdr[i] = "Total";
                }
                else
                {
                    lastdr[i] = endtotal[i];
                    total    += Convert.ToDouble(endtotal[i]);
                }
            }
            lastdr["Total"] = Math.Round(total, 2).ToString();
            main1.Rows.Add(lastdr.ItemArray);
            main1.Rows.Add();
            #endregion
            PdfPTable bltable  = new PdfPTable(main1.Columns.Count);
            float[]   blwidths = new float[] { 4f, 4f, 4f, 4f };
            bltable.WidthPercentage = 100;

            PdfPCell blpcell = new PdfPCell(new Phrase(""));
            blpcell.BorderColor = iTextSharp.text.Color.WHITE;
            blpcell.FixedHeight = 10f;

            for (int i = 0; i < main1.Columns.Count; i++)
            {
                bltable.AddCell(blpcell);
            }
            #region
            main4.Columns.Add("Client Name", typeof(string));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                main4.Columns.Add(dt.Rows[i]["productname"].ToString());
            }
            main4.Columns.Add("Total", typeof(string));
            Double[] endtotal4 = new Double[main4.Columns.Count];

            label3.Text = "Department:" + dtdept.Rows[1][1].ToString();
            //main4.Rows.Add();
            main4.Rows.Add(label3.Text);

            for (int j = 0; j < dt1.Rows.Count; j++)
            {
                Double  sum = 0;
                DataRow dr  = main4.NewRow();
                dr["Client Name"] = dt1.Rows[j]["AccountName"].ToString();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string qty = cl.ExecuteScalar("select po.qty from purchaseorderproductmaster po inner join productmaster p on p.Product_Name = po.ProductName where po.isactive=1 and p.DepartmentId='" + dtdept.Rows[1][0].ToString() + "' and po.productname='" + dt.Rows[i]["productname"].ToString() + "'");

                    if (qty == "")
                    {
                        qty = "0";
                    }
                    dr[dt.Rows[i]["ProductName"].ToString()] = qty;
                    sum += Convert.ToDouble(qty);
                    endtotal4[i + 1] += Convert.ToDouble(qty);
                }
                dr["Total"] = sum;
                if (sum > 0)
                {
                    main4.Rows.Add(dr.ItemArray);
                }
            }

            double  total4  = 0;
            DataRow lastdr4 = main4.NewRow();
            for (int i = 0; i < endtotal4.Length; i++)
            {
                if (i == 0)
                {
                    lastdr4[i] = "Total";
                }
                else
                {
                    lastdr4[i] = endtotal4[i];
                    total4    += Convert.ToDouble(endtotal4[i]);
                }
            }
            lastdr4["Total"] = Math.Round(total4, 2).ToString();
            main4.Rows.Add(lastdr4.ItemArray);
            main4.Rows.Add();
            #endregion
            PdfPTable bltable1  = new PdfPTable(main4.Columns.Count);
            float[]   blwidths1 = new float[] { 4f, 4f, 4f, 4f };
            bltable1.WidthPercentage = 100;

            PdfPCell blpcell1 = new PdfPCell(new Phrase(""));
            blpcell1.BorderColor = iTextSharp.text.Color.WHITE;
            blpcell1.FixedHeight = 10f;

            for (int i = 0; i < main4.Columns.Count; i++)
            {
                bltable1.AddCell(blpcell1);
            }
            #region
            main5.Columns.Add("Client Name", typeof(string));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                main5.Columns.Add(dt.Rows[i]["productname"].ToString());
            }
            main5.Columns.Add("Total", typeof(string));
            Double[] endtotal5 = new Double[main5.Columns.Count];

            label3.Text = "Department:" + dtdept.Rows[2][1].ToString();
            //  main5.Rows.Add();
            main5.Rows.Add(label3.Text);

            for (int j = 0; j < dt1.Rows.Count; j++)
            {
                Double  sum = 0;
                DataRow dr  = main5.NewRow();
                dr["Client Name"] = dt1.Rows[j]["AccountName"].ToString();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string qty = cl.ExecuteScalar("select po.qty from purchaseorderproductmaster po inner join productmaster p on p.Product_Name = po.ProductName where po.isactive=1 and p.DepartmentId='" + dtdept.Rows[2][0].ToString() + "' and po.productname='" + dt.Rows[i]["productname"].ToString() + "'");

                    if (qty == "")
                    {
                        qty = "0";
                    }
                    dr[dt.Rows[i]["ProductName"].ToString()] = qty;
                    sum += Convert.ToDouble(qty);
                    endtotal5[i + 1] += Convert.ToDouble(qty);
                }
                dr["Total"] = sum;
                if (sum > 0)
                {
                    main5.Rows.Add(dr.ItemArray);
                }
            }

            double  total5  = 0;
            DataRow lastdr5 = main5.NewRow();
            for (int i = 0; i < endtotal5.Length; i++)
            {
                if (i == 0)
                {
                    lastdr5[i] = "Total";
                }
                else
                {
                    lastdr5[i] = endtotal5[i];
                    total5    += Convert.ToDouble(endtotal5[i]);
                }
            }
            lastdr5["Total"] = Math.Round(total5, 2).ToString();
            main5.Rows.Add(lastdr5.ItemArray);
            main5.Rows.Add();
            #endregion
            PdfPTable bltable2  = new PdfPTable(main5.Columns.Count);
            float[]   blwidths2 = new float[] { 4f, 4f, 4f, 4f };
            bltable2.WidthPercentage = 100;

            PdfPCell blpcell2 = new PdfPCell(new Phrase(""));
            blpcell2.BorderColor = iTextSharp.text.Color.WHITE;
            blpcell2.FixedHeight = 10f;

            for (int i = 0; i < main5.Columns.Count; i++)
            {
                bltable2.AddCell(blpcell2);
            }
            #region
            String path = Application.StartupPath;
            System.IO.Directory.CreateDirectory(path + @"\report");
            Document document = new Document();

            PdfWriter            writer = PdfWriter.GetInstance(document, new FileStream(path + "\\report\\PurchaseOrderReportItem-" + DateTime.Now.ToString("dd_MMM_yyyy hh_mm_ss") + ".pdf", FileMode.Create));
            iTextSharp.text.Font font5  = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 8);
            document.Open();

            PdfPTable table = new PdfPTable(main1.Columns.Count);

            float[] widths = new float[] { 4f, 4f, 4f, 4f };

            table.WidthPercentage = 100;

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

            cell.Colspan = main1.Columns.Count;

            foreach (DataColumn c in main1.Columns)
            {
                table.AddCell(new Phrase(c.ColumnName, font5));
            }

            for (int i = 0; i < main1.Rows.Count; i++)
            {
                for (int j = 0; j < main1.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(main1.Rows[i][j].ToString(), font5));
                }
            }

            PdfPTable table4 = new PdfPTable(main4.Columns.Count);

            float[] widths4 = new float[] { 4f, 4f, 4f, 4f };

            table4.WidthPercentage = 100;

            PdfPCell cell4 = new PdfPCell(new Phrase("Products"));

            cell4.Colspan = main4.Columns.Count;

            foreach (DataColumn c in main4.Columns)
            {
                table4.AddCell(new Phrase(c.ColumnName, font5));
            }

            for (int i = 0; i < main4.Rows.Count; i++)
            {
                for (int j = 0; j < main4.Columns.Count; j++)
                {
                    table4.AddCell(new Phrase(main4.Rows[i][j].ToString(), font5));
                }
            }


            PdfPTable table5 = new PdfPTable(main5.Columns.Count);

            float[] widths5 = new float[] { 4f, 4f, 4f, 4f };

            table5.WidthPercentage = 100;

            PdfPCell cell5 = new PdfPCell(new Phrase("Products"));

            cell5.Colspan = main5.Columns.Count;

            foreach (DataColumn c in main5.Columns)
            {
                table5.AddCell(new Phrase(c.ColumnName, font5));
            }

            for (int i = 0; i < main5.Rows.Count; i++)
            {
                for (int j = 0; j < main5.Columns.Count; j++)
                {
                    table5.AddCell(new Phrase(main5.Rows[i][j].ToString(), font5));
                }
            }

            document.Add(table);
            document.Add(bltable);
            document.Add(table4);
            document.Add(bltable1);
            document.Add(table5);
            document.Add(bltable2);
            document.Close();
            #endregion
        }
        public ActionResult BalanceSheet(String DateAsOf, Int32 CompanyId)
        {
            // ============
            // PDF settings
            // ============
            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 Customization
            // ===================
            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);

            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 == CompanyId select d.Company).SingleOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == CompanyId select d.Address).SingleOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == CompanyId select d.ContactNumber).SingleOrDefault();

            // ======
            // Header
            // ======
            PdfPTable header = new PdfPTable(2);

            float[] widthsCellsHeader = new float[] { 100f, 75f };
            header.SetWidths(widthsCellsHeader);
            header.WidthPercentage = 100;
            header.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            header.AddCell(new PdfPCell(new Phrase("Balance Sheet", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date as of " + Convert.ToDateTime(DateAsOf).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2,
            });
            header.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.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(header);
            document.Add(line);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });
            document.Add(spaceTable);

            Decimal totalOverallAssets      = 0;
            Decimal totalOverallLiabilities = 0;
            Decimal totalOverallEquities    = 0;

            // ==========
            // Get Assets
            // ==========
            var assets = from d in db.TrnJournals
                         where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                         d.MstAccount.MstAccountType.MstAccountCategory.Id == 1 &&
                         d.MstBranch.CompanyId == CompanyId
                         group d by d.MstAccount into g
                         select new
            {
                DocumentReference      = "1 - Asset",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.DebitAmount - d.CreditAmount)
            };

            if (assets.Any())
            {
                // ==============================
                // Asset Sub Category Description
                // ==============================
                var assetSubCategoryDescriptions = from d in assets
                                                   group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.DebitAmount - d.CreditAmount)
                };

                if (assetSubCategoryDescriptions.Any())
                {
                    Decimal totalAllAssets = 0;
                    foreach (var assetSubCategoryDescription in assetSubCategoryDescriptions)
                    {
                        PdfPTable assetSubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsAssetSubCategoryDescriptionTable = new float[] { 100f };
                        assetSubCategoryDescriptionTable.SetWidths(widthCellsAssetSubCategoryDescriptionTable);
                        assetSubCategoryDescriptionTable.WidthPercentage = 100;
                        assetSubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(assetSubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(assetSubCategoryDescriptionTable);

                        // ===================
                        // Asset Account Types
                        // ===================
                        var assetAccountTypes = from d in assets
                                                where d.SubCategoryDescription.Equals(assetSubCategoryDescription.SubCategoryDescription)
                                                group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.DebitAmount - d.CreditAmount)
                        };

                        if (assetAccountTypes.Any())
                        {
                            Decimal totalCurrentAssets = 0;
                            foreach (var assetAccountType in assetAccountTypes)
                            {
                                totalCurrentAssets += assetAccountType.Balance;

                                PdfPTable assetAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsAssetAccountTypeTable = new float[] { 50f, 100f, 50f };
                                assetAccountTypeTable.SetWidths(widthCellsAssetAccountTypeTable);
                                assetAccountTypeTable.WidthPercentage = 100;
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase(assetAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase(assetAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(assetAccountTypeTable);

                                // ==============
                                // Asset Accounts
                                // ==============
                                var assetAccounts = from d in assets
                                                    where d.AccountType.Equals(assetAccountType.AccountType)
                                                    group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.DebitAmount - d.CreditAmount)
                                };

                                if (assetAccounts.Any())
                                {
                                    foreach (var assetAccount in assetAccounts)
                                    {
                                        totalAllAssets += assetAccount.Balance;

                                        PdfPTable assetAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsAssetAccountTable = new float[] { 50f, 100f, 50f };
                                        assetAccountTable.SetWidths(widthCellsAssetAccountTable);
                                        assetAccountTable.WidthPercentage = 100;
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(assetAccountTable);
                                    }
                                }
                            }

                            // ====================
                            // Total Current Assets
                            // ====================
                            document.Add(line);
                            PdfPTable totalCurrentAssetsTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentAssetsTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentAssetsTable.SetWidths(widthCellsTotalCurrentAssetsTable);
                            totalCurrentAssetsTable.WidthPercentage = 100;
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("Total " + assetSubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase(totalCurrentAssets.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentAssetsTable);
                        }
                    }

                    // ================
                    // Total All Assets
                    // ================
                    document.Add(line);
                    PdfPTable totalAllAssetsTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllAssetsTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllAssetsTable.SetWidths(widthCellsTotalAllAssetsTable);
                    totalAllAssetsTable.WidthPercentage = 100;
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("Total Asset", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase(totalAllAssets.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllAssetsTable);

                    totalOverallAssets += totalAllAssets;
                    document.Add(Chunk.NEWLINE);
                }
            }

            // ===============
            // Get Liabilities
            // ===============
            var liabilities = from d in db.TrnJournals
                              where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                              d.MstAccount.MstAccountType.MstAccountCategory.Id == 2 &&
                              d.MstBranch.CompanyId == CompanyId
                              group d by d.MstAccount into g
                              select new Models.TrnJournal
            {
                DocumentReference      = "2 - Liability",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            if (liabilities.Any())
            {
                // ==================================
                // Liability Sub Category Description
                // ==================================
                var liabilitySubCategoryDescriptions = from d in liabilities
                                                       group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.CreditAmount - d.DebitAmount)
                };

                if (liabilitySubCategoryDescriptions.Any())
                {
                    Decimal totalAllLiabilities = 0;
                    foreach (var liabilitySubCategoryDescription in liabilitySubCategoryDescriptions)
                    {
                        PdfPTable liabilitySubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsLiabilitySubCategoryDescriptionTable = new float[] { 100f };
                        liabilitySubCategoryDescriptionTable.SetWidths(widthCellsLiabilitySubCategoryDescriptionTable);
                        liabilitySubCategoryDescriptionTable.WidthPercentage = 100;
                        liabilitySubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(liabilitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(liabilitySubCategoryDescriptionTable);

                        // =======================
                        // Liability Account Types
                        // =======================
                        var liabilityAccountTypes = from d in liabilities
                                                    where d.SubCategoryDescription.Equals(liabilitySubCategoryDescription.SubCategoryDescription)
                                                    group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.CreditAmount - d.DebitAmount)
                        };

                        if (liabilityAccountTypes.Any())
                        {
                            Decimal totalCurrentLiabilities = 0;
                            foreach (var liabilityAccountType in liabilityAccountTypes)
                            {
                                totalCurrentLiabilities += liabilityAccountType.Balance;

                                PdfPTable liabilityAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsLiabilityAccountTypeTable = new float[] { 50f, 100f, 50f };
                                liabilityAccountTypeTable.SetWidths(widthCellsLiabilityAccountTypeTable);
                                liabilityAccountTypeTable.WidthPercentage = 100;
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase(liabilityAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase(liabilityAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(liabilityAccountTypeTable);

                                // ==================
                                // Liability Accounts
                                // ==================
                                var liabilityAccounts = from d in liabilities
                                                        where d.AccountType.Equals(liabilityAccountType.AccountType)
                                                        group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
                                };

                                if (liabilityAccounts.Any())
                                {
                                    foreach (var liabilityAccount in liabilityAccounts)
                                    {
                                        totalAllLiabilities += liabilityAccount.Balance;

                                        PdfPTable liabilityAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsLiabilityAccountTable = new float[] { 50f, 100f, 50f };
                                        liabilityAccountTable.SetWidths(widthCellsLiabilityAccountTable);
                                        liabilityAccountTable.WidthPercentage = 100;
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(liabilityAccountTable);
                                    }
                                }
                            }

                            // =========================
                            // Total Current Liabilities
                            // =========================
                            document.Add(line);
                            PdfPTable totalCurrentLiabilitiesTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentLiabilitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentLiabilitiesTable.SetWidths(widthCellsTotalCurrentLiabilitiesTable);
                            totalCurrentLiabilitiesTable.WidthPercentage = 100;
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("Total " + liabilitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase(totalCurrentLiabilities.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentLiabilitiesTable);
                        }
                    }

                    // =====================
                    // Total All Liabilities
                    // =====================
                    document.Add(line);
                    PdfPTable totalAllLiabilitiesTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllLiabilitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllLiabilitiesTable.SetWidths(widthCellsTotalAllLiabilitiesTable);
                    totalAllLiabilitiesTable.WidthPercentage = 100;
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("Total Liability", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase(totalAllLiabilities.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllLiabilitiesTable);

                    totalOverallLiabilities += totalAllLiabilities;
                    document.Add(Chunk.NEWLINE);
                }
            }

            // ===================
            // Get Profit and Loss
            // ===================
            var profitAndLoss = from d in db.TrnJournals
                                where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                                (d.MstAccount.MstAccountType.MstAccountCategory.Id == 5 || d.MstAccount.MstAccountType.MstAccountCategory.Id == 6) &&
                                d.MstBranch.CompanyId == CompanyId
                                group d by d.MstAccount into g
                                select new Models.TrnJournal
            {
                DocumentReference      = "ProfitAndLoss",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            // ============
            // Get Equities
            // ============

            var equities = from d in db.TrnJournals
                           where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                           d.MstAccount.MstAccountType.MstAccountCategory.Id == 4 &&
                           d.MstBranch.CompanyId == CompanyId
                           group d by d.MstAccount into g
                           select new Models.TrnJournal
            {
                DocumentReference      = "3 - Equity",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            var currentUser   = from d in db.MstUsers where d.UserId == User.Identity.GetUserId() select d;
            var incomeAccount = from d in db.MstAccounts where d.Id == currentUser.FirstOrDefault().IncomeAccountId select d;

            var retainedEarnings = from d in profitAndLoss
                                   group d by d.DocumentReference into g
                                   select new Models.TrnJournal
            {
                DocumentReference      = "3 - Equity",
                AccountCategoryCode    = incomeAccount.FirstOrDefault().MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = incomeAccount.FirstOrDefault().MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = incomeAccount.FirstOrDefault().MstAccountType.SubCategoryDescription,
                AccountTypeCode        = incomeAccount.FirstOrDefault().MstAccountType.AccountTypeCode,
                AccountType            = incomeAccount.FirstOrDefault().MstAccountType.AccountType,
                AccountCode            = incomeAccount.FirstOrDefault().AccountCode,
                Account      = incomeAccount.FirstOrDefault().Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.Balance),
            };

            var unionEquitiesWithRetainEarnings = equities.Union(retainedEarnings);

            if (unionEquitiesWithRetainEarnings.Any())
            {
                // ================================
                // Equity Sub Category Descriptions
                // ================================
                var equitySubCategoryDescriptions = from d in unionEquitiesWithRetainEarnings
                                                    group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.CreditAmount - d.DebitAmount)
                };

                if (equitySubCategoryDescriptions.Any())
                {
                    Decimal totalAllEquities = 0;
                    foreach (var equitySubCategoryDescription in equitySubCategoryDescriptions)
                    {
                        PdfPTable equitySubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsEquitySubCategoryDescriptionTable = new float[] { 100f };
                        equitySubCategoryDescriptionTable.SetWidths(widthCellsEquitySubCategoryDescriptionTable);
                        equitySubCategoryDescriptionTable.WidthPercentage = 100;
                        equitySubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(equitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(equitySubCategoryDescriptionTable);

                        // ====================
                        // Equity Account Types
                        // ====================
                        var equityAccountTypes = from d in unionEquitiesWithRetainEarnings
                                                 where d.SubCategoryDescription.Equals(equitySubCategoryDescription.SubCategoryDescription)
                                                 group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.CreditAmount - d.DebitAmount)
                        };

                        if (equityAccountTypes.Any())
                        {
                            Decimal totalCurrentEquities = 0;
                            foreach (var equityAccountType in equityAccountTypes)
                            {
                                totalCurrentEquities += equityAccountType.Balance;

                                PdfPTable equityAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsEquityAccountTypeTable = new float[] { 50f, 100f, 50f };
                                equityAccountTypeTable.SetWidths(widthCellsEquityAccountTypeTable);
                                equityAccountTypeTable.WidthPercentage = 100;
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase(equityAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase(equityAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(equityAccountTypeTable);

                                // ===============
                                // Equity Accounts
                                // ===============
                                var equityAccounts = from d in unionEquitiesWithRetainEarnings
                                                     where d.AccountType.Equals(equityAccountType.AccountType)
                                                     group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
                                };

                                if (equityAccounts.Any())
                                {
                                    foreach (var equityAccount in equityAccounts)
                                    {
                                        totalAllEquities += equityAccount.Balance;

                                        PdfPTable equityAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsEquityAccountTable = new float[] { 50f, 100f, 50f };
                                        equityAccountTable.SetWidths(widthCellsEquityAccountTable);
                                        equityAccountTable.WidthPercentage = 100;
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(equityAccountTable);
                                    }
                                }
                            }

                            // ======================
                            // Total Current Equities
                            // ======================
                            document.Add(line);
                            PdfPTable totalCurrentEquitiesTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentEquitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentEquitiesTable.SetWidths(widthCellsTotalCurrentEquitiesTable);
                            totalCurrentEquitiesTable.WidthPercentage = 100;
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("Total " + equitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase(totalCurrentEquities.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentEquitiesTable);
                        }
                    }

                    // ==================
                    // Total All Equities
                    // ==================
                    document.Add(line);
                    PdfPTable totalAllEquitiesTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllEquitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllEquitiesTable.SetWidths(widthCellsTotalAllEquitiesTable);
                    totalAllEquitiesTable.WidthPercentage = 100;
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("Total Equity", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase(totalAllEquities.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllEquitiesTable);

                    totalOverallEquities += totalAllEquities;
                    document.Add(Chunk.NEWLINE);
                }
            }

            document.Add(Chunk.NEWLINE);

            // ==============================
            // Total Liabilities and Equities
            // ==============================
            Decimal totalLiabilityAndEquity = totalOverallLiabilities + totalOverallEquities;

            document.Add(line);
            PdfPTable tableTotalLiabilityAndEquityTable = new PdfPTable(5);

            float[] widthCellsTableTotalLiabilityAndEquityTable = new float[] { 50f, 70f, 100f, 100f, 60f };
            tableTotalLiabilityAndEquityTable.SetWidths(widthCellsTableTotalLiabilityAndEquityTable);
            tableTotalLiabilityAndEquityTable.WidthPercentage = 100;
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("Total Liability and Equity", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase(totalLiabilityAndEquity.ToString("#,##0.00"), fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            document.Add(tableTotalLiabilityAndEquityTable);

            // =======
            // Balance
            // =======
            Decimal Balance = totalOverallAssets - totalLiabilityAndEquity;

            document.Add(line);
            PdfPTable balanceTable = new PdfPTable(5);

            float[] widthCellsBalanceTable = new float[] { 50f, 70f, 100f, 100f, 60f };
            balanceTable.SetWidths(widthCellsBalanceTable);
            balanceTable.WidthPercentage = 100;
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("Balance", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase(Balance.ToString("#,##0.00"), fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            document.Add(balanceTable);

            document.Close();

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

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Ejemplo n.º 11
0
        private void btnImprimir_Click(object sender, EventArgs e)
        {
            try
            {
                BmsSoftware.ConfigSistema1.Default.TituloRelatorio = txtTitulo.Text;
                BmsSoftware.ConfigSistema1.Default.Save();

                SalveConfig(NometelaSelec, NomeGridSelec);

                int i           = 0;
                int TotalColuna = 0;
                foreach (DataGridViewColumn col in DataGridExport.Columns)
                {
                    if (ctlColumnsToPrintCHKLBX.GetItemCheckState(i) == CheckState.Checked)
                    {
                        col.Visible = true;
                        TotalColuna++;
                    }
                    else
                    {
                        col.Visible = false;
                    }

                    i++;
                }

                //Creating iTextSharp Table from the DataTable data
                PdfPTable pdfTable = new PdfPTable(TotalColuna);
                pdfTable.WidthPercentage = 90;

                //pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfTable.DefaultCell.BorderWidth = 1;
                float[] widths = new float[TotalColuna];

                //Adding Header row
                int x = 0;
                foreach (DataGridViewColumn column in DataGridExport.Columns)
                {
                    if (column.Visible)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                        //pdfTable.WidthPercentage = 100;
                        // pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                        //pdfTable.HeaderHeight = column.Width;
                        cell.HorizontalAlignment = 1;  //0=Left, 1=Center, 2=Right

                        widths[x] = column.Width;
                        x++;

                        pdfTable.SpacingAfter = 10;
                        cell.BackgroundColor  = new iTextSharp.text.BaseColor(240, 240, 240);
                        pdfTable.AddCell(cell);
                    }
                }

                pdfTable.SetWidths(widths);

                //Adding DataRow
                foreach (DataGridViewRow row in DataGridExport.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Visible && row.Visible)
                        {
                            if (cell.Value != null)
                            {
                                PdfPCell cell_Pdf   = new PdfPCell(new Phrase(cell.EditedFormattedValue.ToString()));
                                String   CelulaGrid = string.Empty;

                                if (cell.EditedFormattedValue.ToString().IndexOf(",") != -1 && ValidacoesLibrary.ValidaTipoDecimal(cell.EditedFormattedValue.ToString()))
                                {
                                    CelulaGrid = Convert.ToDecimal(cell.EditedFormattedValue.ToString()).ToString("n2");
                                    PdfPCell cell_Pdf_TipoMoeda = new PdfPCell(new Phrase(CelulaGrid));
                                    cell_Pdf_TipoMoeda.HorizontalAlignment = 2; //0=Left, 1=Center, 2=Right
                                    pdfTable.AddCell(cell_Pdf_TipoMoeda);
                                }
                                //else if (ValidacoesLibrary.ValidaTipoInt32(cell.EditedFormattedValue.ToString()))
                                //{
                                //    CelulaGrid = Convert.ToDecimal(cell.EditedFormattedValue.ToString()).ToString();
                                //    PdfPCell cell_Pdf_Int = new PdfPCell(new Phrase(CelulaGrid));
                                //    cell_Pdf_Int.HorizontalAlignment = 2; //0=Left, 1=Center, 2=Right
                                //    pdfTable.AddCell(cell_Pdf_Int);
                                //}
                                else if (cell.EditedFormattedValue.ToString().Length == 10 && ValidacoesLibrary.ValidaTipoDateTime(cell.EditedFormattedValue.ToString()))
                                {
                                    CelulaGrid = Convert.ToDateTime(cell.EditedFormattedValue.ToString()).ToString("dd/MM/yyyy");
                                    PdfPCell cell_Pdf_Date = new PdfPCell(new Phrase(CelulaGrid));
                                    cell_Pdf_Date.HorizontalAlignment = 2; //0=Left, 1=Center, 2=Right
                                    pdfTable.AddCell(cell_Pdf_Date);
                                }
                                else
                                {
                                    cell_Pdf.HorizontalAlignment = 0; //0=Left, 1=Center, 2=Right
                                    pdfTable.AddCell(cell_Pdf);
                                }
                            }
                            else
                            {
                                pdfTable.AddCell("");
                            }
                        }
                    }
                }



                if (txtNomeArquivo.Text.Trim() == string.Empty)
                {
                    txtNomeArquivo.Text = "ListadaPesquisa";
                }

                //Exporting to PDF
                // string folderPath = "C:\\PDFs\\";
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                using (FileStream stream = new FileStream(folderPath + @"\" + txtNomeArquivo.Text + ".pdf", FileMode.Create))
                {
                    Document pdfDoc = new Document(PageSize.A2, 20f, 10f, 80f, 10f);
                    pdfDoc.AddTitle(txtTitulo.Text);

                    PdfWriter       writer          = PdfWriter.GetInstance(pdfDoc, stream);
                    PageEventHelper pageEventHelper = new PageEventHelper();
                    writer.PageEvent = pageEventHelper;

                    pdfDoc.Open();
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();
                    stream.Close();
                }

                foreach (DataGridViewColumn col in DataGridExport.Columns)
                {
                    col.Visible = true;
                }

                MessageBox.Show("Arquivo " + txtNomeArquivo.Text + ".pdf gerado com sucesso!");

                System.Diagnostics.Process Processo1 = null;
                if (File.Exists(folderPath + @"\" + txtNomeArquivo.Text + ".pdf"))
                {
                    Processo1 = System.Diagnostics.Process.Start(folderPath + @"\" + txtNomeArquivo.Text + ".pdf");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro ao exportar o arquivo PDF!");
                MessageBox.Show("Erro técnico: " + ex.Message);
            }
        }
Ejemplo n.º 12
0
        public Paragraph GetTypeWiseReportPdfParagraph(string fromDate, string toDate, GridView aGridView, string totalFee)
        {
            var    titleFont      = FontFactory.GetFont("Candara", 18, Font.BOLD);
            Phrase headingPhrase  = new Phrase("Type Wise Report" + Environment.NewLine, titleFont);
            Phrase dotlinePhrase  = new Phrase("======================================================================" + Environment.NewLine);
            Phrase fromDatePhrase = new Phrase("From Date: " + fromDate + Environment.NewLine);
            Phrase toDatePhrase   = new Phrase("To Date: " + toDate + Environment.NewLine);

            PdfPTable pdfTable = new PdfPTable(4);

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

            SN.HorizontalAlignment = 1;
            pdfTable.AddCell(SN);
            PdfPCell TestType = new PdfPCell(new Phrase("Test Type"));

            TestType.HorizontalAlignment = 1;
            pdfTable.AddCell(TestType);
            PdfPCell NoOfTest = new PdfPCell(new Phrase("No Of Test"));

            NoOfTest.HorizontalAlignment = 1;
            pdfTable.AddCell(NoOfTest);
            PdfPCell TotalAmount = new PdfPCell(new Phrase("Total Amount"));

            TotalAmount.HorizontalAlignment = 1;
            pdfTable.AddCell(TotalAmount);

            int sn = 1;

            for (int i = 0; i < aGridView.Rows.Count; i++)
            {
                PdfPCell snCell          = new PdfPCell(new Phrase(sn++.ToString()));
                PdfPCell testTypeCell    = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[1].Text));
                PdfPCell noOfTestCell    = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[2].Text));
                PdfPCell totalAmountCell = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[3].Text));

                snCell.HorizontalAlignment          = 1;
                noOfTestCell.HorizontalAlignment    = 1;
                totalAmountCell.HorizontalAlignment = 1;

                pdfTable.AddCell(snCell);
                pdfTable.AddCell(testTypeCell);
                pdfTable.AddCell(noOfTestCell);
                pdfTable.AddCell(totalAmountCell);
            }

            Phrase totalPhrase    = new Phrase("Total: " + totalFee + Environment.NewLine);
            Phrase dotlinePhrase2 = new Phrase("======================================================================" + Environment.NewLine);
            Phrase creditPhrase   = new Phrase("<--- Managed by Team_MVC --->");

            Paragraph aParagraph = new Paragraph();

            aParagraph.Add(headingPhrase);
            aParagraph.Add(dotlinePhrase);
            aParagraph.Add(fromDatePhrase);
            aParagraph.Add(toDatePhrase);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(pdfTable);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(totalPhrase);
            aParagraph.Add(dotlinePhrase2);
            aParagraph.Add(creditPhrase);

            return(aParagraph);
        }
Ejemplo n.º 13
0
        public Paragraph GetUnpaidBillReportPdfParagraph(string fromDate, string toDate, GridView aGridView, string totalFee)
        {
            var    titleFont      = FontFactory.GetFont("Candara", 18, Font.BOLD);
            Phrase headingPhrase  = new Phrase("Unpaid Bill Report" + Environment.NewLine, titleFont);
            Phrase dotlinePhrase  = new Phrase("======================================================================" + Environment.NewLine);
            Phrase fromDatePhrase = new Phrase("From Date: " + fromDate + Environment.NewLine);
            Phrase toDatePhrase   = new Phrase("To Date: " + toDate + Environment.NewLine);

            PdfPTable pdfTable = new PdfPTable(5);

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

            SN.HorizontalAlignment = 1;
            pdfTable.AddCell(SN);
            PdfPCell BillNo = new PdfPCell(new Phrase("Bill No"));

            BillNo.HorizontalAlignment = 1;
            pdfTable.AddCell(BillNo);
            PdfPCell PatientName = new PdfPCell(new Phrase("Patient Name"));

            PatientName.HorizontalAlignment = 1;
            pdfTable.AddCell(PatientName);
            PdfPCell MobileNo = new PdfPCell(new Phrase("Mobile No"));

            MobileNo.HorizontalAlignment = 1;
            pdfTable.AddCell(MobileNo);
            PdfPCell TotalAmount = new PdfPCell(new Phrase("Billl Amount"));

            TotalAmount.HorizontalAlignment = 1;
            pdfTable.AddCell(TotalAmount);

            int sn = 1;

            for (int i = 0; i < aGridView.Rows.Count; i++)
            {
                PdfPCell snCell         = new PdfPCell(new Phrase(sn++.ToString()));
                PdfPCell billNoCell     = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[1].Text));
                PdfPCell nameCell       = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[2].Text));
                PdfPCell mobileNoCell   = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[3].Text));
                PdfPCell billAmountCell = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[4].Text));

                snCell.HorizontalAlignment         = 1;
                billNoCell.HorizontalAlignment     = 1;
                mobileNoCell.HorizontalAlignment   = 1;
                billAmountCell.HorizontalAlignment = 1;

                pdfTable.AddCell(snCell);
                pdfTable.AddCell(billNoCell);
                pdfTable.AddCell(nameCell);
                pdfTable.AddCell(mobileNoCell);
                pdfTable.AddCell(billAmountCell);
            }

            Phrase totalPhrase    = new Phrase("Total: " + totalFee + Environment.NewLine);
            Phrase dotlinePhrase2 = new Phrase("======================================================================" + Environment.NewLine);
            Phrase creditPhrase   = new Phrase("<--- Managed by Team --->");

            Paragraph aParagraph = new Paragraph();

            aParagraph.Add(headingPhrase);
            aParagraph.Add(dotlinePhrase);
            aParagraph.Add(fromDatePhrase);
            aParagraph.Add(toDatePhrase);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(pdfTable);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(totalPhrase);
            aParagraph.Add(dotlinePhrase2);
            aParagraph.Add(creditPhrase);

            return(aParagraph);
        }
Ejemplo n.º 14
0
        public Paragraph GetBillPdfParagraph(string printDate, int PatientId, string patientName, string dateOfBirth, string mobileNo, GridView aGridView, string totalFee)
        {
            var    titleFont          = FontFactory.GetFont("Candara", 18, Font.BOLD);
            Phrase headingPhrase      = new Phrase("Bill Copy" + Environment.NewLine, titleFont);
            Phrase dotlinePhrase      = new Phrase("======================================================================" + Environment.NewLine);
            Phrase printDatePhrase    = new Phrase("Print Date: " + printDate + Environment.NewLine);
            Phrase billNoPhrase       = new Phrase("Bill No: " + PatientId + Environment.NewLine);
            Phrase patientNamePhrase  = new Phrase("Patient Name: " + patientName + Environment.NewLine);
            Phrase dateOfBirthPhrase  = new Phrase("Date of Birth: " + dateOfBirth + Environment.NewLine);
            Phrase mobileNoPhrase     = new Phrase("Mobile No: " + mobileNo + Environment.NewLine);
            Phrase selectedTestPhrase = new Phrase("Selected Tests are: " + Environment.NewLine);

            PdfPTable pdfTable = new PdfPTable(3);

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

            SN.HorizontalAlignment = 1;
            pdfTable.AddCell(SN);
            PdfPCell TestName = new PdfPCell(new Phrase("Test Name"));

            TestName.HorizontalAlignment = 1;
            pdfTable.AddCell(TestName);
            PdfPCell Fee = new PdfPCell(new Phrase("Fee"));

            Fee.HorizontalAlignment = 1;
            pdfTable.AddCell(Fee);

            int sn = 1;

            for (int i = 0; i < aGridView.Rows.Count; i++)
            {
                PdfPCell snCell       = new PdfPCell(new Phrase(sn++.ToString()));
                PdfPCell testNameCell = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[1].Text));
                PdfPCell feeCell      = new PdfPCell(new Phrase(aGridView.Rows[i].Cells[2].Text));
                snCell.HorizontalAlignment  = 1;
                feeCell.HorizontalAlignment = 1;
                pdfTable.AddCell(snCell);
                pdfTable.AddCell(testNameCell);
                pdfTable.AddCell(feeCell);
            }

            Phrase totalPhrase         = new Phrase("Total Fee: " + totalFee + Environment.NewLine);
            Phrase paymentStatusPhrase = new Phrase("Payment Status : Unpaid" + Environment.NewLine);
            Phrase dotlinePhrase2      = new Phrase("======================================================================" + Environment.NewLine);
            Phrase creditPhrase        = new Phrase("<--- Health is Wealth --->");

            Paragraph aParagraph = new Paragraph();

            aParagraph.Add(headingPhrase);
            aParagraph.Add(dotlinePhrase);
            aParagraph.Add(printDatePhrase);
            aParagraph.Add(billNoPhrase);
            aParagraph.Add(patientNamePhrase);
            aParagraph.Add(dateOfBirthPhrase);
            aParagraph.Add(mobileNoPhrase);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(selectedTestPhrase);
            aParagraph.Add(pdfTable);
            aParagraph.Add(Chunk.NEWLINE);
            aParagraph.Add(totalPhrase);
            aParagraph.Add(paymentStatusPhrase);
            aParagraph.Add(dotlinePhrase2);
            aParagraph.Add(creditPhrase);

            return(aParagraph);
        }
Ejemplo n.º 15
0
        protected void Button4_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtDinero.Text))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "SweetAlert", "vacio()", true);
                this.Calcular();
            }
            else
            {
                DataTable dt       = new DataTable();
                Document  document = new Document();
                PdfWriter writer   = PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
                DateTime  fechact  = DateTime.Now;
                this.Calcular();

                var venta = (from ven in contexto.tblVenta
                             orderby ven.idVenta descending
                             select new { ultimo = ven.idVenta }).FirstOrDefault();

                var nuevo = venta.ultimo + 1;


                dt = (DataTable)Session["contado"];

                if (dt.Rows.Count > 0)
                {
                    document.Open();

                    String rutaLogo = Server.MapPath("../Alumno/images/XIUGAR.jpg");

                    var image = iTextSharp.text.Image.GetInstance(rutaLogo);
                    //var image = iTextSharp.text.Image.GetInstance(@"C:\Users\RodrigoM\Desktop\Sitema-XIU-GAR\ProyectoPaslum\ProjectPaslum\Alumno\images\XIUGAR.jpg");

                    // iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance("../../images/avatar.png");
                    //image1.ScalePercent(50f);
                    image.ScaleAbsoluteWidth(220);
                    image.ScaleAbsoluteHeight(90);
                    image.SetAbsolutePosition(350, 720);
                    document.Add(image);


                    Font fontTitle = FontFactory.GetFont(FontFactory.COURIER_BOLD, 25);
                    Font font9     = FontFactory.GetFont(FontFactory.HELVETICA, 13);
                    Font font7     = FontFactory.GetFont(FontFactory.TIMES, 13);
                    Font font8     = FontFactory.GetFont(FontFactory.TIMES, 9);

                    PdfPTable table = new PdfPTable(dt.Columns.Count);

                    //Paragraph title = new Paragraph(string.Format("XIU-GAR"), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20, iTextSharp.text.Font.BOLD));
                    //title.Alignment = Element.ALIGN_CENTER;
                    //document.Add(title);

                    //document.Add(new Paragraph(20, "Ticket XIU-GAR", fontTitle));

                    document.Add(new Chunk("\n"));

                    document.Add(new Paragraph(16, "N° Venta: " + nuevo.ToString(), font7));
                    document.Add(new Paragraph(16, "Vendedor: " + (Session["CompletoNombre"].ToString()), font7));
                    document.Add(new Paragraph(16, "Cliente: " + txtCliente.Text, font7));
                    document.Add(new Paragraph(16, "Domicilio: " + (Session["domicilio"].ToString()), font7));
                    document.Add(new Paragraph(16, "Fecha: " + DateTime.Now.Date.ToString().Substring(0, 10), font7));

                    document.Add(new Chunk("\n"));

                    float[] widths = new float[dt.Columns.Count];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        widths[i] = 4f;
                    }

                    table.SetWidths(widths);
                    table.WidthPercentage = 90;

                    PdfPCell cell = new PdfPCell(new Phrase("columns"));
                    cell.Colspan = dt.Columns.Count;

                    table.AddCell("CODIGO");
                    table.AddCell("DESCRIPCIÓN");
                    table.AddCell("CANTIDAD");
                    table.AddCell("PRECIO");
                    table.AddCell("TOTAL");


                    foreach (DataColumn c in dt.Columns)
                    {
                        if (c.ColumnName == "idProducto")
                        {
                        }
                        else if (c.ColumnName == "strNombre")
                        {
                        }
                        else if (c.ColumnName == "dblPrecio")
                        {
                        }
                        else if (c.ColumnName == "subtotal")
                        {
                        }
                        else if (c.ColumnName == "canproducto")
                        {
                        }
                        else if (c.ColumnName == "preVenta")
                        {
                        }
                        else if (c.ColumnName == "dblCosto")
                        {
                        }

                        else
                        {
                            table.AddCell(new Phrase(c.ColumnName, font8));
                        }
                    }

                    foreach (DataRow r in dt.Rows)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            for (int h = 0; h < dt.Columns.Count; h++)
                            {
                                table.AddCell(new Phrase(r[h].ToString(), font8));
                            }
                        }
                    }

                    document.Add(table);
                    document.Add(new Chunk("\n"));

                    Paragraph total    = new Paragraph(16, "Total: $" + decimal.Parse(lblTotal2.Text), font9);
                    Paragraph efectivo = new Paragraph(16, "Efectivo: $" + decimal.Parse(txtDinero.Text), font9);
                    Paragraph cambio   = new Paragraph(16, "Cambio: $" + (decimal.Parse(txtDinero.Text) - decimal.Parse(lblTotal2.Text)), font9);
                    document.Add(new Chunk("\n"));
                    Paragraph gracias = new Paragraph(18, "Gracias por su compra, vuelva pronto.", font9);


                    total.Alignment    = Element.ALIGN_RIGHT;
                    efectivo.Alignment = Element.ALIGN_RIGHT;
                    cambio.Alignment   = Element.ALIGN_RIGHT;
                    gracias.Alignment  = Element.ALIGN_CENTER;

                    document.Add(total);
                    document.Add(efectivo);
                    document.Add(cambio);
                    document.Add(gracias);
                }

                document.Close();

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=Num. Venta: " + nuevo + "_" + fechact + ".pdf");
                HttpContext.Current.Response.Write(document);
                Response.Flush();
                Response.End();
            }
        }
Ejemplo n.º 16
0
        private void PurchaseOrderReport()
        {
            String path = Application.StartupPath;

            System.IO.Directory.CreateDirectory(path + @"\report");
            Document  document     = new Document();
            String    DateTimeName = DateTime.Now.ToString("dd_MMM_yyyy hh_mm_ss");
            PdfWriter writer       = PdfWriter.GetInstance(document, new FileStream(path + "\\report\\PurchaseOrderReport-" + DateTimeName + ".pdf", FileMode.Create));

            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 8);
            document.Open();
            foreach (object itemChecked in checkedListBox2.CheckedItems)
            {
                DataTable main = new DataTable();
                main.Columns.Add("DESCRIPTION", typeof(string));
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    main.Columns.Add("" + dt1.Rows[i]["AccountName"].ToString(), typeof(string));
                }
                main.Columns.Add("Total", typeof(string));
                Double[]  endtotal = new Double[main.Columns.Count];
                DataTable dtdept   = new DataTable();
                //string str = "select * from DepartmentMaster where ";
                //str += "Departmentname like '%" + itemChecked.ToString() + "%'";
                dtdept      = cl.getdataset("select * from DepartmentMaster where Departmentname like '%" + itemChecked.ToString() + "%'");
                label2.Text = "Department:" + itemChecked.ToString();
                main.Rows.Add(label2.Text);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Double  sum = 0;
                    DataRow dr  = main.NewRow();
                    dr["DESCRIPTION"] = dt.Rows[i]["productname"].ToString();
                    for (int j = 0; j < dt1.Rows.Count; j++)
                    {
                        string qty = cl.ExecuteScalar("select po.qty from purchaseorderproductmaster po inner join productmaster p on p.Product_Name=po.ProductName where po.isactive=1 and p.DepartmentId='" + dtdept.Rows[0]["DepartmentId"].ToString() + "' and po.productname='" + dt.Rows[i]["productname"].ToString() + "'and po.CompanyID='" + dt1.Rows[j]["clientid"].ToString() + "'");
                        if (qty == "")
                        {
                            qty = "0";
                        }
                        dr["" + dt1.Rows[j]["AccountName"].ToString()] = qty;
                        sum             += Convert.ToDouble(qty);
                        endtotal[j + 1] += Convert.ToDouble(qty);
                    }

                    dr["Total"] = sum;
                    if (sum > 0)
                    {
                        main.Rows.Add(dr.ItemArray);
                    }
                }
                double  total  = 0;
                DataRow lastdr = main.NewRow();
                for (int i = 0; i < endtotal.Length; i++)
                {
                    if (i == 0)
                    {
                        lastdr[i] = "Total";
                    }
                    else
                    {
                        lastdr[i] = endtotal[i];
                        total    += Convert.ToDouble(endtotal[i]);
                    }
                }
                lastdr["Total"] = Math.Round(total, 2).ToString();
                main.Rows.Add(lastdr.ItemArray);
                main.Rows.Add();
                PdfPTable bltable  = new PdfPTable(main.Columns.Count);
                float[]   blwidths = new float[] { 4f, 4f, 4f, 4f };
                bltable.WidthPercentage = 100;

                PdfPCell blpcell = new PdfPCell(new Phrase(""));
                blpcell.BorderColor = iTextSharp.text.Color.WHITE;
                blpcell.FixedHeight = 10f;

                for (int i = 0; i < main.Columns.Count; i++)
                {
                    bltable.AddCell(blpcell);
                }
                #region
                PdfPTable table  = new PdfPTable(main.Columns.Count);
                float[]   widths = new float[] { 4f, 4f, 4f, 4f };
                table.WidthPercentage = 100;
                PdfPCell cell = new PdfPCell(new Phrase("Products"));

                cell.Colspan = main.Columns.Count;

                foreach (DataColumn c in main.Columns)
                {
                    table.AddCell(new Phrase(c.ColumnName, font5));
                }

                for (int i = 0; i < main.Rows.Count; i++)
                {
                    for (int j = 0; j < main.Columns.Count; j++)
                    {
                        table.AddCell(new Phrase(main.Rows[i][j].ToString(), font5));
                    }
                }



                document.Add(table);
                document.Add(bltable);


                #endregion
            }

            document.Close();
            #region
            //String sReport =path+ "\\report\\PurchaseOrderReport-" + DateTimeName + ".pdf"; //'Complete name/path of PDF file
            //PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
            //writer.SetOpenAction(action);

            //Print(sReport);
            System.Diagnostics.Process.Start(path + "\\report\\PurchaseOrderReport-" + DateTimeName + ".pdf");
            String pathToExecutable = "AcroRd32.exe";
            #endregion
        }
Ejemplo n.º 17
0
        public static MemoryStream Generate(GarmentCorrectionNote model, IServiceProvider serviceProvider, int clientTimeZoneOffset = 7, string userName = "")
        {
            IGarmentDeliveryOrderFacade garmentDeliveryOrderFacade = (IGarmentDeliveryOrderFacade)serviceProvider.GetService(typeof(IGarmentDeliveryOrderFacade));
            IGarmentInvoice             garmentInvoiceFacade       = (IGarmentInvoice)serviceProvider.GetService(typeof(IGarmentInvoice));

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

            document.Open();

            Font header_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10);
            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);

            PdfPCell cellLeftNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellCenterNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellCenterTopNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_TOP
            };
            PdfPCell cellRightNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            PdfPCell cellJustifyNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_JUSTIFIED
            };
            PdfPCell cellJustifyAllNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_JUSTIFIED_ALL
            };

            PdfPCell cellCenter = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellRight = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellLeft = 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
            };

            var deliveryOrder = garmentDeliveryOrderFacade.ReadById((int)model.DOId);
            var invoice       = garmentInvoiceFacade.ReadByDOId((int)model.DOId);

            #region Header
            string addressString = "PT. DAN LIRIS\n" +
                                   "Head Offce :\n" +
                                   "Kelurahan Banaran, Kecamatan Grogol\n" +
                                   "Sukoharjo 57193 - INDONESIA\n" +
                                   "PO.BOX 166 Solo 57100\n" +
                                   "Telp. (0271) 740888, 714400\n" +
                                   "Fax. (0271) 735222, 740777";
            Paragraph addressParagraph = new Paragraph(8f, addressString, bold_font)
            {
                Alignment = Element.ALIGN_LEFT
            };
            document.Add(addressParagraph);
            Paragraph headerParagraph = new Paragraph("NOTA KOREKSI PAJAK", header_font)
            {
                Alignment = Element.ALIGN_CENTER, SpacingAfter = 15f
            };
            document.Add(headerParagraph);
            #endregion

            #region Identity

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

            PdfPTable tableIdentityLeft = new PdfPTable(2);
            tableIdentityLeft.SetWidths(new float[] { 3f, 5f });

            cellLeftNoBorder.Phrase = new Phrase("No. Nota Koreksi", normal_font);
            tableIdentityLeft.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase($":   {model.CorrectionNo}", normal_font);
            tableIdentityLeft.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("No. Nota Pajak", normal_font);
            tableIdentityLeft.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase($":   {model.NKPH}", normal_font);
            tableIdentityLeft.AddCell(cellLeftNoBorder);

            PdfPTable tableIdentityRight = new PdfPTable(2);
            cellLeftNoBorder.Phrase = new Phrase("Kode Supplier", normal_font);
            tableIdentityRight.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase($":   {model.SupplierCode}", normal_font);
            tableIdentityRight.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase("Nama Supplier", normal_font);
            tableIdentityRight.AddCell(cellLeftNoBorder);
            cellLeftNoBorder.Phrase = new Phrase($":   {model.SupplierName}", normal_font);
            tableIdentityRight.AddCell(cellLeftNoBorder);

            PdfPCell cellIdentityLeft = new PdfPCell(tableIdentityLeft)
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            tableIdentity.AddCell(cellIdentityLeft);
            PdfPCell cellIdentityRight = new PdfPCell(tableIdentityRight)
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            tableIdentity.AddCell(cellIdentityRight);

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

            #endregion

            #region TableContent

            var columnHeaders = new List <string> {
                "No. Surat Jalan", "Tgl. Surat Jalan", "Tgl. Jatuh Tempo", "No. Invoice", "Nama Barang", "Rate", $"Total PPH ({model.CurrencyCode})"
            };

            PdfPTable tableContent = new PdfPTable(columnHeaders.Count);
            tableContent.SetWidths(new float[] { 1.1f, 1.2f, 1f, 1f, 1.1f, 0.5f, 1.2f });

            foreach (var columnName in columnHeaders)
            {
                cellCenter.Phrase = new Phrase(columnName, bold_font);
                tableContent.AddCell(cellCenter);
            }

            Dictionary <string, decimal> dictionaryUnitAmount = new Dictionary <string, decimal>();
            var totalAmountPPH = 0m;
            foreach (var item in model.Items)
            {
                var deliveryOrderItem = deliveryOrder.Items.First(i => i.Details.Any(d => d.Id == item.DODetailId));

                cellLeft.Phrase = new Phrase(deliveryOrder.DONo, normal_font);
                tableContent.AddCell(cellLeft);

                cellLeft.Phrase = new Phrase(deliveryOrder.DODate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
                tableContent.AddCell(cellLeft);

                cellLeft.Phrase = new Phrase(deliveryOrder.DODate.AddDays(deliveryOrderItem.PaymentDueDays).ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
                tableContent.AddCell(cellLeft);

                if (invoice != null)
                {
                    cellLeft.Phrase = new Phrase(invoice.InvoiceNo, normal_font);
                    tableContent.AddCell(cellLeft);
                }
                else
                {
                    cellLeft.Phrase = new Phrase("", normal_font);
                    tableContent.AddCell(cellLeft);
                }

                cellLeft.Phrase = new Phrase(item.ProductName, normal_font);
                tableContent.AddCell(cellLeft);

                cellRight.Phrase = new Phrase(((double)model.IncomeTaxRate).ToString("n", new CultureInfo("id-ID")), normal_font);
                tableContent.AddCell(cellRight);

                decimal totalPPH;

                totalPPH = model.IncomeTaxRate / 100 * item.PricePerDealUnitAfter * item.Quantity;

                totalAmountPPH += totalPPH;

                cellRight.Phrase = new Phrase(totalPPH.ToString("n", new CultureInfo("id-ID")), normal_font);
                tableContent.AddCell(cellRight);
            }

            PdfPCell cellRightMerge = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_TOP,
                Padding             = 5,
                Colspan             = columnHeaders.Count - 1
            };

            cellRightMerge.Phrase = new Phrase($"Total PPH ({model.CurrencyCode})", normal_font);
            tableContent.AddCell(cellRightMerge);

            cellRight.Phrase = new Phrase(totalAmountPPH.ToString("n", new CultureInfo("id-ID")), normal_font);
            tableContent.AddCell(cellRight);

            cellRightMerge.Phrase = new Phrase("Total PPH (IDR)", normal_font);
            tableContent.AddCell(cellRightMerge);

            cellRight.Phrase = new Phrase((totalAmountPPH * (decimal)deliveryOrder.DOCurrencyRate).ToString("n", new CultureInfo("id-ID")), normal_font);
            tableContent.AddCell(cellRight);

            PdfPCell cellContent = new PdfPCell(tableContent);
            tableContent.ExtendLastRow = false;
            tableContent.SpacingAfter  = 60f;
            document.Add(tableContent);

            #endregion

            #region TableSignature

            var signer = new List <string> {
                "Staff Pembelian", "Administrasi", "Keuangan", "Pembukuan"
            };

            PdfPTable tableSignature = new PdfPTable(signer.Count);

            foreach (var columnName in signer)
            {
                cellCenter.Phrase = new Phrase(columnName, bold_font);
                tableSignature.AddCell(cellCenter);
            }

            for (int i = 0; i < signer.Count; i++)
            {
                cellCenter.Phrase = new Phrase("\n\n\n\n\n\n(Nama & Tanggal)", bold_font);
                tableSignature.AddCell(cellCenter);
            }

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

            #endregion

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

            return(stream);
        }
Ejemplo n.º 18
0
            public override void OnStartPage(PdfWriter writer, Document document)
            {
                //BaseFont customfont = BaseFont.CreateFont(System.Web.HttpContext.Current.Server.MapPath("~/fonts/OpenSans-Regular.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);
                //Font font = new Font(customfont);
                //var FontColour = new BaseColor(0, 100, 0);
                //var FontColour1 = new BaseColor(0, 100, 3);
                //PdfPTable headerSectionTbl = new PdfPTable(2);
                //headerSectionTbl.DefaultCell.Border = Rectangle.NO_BORDER;
                //float[] ColumnWidths = new float[] { 119.055F, document.PageSize.Width - 119.055F };
                //headerSectionTbl.SetWidths(ColumnWidths);
                //headerSectionTbl.TotalWidth = document.PageSize.Width;
                //Paragraph p = new Paragraph(new Chunk(new LineSeparator(34.01F, 102.0F, FontColour, Element.ALIGN_LEFT, 0)));
                //PdfPCell cellLine = new PdfPCell(p);
                //cellLine.Colspan = 2;
                //cellLine.MinimumHeight = 34.01F;
                //cellLine.Border = Rectangle.NO_BORDER;
                //cellLine.PaddingLeft = -10;
                //headerSectionTbl.AddCell(cellLine);
                //iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
                //jpg.SetAbsolutePosition(0, 0);
                //Resize image depend upon your need
                //jpg.ScaleToFit(76.5354f, 93.5433f);
                //jpg.SpacingBefore = 14.1732F;
                //jpg.Alignment = Element.ALIGN_RIGHT;
                //Font myFont = FontFactory.GetFont("OpenSans", 12, iTextSharp.text.Font.BOLD, FontColour);
                //Font myFont1 = FontFactory.GetFont("OpenSans", 9, iTextSharp.text.Font.BOLD, FontColour1);
                //Font myFont2 = FontFactory.GetFont("OpenSans", 10, iTextSharp.text.Font.BOLDITALIC, FontColour1);
                //string line1 = "\nPilotsmith (India) Pvt.Ltd." + "\n";
                //string line2 = "www.pilotsmithindia.com" + "\n";
                //string line3 = "\n" + "Manufacturers and Consultants for Food and Ayurvedic Processing Equipments." + "\n";
                //Paragraph header = new Paragraph();
                //Phrase ph1 = new Phrase(line1, myFont);
                //Phrase ph2 = new Phrase(line2, myFont1);
                //Phrase ph3 = new Phrase(line3, myFont2);
                //header.Add(ph1);
                //header.Add(ph2);
                //header.Add(ph3);
                //header.SpacingBefore = 14.1732F;
                //header.Alignment = Element.ALIGN_LEFT;
                //PdfPCell cellImage = new PdfPCell(jpg);
                //cellImage.Border = Rectangle.NO_BORDER;
                //cellImage.PaddingLeft = 42.5197F;
                //headerSectionTbl.AddCell(cellImage);
                //PdfPCell cell1 = new PdfPCell(header);
                //cell1.Border = 0;
                //cell1.PaddingLeft = 19.8425F;
                //headerSectionTbl.AddCell(cell1);
                //headerSectionTbl.WriteSelectedRows(0, -1, 0, document.PageSize.Height, writer.DirectContent);
                var       FontColour       = new BaseColor(211, 211, 211);
                PdfPTable headerSectionTbl = new PdfPTable(1);

                headerSectionTbl.DefaultCell.Border = Rectangle.NO_BORDER;
                float[] ColumnWidths = new float[] { document.PageSize.Width };
                headerSectionTbl.SetWidths(ColumnWidths);
                headerSectionTbl.TotalWidth = document.PageSize.Width;
                Font      myFont = FontFactory.GetFont("OpenSans", 60, iTextSharp.text.Font.NORMAL, FontColour);
                string    line1  = watermark;
                Paragraph header = new Paragraph();
                Phrase    ph1    = new Phrase(line1, myFont);

                header.Add(ph1);
                header.SpacingBefore = 14.1732F;
                header.Alignment     = Element.ALIGN_LEFT;
                PdfPCell cell1 = new PdfPCell(header);

                cell1.Border      = 0;
                cell1.PaddingLeft = 19.8425F;
                headerSectionTbl.AddCell(cell1);
                headerSectionTbl.WriteSelectedRows(0, -1, 110, (document.PageSize.Height / 2) + 20, writer.DirectContent);
                iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
                jpg.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
                jpg.SetAbsolutePosition(0, 0);
                document.Add(jpg);
            }
Ejemplo n.º 19
0
        private void ImprimeCabecalho(PdfWriter writer, Document doc)
        {
            #region Dados do Cabeçalho
            if (ImprimirCabecalhoPadrao)
            {
                BaseColor preto  = new BaseColor(0, 0, 0);
                Font      font   = FontFactory.GetFont("Verdana", 8, Font.NORMAL, preto);
                Font      titulo = FontFactory.GetFont("Verdana", 12, Font.BOLD, preto);
                float[]   sizes  = new float[] { 1f, 3f, 1f };

                PdfPTable table = new PdfPTable(3);
                table.TotalWidth = doc.PageSize.Width - (doc.LeftMargin + doc.RightMargin);
                table.SetWidths(sizes);

                #region Logo Empresa
                Image foot;
                if (File.Exists(BasePath + @"\PublicResources\" + PageSubLogo))
                {
                    foot = Image.GetInstance(BasePath + @"\PublicResources\" + PageSubLogo);
                }
                else
                {
                    foot = Image.GetInstance(BasePath + @"\Content\tne_mascote.png");
                }
                foot.ScalePercent(60);

                PdfPCell cell = new PdfPCell(foot);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                cell.PaddingBottom     = 10f;
                table.AddCell(cell);

                PdfPTable micros = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase(PageSubTitle, font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                micros.AddCell(cell);
                cell        = new PdfPCell(new Phrase(PageTitle, titulo));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                table.AddCell(cell);
                #endregion

                #region Página
                micros      = new PdfPTable(1);
                cell        = new PdfPCell(new Phrase("Página: " + (doc.PageNumber).ToString(), font));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                micros.AddCell(cell);

                cell = new PdfPCell(micros);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border            = 0;
                cell.BorderWidthTop    = 1.5f;
                cell.BorderWidthBottom = 1.5f;
                cell.PaddingTop        = 10f;
                table.AddCell(cell);
                #endregion

                table.WriteSelectedRows(0, -1, doc.LeftMargin, (doc.PageSize.Height - 10), writer.DirectContent);
            }
            #endregion
        }
Ejemplo n.º 20
0
        protected void btnExportarPdf_Click(object sender, EventArgs e)
        {
            Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);

            try
            {
                PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
                pdfDoc.Open();
                Chunk     c = new Chunk("Lista de documentos", FontFactory.GetFont("Verdana", 16));
                Paragraph p = new Paragraph();
                p.Alignment = Element.ALIGN_CENTER;
                p.Add(c);
                p.SpacingAfter = 20;
                pdfDoc.Add(p);

                //Resize image depend upon your need

                Font font8    = FontFactory.GetFont("ARIAL", 7);
                var  boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7);
                var  dt       = UsuariosBAL.Instance.ObtenerReporteDocumentos();
                if (dt != null)
                {
                    //Craete instance of the pdf table and set the number of column in that table
                    PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                    PdfPCell  PdfPCell = null;

                    foreach (DataColumn column in dt.Columns)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(column.ColumnName, boldFont)));
                        PdfTable.AddCell(PdfPCell);
                    }


                    for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                        for (int column = 0; column < dt.Columns.Count; column++)
                        {
                            PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                        }
                    }
                    //PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
                    pdfDoc.Add(PdfTable); // add pdf table to the document
                }
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename= reporte.pdf");
                System.Web.HttpContext.Current.Response.Write(pdfDoc);
                Response.Flush();
                Response.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (DocumentException de)
            {
                System.Web.HttpContext.Current.Response.Write(de.Message);
            }
            catch (IOException ioEx)
            {
                System.Web.HttpContext.Current.Response.Write(ioEx.Message);
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
        }
Ejemplo n.º 21
0
        // GET: Proposal/ExportPDF
        public ActionResult ExportPDF(int recordID)
        {
            Proposal proposals;
            Idea     ideas;
            Fields   field;

            using (TicketingApp db = new TicketingApp())
            {
                proposals = db.Proposal.Where(u => u.recordID == recordID).FirstOrDefault();
                ideas     = db.Idea.Where(idea => idea == proposals.Idea).FirstOrDefault();
            }

            Document document = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

            //var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);


            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                var writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();


                //var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/ABsIS_Logo.jpg"));
                //logo.SetAbsolutePosition(430, 770);
                //logo.ScaleAbsoluteHeight(30);
                //logo.ScaleAbsoluteWidth(70);
                //document.Add(logo);

                PdfPTable table1 = new PdfPTable(1);
                //table1.PaddingTop = 2f;
                PdfPCell cell11 = new PdfPCell();
                cell11.Border = Rectangle.NO_BORDER;
                Phrase phrase = null;

                phrase = new Paragraph();

                phrase.Add(new Chunk("Project Proposal\n\n\n", FontFactory.GetFont("Arial", 20, Font.BOLD, BaseColor.BLACK)));

                phrase.Add(new Chunk("Name of the Project :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.nameOfProject + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));

                phrase.Add(new Chunk("Abstract :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.abstrac + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));

                phrase.Add(new Chunk("Proposal Type :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(ideas.type + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));


                phrase.Add(new Chunk("Introduction :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.introduction + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));


                phrase.Add(new Chunk("Overall Description :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.overallDescription + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));


                phrase.Add(new Chunk("Function Requirements :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.functionalRequirements + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));


                phrase.Add(new Chunk("Non-Function Requirements :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.nonFunctionalRequirements + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));

                phrase.Add(new Chunk("Project Technologies :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.projectTechnologies + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));


                phrase.Add(new Chunk("Result: :\n", FontFactory.GetFont("Arial", 16, Font.BOLD, BaseColor.BLACK)));
                phrase.Add(new Chunk(proposals.result + "\n\n", FontFactory.GetFont("Arial", 14, Font.NORMAL, BaseColor.BLACK)));

                cell11.AddElement(phrase);
                cell11.VerticalAlignment = Element.ALIGN_RIGHT;

                table1.AddCell(cell11);



                document.Add(table1);
                document.Close();
                byte[] bytes = memoryStream.ToArray();
                memoryStream.Close();
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=Proposal.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
            return(null);
        }
Ejemplo n.º 22
0
        public void Invoice()
        {
            var doc = new Document();

            PdfWriter.GetInstance(doc, new FileStream(@"D:\Счет на оплату.pdf", FileMode.OpenOrCreate));
            doc.Open();

            string   fg       = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Fradm.TTF");
            BaseFont baseFont = BaseFont.CreateFont(fg, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            ArrayList list = new ArrayList();

            list.Add("Поставщик");
            list.Add("Юр. адрес");
            iTextSharp.text.Font font  = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);
            PdfPTable            table = new PdfPTable(1);
            PdfPCell             cell  = new PdfPCell();

            for (int k = 0; k < list.Count; k++)
            {
                cell = new PdfPCell(new Phrase(list[k].ToString(), font));
                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                cell.BorderWidth         = 1;
                cell.Colspan             = 15;
                table.AddCell(cell);
            }
            doc.Add(table);

            iTextSharp.text.Phrase j = new Phrase(" ", font);
            Paragraph a = new Paragraph(j);

            a.SpacingAfter = 20;
            doc.Add(a);

            list.Clear();
            list.Add("ИНН");
            list.Add("КПП");
            list.Add("Счет № ");
            list.Add("Получатель");
            list.Add("Банк получателя");
            list.Add("БИК");
            list.Add("Счет № ");
            PdfPTable table2 = new PdfPTable(3);

            cell             = new PdfPCell(new Phrase(list[0].ToString(), font));
            cell.BorderWidth = 1;
            cell.Colspan     = 1;
            table2.AddCell(cell);

            cell             = new PdfPCell(new Phrase(list[1].ToString(), font));
            cell.BorderWidth = 1;
            cell.Colspan     = 1;
            table2.AddCell(cell);

            cell               = new PdfPCell(new Phrase(list[2].ToString(), font));
            cell.BorderWidth   = 1;
            cell.PaddingBottom = 15;
            cell.Colspan       = 2;
            cell.Rowspan       = 4;
            table2.AddCell(cell);

            cell             = new PdfPCell(new Phrase(list[3].ToString(), font));
            cell.BorderWidth = 1;
            cell.Colspan     = 2;
            cell.Rowspan     = 3;
            table2.AddCell(cell);

            cell             = new PdfPCell(new Phrase(list[4].ToString(), font));
            cell.BorderWidth = 1;
            cell.Colspan     = 2;
            cell.Rowspan     = 2;
            table2.AddCell(cell);

            cell             = new PdfPCell(new Phrase(list[5].ToString(), font));
            cell.BorderWidth = 1;
            cell.PaddingTop  = 5;
            cell.Colspan     = 2;
            table2.AddCell(cell);

            cell               = new PdfPCell(new Phrase(list[6].ToString(), font));
            cell.BorderWidth   = 1;
            cell.PaddingBottom = 5;
            cell.Colspan       = 2;
            table2.AddCell(cell);
            doc.Add(table2);

            Random rnd     = new Random();
            string curDate = DateTime.Now.ToLongDateString();

            iTextSharp.text.Phrase j1 = new Phrase("Счет № " + rnd.Next(1, 300) + " от " + curDate, new iTextSharp.text.Font(baseFont, 24, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
            Paragraph a1 = new Paragraph(j1);

            a1.Alignment    = Element.ALIGN_CENTER;
            a1.SpacingAfter = 5;
            doc.Add(a1);

            iTextSharp.text.Phrase j2 = new Phrase("Плательщик      ", new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a2 = new Paragraph(j2);

            a2.Alignment    = Element.ALIGN_LEFT;
            a2.SpacingAfter = 5;
            doc.Add(a2);

            iTextSharp.text.Phrase j3 = new Phrase("Грузополучатель ", new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a3 = new Paragraph(j3);

            a3.Alignment    = Element.ALIGN_LEFT;
            a3.SpacingAfter = 15;
            doc.Add(a3);


            PdfPTable table3 = new PdfPTable(6);

            list.Clear();
            list.Add("№");
            list.Add("Товар");
            list.Add("Единица");
            list.Add("Количество");
            list.Add("Цена");
            list.Add("Сумма");
            for (int k = 0; k < list.Count; k++)
            {
                cell = new PdfPCell(new Phrase(list[k].ToString(), font));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                cell.BorderWidth         = 1;
                table3.AddCell(cell);
            }

            for (int i = 0; i < 20; i++)
            {
                for (int k = 0; k < 6; k++)
                {
                    table3.AddCell(" ");
                }
            }

            doc.Add(table3);

            iTextSharp.text.Phrase j4 = new Phrase("Итого ".PadLeft(120) + rnd.Next(1, 300), new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a4 = new Paragraph(j4);

            a4.Alignment    = Element.ALIGN_CENTER;
            a4.SpacingAfter = 20;
            doc.Add(a4);

            iTextSharp.text.Phrase j5 = new Phrase("Всего на оплату " + rnd.Next(1, 300) + ", на сумму " + rnd.Next(1, 300), new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.UNDERLINE, new BaseColor(Color.Black)));
            Paragraph a5 = new Paragraph(j5);

            a5.Alignment    = Element.ALIGN_LEFT;
            a5.SpacingAfter = 15;
            doc.Add(a5);

            iTextSharp.text.Phrase j6 = new Phrase("Главный директор  _________________________ (_________________________________) ", new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a6 = new Paragraph(j6);

            a6.Alignment    = Element.ALIGN_LEFT;
            a6.SpacingAfter = 15;
            doc.Add(a6);

            iTextSharp.text.Phrase j7 = new Phrase("Главный бухгалтер _________________________ (_________________________________) ", new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a7 = new Paragraph(j7);

            a7.Alignment    = Element.ALIGN_LEFT;
            a7.SpacingAfter = 15;
            doc.Add(a7);

            doc.Close();
        }
Ejemplo n.º 23
0
        private PdfPTable GetDetailInfo(NewShipmentDocumentModel model)
        {
            PdfPTable table = new PdfPTable(8)
            {
                WidthPercentage = 100
            };

            float[] widths = new float[] { 2f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
            table.SetWidths(widths);
            PdfPCell cellHeader = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
            };

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

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

            foreach (var column in bodyTableColumns)
            {
                cellHeader.Phrase = new Phrase(column, TEXT_FONT_BOLD);
                table.AddCell(cellHeader);
            }

            double quantityTotal = 0;
            double lengthTotal   = 0;
            double weightTotal   = 0;

            foreach (var detail in model.Details)
            {
                foreach (var item in detail.Items)
                {
                    foreach (var packingReceiptItem in item.PackingReceiptItems)
                    {
                        cellLeft.Phrase = new Phrase(packingReceiptItem.ProductName, TEXT_FONT);
                        table.AddCell(cellLeft);

                        cellLeft.Phrase = new Phrase(detail.ProductionOrderDesignCode, TEXT_FONT);
                        table.AddCell(cellLeft);

                        cellLeft.Phrase = new Phrase(detail.ProductionOrderNo, TEXT_FONT);
                        table.AddCell(cellLeft);

                        cellLeft.Phrase = new Phrase(detail.ProductionOrderColorType, TEXT_FONT);
                        table.AddCell(cellLeft);

                        cellLeft.Phrase = new Phrase(packingReceiptItem.UOMUnit, TEXT_FONT);
                        table.AddCell(cellLeft);

                        cellRight.Phrase = new Phrase(packingReceiptItem.Quantity.ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
                        table.AddCell(cellRight);
                        quantityTotal += packingReceiptItem.Quantity;

                        cellRight.Phrase = new Phrase((packingReceiptItem.Quantity * packingReceiptItem.Length).ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
                        table.AddCell(cellRight);
                        lengthTotal += (packingReceiptItem.Quantity * packingReceiptItem.Length);

                        cellRight.Phrase = new Phrase((packingReceiptItem.Quantity * packingReceiptItem.Weight).ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
                        table.AddCell(cellRight);
                        weightTotal += (packingReceiptItem.Quantity * packingReceiptItem.Weight);
                    }
                }
            }

            PdfPCell cellColspan = new PdfPCell()
            {
                Colspan             = 5,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
            };

            cellColspan.Phrase = new Phrase("Total", TEXT_FONT);
            table.AddCell(cellColspan);

            cellRight.Phrase = new Phrase(quantityTotal.ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
            table.AddCell(cellRight);

            cellRight.Phrase = new Phrase(lengthTotal.ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
            table.AddCell(cellRight);

            cellRight.Phrase = new Phrase(weightTotal.ToString("N2", CultureInfo.InvariantCulture), TEXT_FONT);
            table.AddCell(cellRight);

            return(table);
        }
Ejemplo n.º 24
0
        public void packingList()
        {
            var doc = new Document();

            PdfWriter.GetInstance(doc, new FileStream(@"D:\Товарная накладная.pdf", FileMode.OpenOrCreate));
            doc.Open();

            string   fg       = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Fradm.TTF");
            BaseFont baseFont = BaseFont.CreateFont(fg, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Phrase j1 = new Phrase("Организация: ООО \"Фирма\"", new iTextSharp.text.Font(baseFont, 16, iTextSharp.text.Font.UNDERLINE, new BaseColor(Color.Black)));
            Paragraph a1 = new Paragraph(j1);

            a1.Alignment    = Element.ALIGN_CENTER;
            a1.SpacingAfter = 5;
            doc.Add(a1);

            string curDate;

            iTextSharp.text.Phrase j2 = new Phrase(curDate = DateTime.Now.ToLongDateString(), new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
            Paragraph a2 = new Paragraph(j2);

            a2.Alignment    = Element.ALIGN_RIGHT;
            a2.SpacingAfter = 5;
            doc.Add(a2);

            Random rnd = new Random();

            iTextSharp.text.Phrase j3 = new Phrase("Накладная № " + rnd.Next(1, 300), new iTextSharp.text.Font(baseFont, 24, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
            Paragraph a3 = new Paragraph(j3);

            a3.Alignment    = Element.ALIGN_CENTER;
            a3.SpacingAfter = 5;
            doc.Add(a3);

            iTextSharp.text.Phrase j4 = new Phrase("От кого   ", new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a4 = new Paragraph(j4);

            a4.Alignment    = Element.ALIGN_LEFT;
            a4.SpacingAfter = 5;
            doc.Add(a4);

            iTextSharp.text.Phrase j5 = new Phrase("Кому      ", new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a5 = new Paragraph(j5);

            a5.Alignment    = Element.ALIGN_LEFT;
            a5.SpacingAfter = 5;
            doc.Add(a5);

            iTextSharp.text.Phrase j6 = new Phrase("Основание ", new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a6 = new Paragraph(j6);

            a6.Alignment    = Element.ALIGN_LEFT;
            a6.SpacingAfter = 20;
            doc.Add(a6);

            iTextSharp.text.Font font  = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);
            PdfPTable            table = new PdfPTable(6);
            PdfPCell             cell  = new PdfPCell();
            ArrayList            list  = new ArrayList();

            list.Add("№");
            list.Add("Товар");
            list.Add("Единица");
            list.Add("Количество");
            list.Add("Цена");
            list.Add("Сумма");
            for (int k = 0; k < list.Count; k++)
            {
                cell = new PdfPCell(new Phrase(list[k].ToString(), font));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                cell.BorderWidth         = 1;
                table.AddCell(cell);
            }

            for (int j = 0; j < 20; j++)
            {
                for (int k = 0; k < 6; k++)
                {
                    table.AddCell(" ");
                }
            }

            doc.Add(table);

            iTextSharp.text.Phrase j0 = new Phrase("Итого ".PadLeft(120) + rnd.Next(1, 300), new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a = new Paragraph(j0);

            a.Alignment = Element.ALIGN_CENTER;
            doc.Add(a);

            iTextSharp.text.Phrase j7 = new Phrase("Сдал   ___________________", new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a7 = new Paragraph(j7);

            a7.Alignment    = Element.ALIGN_CENTER;
            a7.SpacingAfter = 10;
            doc.Add(a7);

            iTextSharp.text.Phrase j8 = new Phrase("Принял ___________________", new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a8 = new Paragraph(j8);

            a8.Alignment    = Element.ALIGN_CENTER;
            a8.SpacingAfter = 10;
            doc.Add(a8);

            doc.Close();
        }
Ejemplo n.º 25
0
        //private static void SetFooter(Document document)
        //{

        //}

        //private static void SetCurrencyTable(Document document, List<Summary> currencySummaries)
        //{

        //}

        //private static void SetCategoryTable(Document document, List<Summary> categorySummaries, decimal categorySummaryTotal)
        //{

        //}

        private static void SetReportTable(Document document, LocalPurchasingBookReportViewModel viewModel, int timezoneOffset)

        {
            var table = new PdfPTable(16)
            {
                WidthPercentage = 95
            };

            var widths = new List <float>();

            for (var i = 0; i < 16; i++)
            {
                if (i == 1 || i == 10)
                {
                    widths.Add(1f);
                    continue;
                }

                if (i == 3)
                {
                    widths.Add(3f);
                    continue;
                }

                widths.Add(2f);
            }
            table.SetWidths(widths.ToArray());

            SetReportTableHeader(table);

            var grouppedByAccountingCategoriNames = viewModel.Reports.Where(x => x.AccountingUnitName != null).OrderBy(order => order.AccountingLayoutIndex).GroupBy(x => x.AccountingCategoryName).ToList();

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

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

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

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

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

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

            var totalCellNoBorderTopAndBot = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderWidthBottom   = 0,
                BorderWidthTop      = 0
            };

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

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

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

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

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

            var summaryUnit = new Dictionary <string, decimal>();

            foreach (var grouppedAccountingCategory in grouppedByAccountingCategoriNames)
            {
                var accountingCategoryName = grouppedAccountingCategory.Select(x => x.AccountingCategoryName).FirstOrDefault();
                categoryCell.Phrase  = new Phrase(accountingCategoryName, _smallBoldFont);
                categoryCell.Colspan = 18;
                table.AddCell(categoryCell);

                var     totalUnit       = new Dictionary <string, Dictionary <string, decimal> >();
                var     totalCurrencies = new Dictionary <string, Dictionary <string, decimal> >();
                decimal totalIdrDpp     = 0;
                decimal totalIdr        = 0;
                decimal totalIdrVat     = 0;
                decimal totalIdrTax     = 0;

                foreach (var data in grouppedAccountingCategory)
                {
                    cell.Phrase = new Phrase(data.ReceiptDate.AddHours(timezoneOffset).ToString("yyyy-dd-MM"), _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.SupplierCode, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.SupplierName, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.Remark, _smallerFont);
                    table.AddCell(cell);

                    //cell.Phrase = new Phrase(data.IPONo, _smallerFont);
                    //table.AddCell(cell);

                    cell.Phrase = new Phrase(data.URNNo, _smallerFont);
                    table.AddCell(cell);

                    //cell.Phrase = new Phrase(data.DONo, _smallerFont);
                    //table.AddCell(cell);

                    cell.Phrase = new Phrase(data.InvoiceNo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.VATNo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.UPONo, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.CategoryCode + " - " + data.CategoryName, _smallerFont);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(data.AccountingUnitName, _smallerFont);
                    table.AddCell(cell);

                    cellNoBorderRight.Phrase = new Phrase(data.CurrencyCode, _smallerFont);
                    table.AddCell(cellNoBorderRight);

                    cellNoBorderLeft.Phrase = new Phrase(string.Format("{0:n}", data.DPP), _smallerFont);
                    table.AddCell(cellNoBorderLeft);

                    //dppCell.Phrase = new Phrase(data.CurrencyCode + " " + string.Format("{0:n}", data.DPP), _smallerFont);
                    //table.AddCell(dppCell);

                    //cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", data.CurrencyRate), _smallerFont);
                    //table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", data.DPPCurrency), _smallerFont);
                    table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", data.VAT * data.CurrencyRate), _smallerFont);
                    table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", data.IncomeTax * data.CurrencyRate), _smallerFont);
                    table.AddCell(cellAlignRight);

                    //var subTotalIdr = data.IncomeTaxBy == "Supplier" ? data.Total + (data.IncomeTax * data.CurrencyRate) : data.Total;
                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", data.TotalCurrency), _smallerFont);
                    table.AddCell(cellAlignRight);

                    // Units summary
                    if (totalUnit.ContainsKey(data.AccountingUnitName))
                    {
                        totalUnit[data.AccountingUnitName]["DPP"]         += data.DPP;
                        totalUnit[data.AccountingUnitName]["VAT"]         += data.VAT * data.CurrencyRate;
                        totalUnit[data.AccountingUnitName]["TAX"]         += data.IncomeTax * data.CurrencyRate;
                        totalUnit[data.AccountingUnitName]["DPPCurrency"] += data.DPPCurrency;
                        totalUnit[data.AccountingUnitName]["TOTAL"]       += data.TotalCurrency;
                    }
                    else
                    {
                        totalUnit.Add(data.AccountingUnitName, new Dictionary <string, decimal>()
                        {
                            { "DPP", data.DPP },
                            { "VAT", data.VAT * data.CurrencyRate },
                            { "TAX", data.IncomeTax * data.CurrencyRate },
                            { "DPPCurrency", data.DPPCurrency },
                            { "TOTAL", data.TotalCurrency }
                        });
                    }

                    if (summaryUnit.ContainsKey(data.AccountingUnitName))
                    {
                        summaryUnit[data.AccountingUnitName] += data.TotalCurrency;
                    }
                    else
                    {
                        summaryUnit.Add(data.AccountingUnitName, data.TotalCurrency);
                    }


                    //var dpp = data.IncomeTaxBy == "Supplier" ? data.DPP + data.IncomeTax : data.DPP;
                    //var dppCurrency = data.IncomeTaxBy == "Supplier" ? data.DPPCurrency + (data.IncomeTax * data.CurrencyRate) : data.DPPCurrency;
                    // Currencies summary
                    if (totalCurrencies.ContainsKey(data.CurrencyCode))
                    {
                        totalCurrencies[data.CurrencyCode]["DPP"]         += data.DPP;
                        totalCurrencies[data.CurrencyCode]["VAT"]         += data.VAT * data.CurrencyRate;
                        totalCurrencies[data.CurrencyCode]["TAX"]         += data.IncomeTax * data.CurrencyRate;
                        totalCurrencies[data.CurrencyCode]["DPPCurrency"] += data.DPPCurrency;
                        totalCurrencies[data.CurrencyCode]["TOTAL"]       += data.TotalCurrency;
                    }
                    else
                    {
                        totalCurrencies.Add(data.CurrencyCode, new Dictionary <string, decimal>()
                        {
                            { "DPP", data.DPP },
                            { "VAT", data.VAT * data.CurrencyRate },
                            { "TAX", data.IncomeTax * data.CurrencyRate },
                            { "DPPCurrency", data.DPPCurrency },
                            { "TOTAL", data.TotalCurrency }
                        });
                    }

                    totalIdr    += data.TotalCurrency;
                    totalIdrDpp += data.DPPCurrency;
                    totalIdrTax += data.IncomeTax * data.CurrencyRate;
                    totalIdrVat += data.VAT * data.CurrencyRate;
                }

                //var cellGrandTotal = new PdfPCell()
                //{
                //    HorizontalAlignment = Element.ALIGN_RIGHT,
                //    VerticalAlignment = Element.ALIGN_CENTER,
                //    Colspan = 16
                //};

                //cellGrandTotal.Phrase = new Phrase("Grand Total", _smallerBoldFont);
                //table.AddCell(cellGrandTotal);

                //cellGrandTotal.Phrase = new Phrase(string.Format("{0:n}", grandTotal), _smallerBoldFont);
                //table.AddCell(cellGrandTotal);
                totalCell.Phrase  = new Phrase($"TOTAL {accountingCategoryName}", _smallBoldFont);
                totalCell.Colspan = 10;
                table.AddCell(totalCell);

                foreach (var totalCurrency in totalCurrencies)
                {
                    cellNoBorderRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Key), _smallerFont);
                    table.AddCell(cellNoBorderRight);

                    cellNoBorderLeft.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value["DPP"]), _smallerFont);
                    table.AddCell(cellNoBorderLeft);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value["DPPCurrency"]), _smallerFont);
                    table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value["VAT"]), _smallerFont);
                    table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value["TAX"]), _smallerFont);
                    table.AddCell(cellAlignRight);

                    cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalCurrency.Value["TOTAL"]), _smallerBoldFont);
                    table.AddCell(cellAlignRight);

                    totalCellNoBorderTopAndBot.Phrase  = new Phrase();
                    totalCellNoBorderTopAndBot.Colspan = 10;
                    table.AddCell(totalCellNoBorderTopAndBot);
                }

                cellAlignRightColspan3.Phrase = new Phrase(string.Format("{0:n}", totalIdrDpp), _smallerFont);
                table.AddCell(cellAlignRightColspan3);

                cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalIdrVat), _smallerFont);
                table.AddCell(cellAlignRight);

                cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalIdrTax), _smallerFont);
                table.AddCell(cellAlignRight);

                cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", totalIdr), _smallerBoldFont);
                table.AddCell(cellAlignRight);

                if (totalUnit.Count() > 0)
                {
                    foreach (var v in totalUnit)
                    {
                        totalCategoryUnitCell.Phrase  = new Phrase($"{accountingCategoryName}", _smallBoldFont);
                        totalCategoryUnitCell.Colspan = 8;
                        table.AddCell(totalCategoryUnitCell);

                        cellColspan2.Phrase = new Phrase($"{v.Key}  ", _smallBoldFont);
                        table.AddCell(cellColspan2);

                        cellAlignRightColspan3.Phrase = new Phrase(string.Format("{0:n}", v.Value["DPPCurrency"]), _smallerFont);
                        table.AddCell(cellAlignRightColspan3);

                        cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", v.Value["VAT"]), _smallerFont);
                        table.AddCell(cellAlignRight);

                        cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", v.Value["TAX"]), _smallerFont);
                        table.AddCell(cellAlignRight);

                        cellAlignRight.Phrase = new Phrase(string.Format("{0:n}", v.Value["TOTAL"]), _smallerBoldFont);
                        table.AddCell(cellAlignRight);

                        //totalUnitCell.Phrase = new Phrase(string.Format("{0:n}", v.Value), _smallerFont);
                        //totalUnitCell.Colspan = 6;
                        //table.AddCell(totalUnitCell);
                    }
                }
            }

            document.Add(table);

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

            var summaryTable = new PdfPTable(5)
            {
                WidthPercentage = 95,
            };

            var widthSummaryTable = new List <float>()
            {
                2f, 1f, 2f, 1f, 4f
            };

            summaryTable.SetWidths(widthSummaryTable.ToArray());

            summaryTable.AddCell(GetCategorySummaryTable(viewModel.CategorySummaries, viewModel.CategorySummaryTotal));
            summaryTable.AddCell(new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            });
            summaryTable.AddCell(GetUnitSummaryTable(summaryUnit));
            summaryTable.AddCell(new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            });
            summaryTable.AddCell(GetCurrencySummaryTable(viewModel.CurrencySummaries));

            document.Add(summaryTable);
        }
Ejemplo n.º 26
0
        protected void btnFirstPDFeeeeee_ResponseOutput_Click(object sender, EventArgs e)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    // Creae the document object, assigning the page margins
                    Document  document = new Document(PageSize.A4, 25, 25, 30, 30);
                    PdfWriter writer   = PdfWriter.GetInstance(document, ms);
                    // Open the document, enabeling writing to the document
                    document.Open();



                    PdfPTable table = new PdfPTable(2);

                    table.DefaultCell.Border = Rectangle.NO_BORDER;

                    PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
                    cell.Colspan             = 2;
                    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    cell.Border = Rectangle.NO_BORDER;
                    table.AddCell(cell);



                    table.AddCell("Col 1-1");
                    table.AddCell("Col 1-2");
                    table.AddCell("Col 2-1");
                    table.AddCell("Col 2-2");



                    table.AddCell("Col 3-1");
                    var image = iTextSharp.text.Image.GetInstance(Server.MapPath("btw_logo.jpg"));
                    image.SpacingBefore = 10f;
                    image.SpacingAfter  = 10f;
                    var imageCell = new PdfPCell(image);

                    imageCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    imageCell.Border = Rectangle.NO_BORDER;
                    table.AddCell(imageCell);

                    //Add space between table rows
                    PdfPCell spacecell1 = new PdfPCell(new Phrase("\n"));
                    spacecell1.Colspan             = 2;
                    spacecell1.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                    spacecell1.Border = Rectangle.NO_BORDER;
                    table.AddCell(spacecell1);

                    table.AddCell("Col 4-1");
                    table.AddCell("Col 5-2");
                    document.Add(table);

                    document.Close();
                    writer.Close();
                    ms.Close();
                    Response.ContentType = "pdf/application";
                    Response.AddHeader("content-disposition", "attachment;filename=First PDF document.pdf");
                    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 27
0
        protected virtual async Task <PdfPTable> PreparePackagingSlipsProducts(Order order, Shipment shipment, Language language)
        {
            var font = PdfExtensions.GetFont(_pdfSettings.FontFileName);

            var productsTable = new PdfPTable(3);

            productsTable.WidthPercentage = 100f;
            if (language.Rtl)
            {
                productsTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                productsTable.SetWidths(new[] { 20, 20, 60 });
            }
            else
            {
                productsTable.SetWidths(new[] { 60, 20, 20 });
            }

            //product name
            var cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFPackagingSlip.ProductName", language.Id), font));

            cell.BackgroundColor     = BaseColor.LightGray;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            productsTable.AddCell(cell);

            //SKU
            cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFPackagingSlip.SKU", language.Id), font));
            cell.BackgroundColor     = BaseColor.LightGray;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            productsTable.AddCell(cell);

            //qty
            cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFPackagingSlip.QTY", language.Id), font));
            cell.BackgroundColor     = BaseColor.LightGray;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            productsTable.AddCell(cell);

            foreach (var si in shipment.ShipmentItems)
            {
                var productAttribTable = new PdfPTable(1);
                if (language.Rtl)
                {
                    productAttribTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                }
                productAttribTable.DefaultCell.Border = Rectangle.NO_BORDER;

                //product name
                var orderItem = order.OrderItems.Where(x => x.Id == si.OrderItemId).FirstOrDefault();
                if (orderItem == null)
                {
                    continue;
                }

                var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId);

                string name = product.GetLocalized(x => x.Name, language.Id);
                productAttribTable.AddCell(new Paragraph(name, font));
                //attributes
                if (!string.IsNullOrEmpty(orderItem.AttributeDescription))
                {
                    var attributesFont = PdfExtensions.GetFont(_pdfSettings.FontFileName);
                    attributesFont.SetStyle(Font.ITALIC);

                    var attributesParagraph = new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderItem.AttributeDescription, true, true), attributesFont);
                    productAttribTable.AddCell(attributesParagraph);
                }

                productsTable.AddCell(productAttribTable);

                //SKU
                var sku = product.FormatSku(orderItem.AttributesXml, _productAttributeParser);
                cell = new PdfPCell(new Phrase(sku ?? String.Empty, font));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cell);

                //qty
                cell = new PdfPCell(new Phrase(si.Quantity.ToString(), font));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cell);
            }

            return(productsTable);
        }
Ejemplo n.º 28
0
        public MemoryStream GeneratePdfTemplate(CostCalculationGarmentViewModel 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);
            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 PENJUALAN UMUM", 10, 805, 0);
            cb.EndText();
            #endregion

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

            float[] detail1_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 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
            };
            PdfPCell cell_colon = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
            };
            cell_colon.Phrase = new Phrase(":", normal_font);

            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}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("SIZE RANGE", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.SizeRange.Name}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("LEAD TIME", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.LeadTime}", normal_font);
            table_detail1.AddCell(cell_detail1);

            cell_detail1.Phrase = new Phrase("ARTICLE", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.Article}", 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("FABRIC", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.FabricAllowance}%", normal_font);
            table_detail1.AddCell(cell_detail1);

            cell_detail1.Phrase = new Phrase("DATE", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel._CreatedUtc.ToString("dd MMMM yyyy")}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("COMMODITY", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.Commodity}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("ACC", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.AccessoriesAllowance}%", normal_font);
            table_detail1.AddCell(cell_detail1);

            cell_detail1.Phrase = new Phrase("LINE", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.Line.Name}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_detail1);
            #endregion

            #region 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_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 = 180f;

            float[] detail2_widths = new float[] { 1f, 2f };
            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("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("DESCRIPTION", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Description}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("CONT/STYLE", 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("BUYER", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Buyer.Name}", 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.ToString("dd/MM/yyyy")}", normal_font);
            table_detail2.AddCell(cell_detail2);
            #endregion

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

            float[] detail3_widths = new float[] { 1.7f, 1f, 1.3f };
            table_detail3.SetWidths(detail3_widths);

            PdfPCell cell_detail3 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 3
            };

            PdfPCell cell_detail3_colspan2 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 3, Colspan = 2
            };

            cell_detail3.Phrase = new Phrase("TOTAL (OL+Material)", normal_font);
            table_detail3.AddCell(cell_detail3);
            double total = 0;
            foreach (CostCalculationGarment_MaterialViewModel item in viewModel.CostCalculationGarment_Materials)
            {
                total += item.Total;
            }
            total += viewModel.ProductionCost;
            cell_detail3_colspan2.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(total), normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            cell_detail3.Phrase = new Phrase("OTL 1", normal_font);
            table_detail3.AddCell(cell_detail3);
            double OTL1CalculatedValue = viewModel.OTL1.CalculatedValue ?? 0;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(OTL1CalculatedValue)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            double afterOTL1 = total + OTL1CalculatedValue;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(afterOTL1)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("OTL 2", normal_font);
            table_detail3.AddCell(cell_detail3);
            double OTL2CalculatedValue = viewModel.OTL2.CalculatedValue ?? 0;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(OTL2CalculatedValue)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            double afterOTL2 = afterOTL1 + OTL2CalculatedValue;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(afterOTL2)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("RISK", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase(String.Format("{0:0.00}%", viewModel.Risk), normal_font);
            table_detail3.AddCell(cell_detail3);
            double afterRisk = (100 + viewModel.Risk) * afterOTL2 / 100;;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(afterRisk)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("BEA ANGKUT", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(viewModel.FreightCost)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            double afterFreightCost = afterRisk + viewModel.FreightCost;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(afterFreightCost)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("SUB TOTAL", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(afterFreightCost)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            cell_detail3.Phrase = new Phrase("NET/FOB (%)", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase(String.Format("{0:0.00}%", viewModel.NETFOBP), normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(viewModel.NETFOB)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("COMM (%)", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase(String.Format("{0:0.00}%", viewModel.CommissionPortion), normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(viewModel.CommissionRate)}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Phrase = new Phrase("CONFIRM PRICE", normal_font);
            table_detail3.AddCell(cell_detail3);;
            double confirmPrice         = viewModel.ConfirmPrice ?? 0 + viewModel.Rate.Value ?? 0;
            double confirmPriceWithRate = isDollar ? confirmPrice * viewModel.Rate.Value ?? 1 : confirmPrice;
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(confirmPriceWithRate)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            ////cell_detail3.Phrase = new Phrase("PROCESS COST" + "".PadRight(5), normal_font);
            cell_detail3.Phrase = new Phrase("OL" + "".PadRight(5), normal_font);
            table_detail3.AddCell(cell_detail3);
            double processCost = viewModel.ProductionCost;
            ////cell_detail3_colspan2.Phrase = new Phrase($"{GetCurrencyValue(processCost, isDollar)}", normal_font);
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(processCost)}", normal_font);
            //cell_detail3_colspan2.Phrase = new Phrase($"{(processCost)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            cell_detail3.Phrase = new Phrase("OTL1" + "".PadRight(5), normal_font);
            table_detail3.AddCell(cell_detail3);
            double NOTL1CalculatedValue = viewModel.OTL1.CalculatedValue ?? 0;
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(NOTL1CalculatedValue)}", normal_font);
            //cell_detail3_colspan2.Phrase = new Phrase($"{(NOTL1CalculatedValue)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            cell_detail3.Phrase = new Phrase("OTL2" + "".PadRight(5), normal_font);
            table_detail3.AddCell(cell_detail3);
            double NOTL2CalculatedValue = viewModel.OTL2.CalculatedValue ?? 0;
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(NOTL2CalculatedValue)}", normal_font);
            //cell_detail3_colspan2.Phrase = new Phrase($"{(NOTL2CalculatedValue)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);

            cell_detail3.Phrase = new Phrase("Total (OL+OTL1+OTL2)" + "".PadRight(5), normal_font);
            table_detail3.AddCell(cell_detail3);
            double totale = viewModel.ProductionCost + NOTL1CalculatedValue + NOTL2CalculatedValue;
            cell_detail3_colspan2.Phrase = new Phrase($"{Number.ToRupiahWithoutSymbol(totale)}", normal_font);
            //cell_detail3_colspan2.Phrase = new Phrase($"{(totale)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan2);
            #endregion
            #region Detail 4.1 (Bottom, Column 3.1)
            PdfPTable table_detail4_1 = new PdfPTable(2);
            table_detail4_1.TotalWidth = 180f;

            float[] detail4_1_widths = new float[] { 1f, 1f };
            table_detail4_1.SetWidths(detail4_1_widths);

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

            cell_detail4_1.Phrase = new Phrase("FOB PRICE", bold_font);
            table_detail4_1.AddCell(cell_detail4_1);
            cell_detail4_1.Phrase = new Phrase("CMT PRICE", bold_font);
            table_detail4_1.AddCell(cell_detail4_1);

            double CM_Price = 0;
            foreach (CostCalculationGarment_MaterialViewModel item in viewModel.CostCalculationGarment_Materials)
            {
                CM_Price += item.CM_Price ?? 0;
            }
            double ConfirmPrice = viewModel.ConfirmPrice ?? 0;
            double CMT          = CM_Price > 0 ? ConfirmPrice : 0;
            string CMT_Price    = this.GetCurrencyValue(CMT, isDollar);
            double FOB          = ConfirmPrice + CM_Price;
            string FOB_Price    = this.GetCurrencyValue(FOB, isDollar);
            cell_detail4_1.Phrase = new Phrase($"{FOB_Price}", normal_font);
            table_detail4_1.AddCell(cell_detail4_1);
            cell_detail4_1.Phrase = new Phrase($"{CMT_Price}", normal_font);
            table_detail4_1.AddCell(cell_detail4_1);
            #endregion

            #region Detail 4.2 (Bottom, Column 3.2)
            PdfPTable table_detail4_2 = new PdfPTable(2);
            table_detail4_2.TotalWidth = 180f;

            float[] detail4_2_widths = new float[] { 1f, 1f };
            table_detail4_2.SetWidths(detail4_2_widths);

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

            cell_detail4_2.Phrase = new Phrase("CNF PRICE", bold_font);
            table_detail4_2.AddCell(cell_detail4_2);
            cell_detail4_2.Phrase = new Phrase("CIF PRICE", bold_font);
            table_detail4_2.AddCell(cell_detail4_2);

            string CNF_Price = this.GetCurrencyValue(0, isDollar);
            cell_detail4_2.Phrase = new Phrase($"{CNF_Price}", normal_font);
            table_detail4_2.AddCell(cell_detail4_2);
            string CIF_Price = this.GetCurrencyValue(0, isDollar);
            cell_detail4_2.Phrase = new Phrase($"{CIF_Price}", normal_font);
            table_detail4_2.AddCell(cell_detail4_2);
            #endregion

            #region Detail 5 (Bottom, Column 3.3)
            PdfPTable table_detail5 = new PdfPTable(4);
            table_detail5.TotalWidth = 180f;

            float[] detail5_widths = new float[] { 1f, 1.25f, 1f, 1.25f };
            table_detail5.SetWidths(detail5_widths);
            PdfPCell cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };

            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            cell_detail5.Phrase = new Phrase("FREIGHT", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            string freight = this.GetCurrencyValue(viewModel.Freight ?? 0, isDollar);
            cell_detail5.Phrase = new Phrase($"= {freight}", normal_font);
            table_detail5.AddCell(cell_detail5);

            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            cell_detail5.Phrase = new Phrase("INSURANCE", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            string insurance = this.GetCurrencyValue(viewModel.Insurance ?? 0, isDollar);
            cell_detail5.Phrase = new Phrase($"= {insurance}", normal_font);
            table_detail5.AddCell(cell_detail5);

            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            cell_detail5.Phrase = new Phrase("CONFIRM PRICE", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3, Colspan = 2
            };
            string confirmPriceFOB = this.GetCurrencyValue(viewModel.ConfirmPrice ?? 0, isDollar);
            cell_detail5.Phrase = new Phrase($"= {confirmPriceFOB}", normal_font);
            table_detail5.AddCell(cell_detail5);

            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase("SMV CUT", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase($"= {viewModel.SMV_Cutting}", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase("SMV SEW", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase($"= {viewModel.SMV_Sewing}", normal_font);
            table_detail5.AddCell(cell_detail5);

            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase("SMV FIN", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase($"= {viewModel.SMV_Finishing}", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase("SMV TOT", normal_font);
            table_detail5.AddCell(cell_detail5);
            cell_detail5 = new PdfPCell()
            {
                Border = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingTop = 5, PaddingRight = 3, PaddingBottom = 5, PaddingLeft = 3
            };
            cell_detail5.Phrase = new Phrase($"= {viewModel.SMV_Total}", normal_font);
            table_detail5.AddCell(cell_detail5);
            #endregion

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

            float[] signature_widths = new float[] { 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("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);
            cell_signature.Phrase = new Phrase(signatureArea, 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("Direktur Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            #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_detail1.TotalHeight ? imageHeight : table_detail1.TotalHeight;
            float   row2Y              = row1Y - row1Height - 10;
            float[] row3Heights        = { table_detail2.TotalHeight, table_detail3.TotalHeight, table_detail4_1.TotalHeight + 10 + table_detail4_2.TotalHeight + 10 + table_detail5.TotalHeight };
            float   dollarDetailHeight = 10;
            if (isDollar)
            {
                row3Heights[2] += dollarDetailHeight;
            }
            float row3Height = row3Heights.Max();
            float secondHighestRow3Height = row3Heights[1] > row3Heights[2] ? row3Heights[1] : row3Heights[2];
            bool  signatureInsideRow3     = row3Heights.Max() == row3Heights[0] && row3Heights[0] - 10 - secondHighestRow3Height > table_signature.TotalHeight;
            float row2RemainingHeight     = row2Y - 10 - row3Height - printedOnHeight - margin;
            float row2AllowedHeight       = row2Y - printedOnHeight - margin;

            for (int i = 0; i < viewModel.CostCalculationGarment_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.CostCalculationGarment_Materials[i].Category.SubCategory != null ? String.Format("{0} - {1}", viewModel.CostCalculationGarment_Materials[i].Category.Name, viewModel.CostCalculationGarment_Materials[i].Category.SubCategory) : viewModel.CostCalculationGarment_Materials[i].Category.Name, normal_font);
                table_ccm.AddCell(cell_ccm_left);

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

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

                cell_ccm_right.Phrase = new Phrase(String.Format("{0} {1}", viewModel.CostCalculationGarment_Materials[i].Quantity, viewModel.CostCalculationGarment_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.CostCalculationGarment_Materials[i].Price), viewModel.CostCalculationGarment_Materials[i].UOMPrice.Name), normal_font);
                table_ccm.AddCell(cell_ccm_right);

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

                Total += viewModel.CostCalculationGarment_Materials[i].Total;
                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.CalculateHeights();
                        row2Y = startY;
                        row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
                        row2AllowedHeight   = 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 row3RemainingHeight = row3Y - printedOnHeight - margin;
            if (row3RemainingHeight < row3Height)
            {
                this.DrawPrintedOn(now, bf, cb);
                row3Y = startY;
                document.NewPage();
            }

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

            table_detail3.WriteSelectedRows(0, -1, 200, row3Y, cb);

            table_detail4_1.WriteSelectedRows(0, -1, 400, row3Y, cb);

            float detail4_2Y = row3Y - table_detail4_1.TotalHeight - 10;
            table_detail4_2.WriteSelectedRows(0, -1, 400, detail4_2Y, cb);

            float noteY = detail4_2Y - table_detail4_2.TotalHeight;
            float table_detail5Y;
            if (isDollar)
            {
                noteY          = noteY - 15;
                table_detail5Y = noteY - 5;
                cb.BeginText();
                cb.SetFontAndSize(bf, 7);
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, $"NOTE: 1 US$ = {Number.ToRupiah(viewModel.Rate.Value)}", 400, noteY, 0);
                cb.EndText();
            }
            else
            {
                table_detail5Y = noteY - 10;
            }
            table_detail5.WriteSelectedRows(0, -1, 400, table_detail5Y, cb);

            float table_signatureX;
            float table_signatureY;
            if (signatureInsideRow3)
            {
                table_signatureX           = margin + table_detail2.TotalWidth + 10;
                table_signatureY           = row3Y - row3Height + table_signature.TotalHeight;
                table_signature.TotalWidth = 390f;
            }
            else
            {
                table_signatureX = margin;
                table_signatureY = row3Y - row3Height - 10;
                float signatureRemainingHeight = table_signatureY - printedOnHeight - margin;
                if (signatureRemainingHeight < table_signature.TotalHeight)
                {
                    this.DrawPrintedOn(now, bf, cb);
                    table_signatureY = startY;
                    document.NewPage();
                }
            }
            table_signature.WriteSelectedRows(0, -1, table_signatureX, table_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);
        }
Ejemplo n.º 29
0
        public byte[] GeneratePDF()
        {
            Font helveticaBold16 = new Font(Font.HELVETICA, 16, Font.BOLD);
            Font helveticaBold42 = new Font(Font.HELVETICA, 42, Font.BOLD);
            Font helvetica11     = new Font(Font.HELVETICA, 11, Font.NORMAL);
            Font helvetica7      = new Font(Font.HELVETICA, 7, Font.NORMAL);
            Font helveticaBold12 = new Font(Font.HELVETICA, 12, Font.BOLD);
            Font helvetica12     = new Font(Font.HELVETICA, 12, Font.NORMAL);
            Font courier         = new Font(Font.COURIER, 38, Font.NORMAL, new BaseColor(119, 136, 153));
            Font courierBold     = new Font(Font.COURIER, 11, Font.BOLD);

            #endregion
            #region Initialize document and filepath
            // create a document object
            var doc = new Document(PageSize.A4); //define page size
            //get the current directory
            //get PdfWriter object

            // using (var fileStream = new FileStream(path + Path.DirectorySeparatorChar + "faktura.pdf", FileMode.Create))
            using (var fileStream = new MemoryStream())

            {
                PdfWriter.GetInstance(doc, fileStream);



                #endregion
                #region Opening document for writing and creation of upper table
                doc.Open();                             //open the document for writing
                PdfPTable logoTable = new PdfPTable(1); //Upper table with logo.
                logoTable.DefaultCell.FixedHeight         = 90;
                logoTable.HorizontalAlignment             = 1;
                logoTable.DefaultCell.HorizontalAlignment = 1;
                logoTable.DefaultCell.BorderWidth         = 0;

                Image logo;
                if (LogoPath != null)
                {
                    logo = Image.GetInstance(LogoPath);
                    logoTable.AddCell(logo);
                }
                else
                {
                    logoTable.AddCell("");
                }

                logoTable.SpacingAfter = 30;
                #endregion
                #region Second table with customer specifications
                //table with customer in upper right corner
                PdfPTable customerTable = new PdfPTable(1);
                customerTable.WidthPercentage = 100;
                PdfPCell customerCell = new PdfPCell(new Phrase(Model.Customer.Adress.ToString()));
                customerCell.BorderWidth         = 0;
                customerCell.HorizontalAlignment = 2;
                customerTable.AddCell(customerCell);
                #endregion
                #region third table with headlined invoice number
                //table with text headline and invoice number
                PdfPTable inVoiceNumber = new PdfPTable(1);
                inVoiceNumber.WidthPercentage = 100;
                PdfPCell inVoiceCell = new PdfPCell(new Phrase(invoiceGloss + " " + Model.InvoiceNumber, helveticaBold16));
                inVoiceCell.BorderWidth       = 0;
                inVoiceCell.VerticalAlignment = 0;
                inVoiceCell.BorderWidthBottom = 1;
                inVoiceCell.FixedHeight       = 30;
                inVoiceNumber.AddCell(inVoiceCell);
                #endregion
                #region table with invoicenumbers and dates
                //Table with invoicenumber and dates
                PdfPTable invoiceInformation       = new PdfPTable(2);
                float[]   invoiceInformationWidths = new float[] { 1f, 2f }; //Sets the width to culumns in relation to eachother
                invoiceInformation.SetWidths(invoiceInformationWidths);
                invoiceInformation.SpacingBefore           = 20;
                invoiceInformation.WidthPercentage         = 100;
                invoiceInformation.DefaultCell.BorderWidth = 0;
                invoiceInformation.AddCell(new Phrase(invoiceNumberGloss, helvetica12));
                invoiceInformation.AddCell(new Phrase(Model.InvoiceNumber.ToString(), helvetica12));
                invoiceInformation.AddCell(new Phrase(dateGloss, helvetica12));
                invoiceInformation.AddCell(new Phrase(Model.Date.ToString("yyyy-mm-dd"), helvetica12));
                invoiceInformation.AddCell(new Phrase(expirationDateGloss, helvetica12));
                invoiceInformation.AddCell(new Phrase(Model.Date.AddDays(Model.PaymentPeriod).ToString("yyyy-mm-dd"), helvetica12));
                invoiceInformation.SpacingAfter = 50;
                #endregion
                #region Table with services specifications headlines and the specifications
                //Table with the specifcations of services and cost
                PdfPTable MasterServiceTable = new PdfPTable(1); //Servicetables goes in this to be fixed size.
                MasterServiceTable.DefaultCell.MinimumHeight     = 80;
                MasterServiceTable.WidthPercentage               = 100;
                MasterServiceTable.DefaultCell.FixedHeight       = 160;
                MasterServiceTable.DefaultCell.VerticalAlignment = 2;
                MasterServiceTable.DefaultCell.BorderWidth       = 0;
                PdfPTable servicesTable = new PdfPTable(4);

                servicesTable.SpacingBefore = 5;

                servicesTable.WidthPercentage = 100;
                float[] widths = new float[] { 3f, 1f, 1f, 1f }; //Sets the width to culumns in relation to eachother
                servicesTable.SetWidths(widths);
                servicesTable.DefaultCell.BorderWidth = 0;
                PdfPCell servicesDescription = new PdfPCell(new Phrase(specifictionGloss, helveticaBold16));
                servicesDescription.BorderWidth       = 0;
                servicesDescription.BorderWidthBottom = 1;
                servicesDescription.FixedHeight       = 30;
                PdfPCell amountOfHours = new PdfPCell(new Phrase(amountGloss, helvetica12));
                amountOfHours.BorderWidth       = 0;
                amountOfHours.BorderWidthBottom = 1;
                PdfPCell pricePerHour = new PdfPCell(new Phrase(priceGloss, helvetica12));
                pricePerHour.BorderWidth       = 0;
                pricePerHour.BorderWidthBottom = 1;
                PdfPCell subTotal = new PdfPCell(new Phrase(sumGloss, helvetica12));
                subTotal.BorderWidth       = 0;;
                subTotal.BorderWidthBottom = 1;

                servicesTable.AddCell(servicesDescription);
                servicesTable.AddCell(amountOfHours);
                servicesTable.AddCell(pricePerHour);
                servicesTable.AddCell(subTotal);

                foreach (var service in Model.Service)
                {
                    servicesDescription             = new PdfPCell(new Phrase(service.Label, helvetica12));
                    servicesDescription.BorderWidth = 0;
                    amountOfHours             = new PdfPCell(new Phrase(service.Amount.ToString(), helvetica12));
                    amountOfHours.BorderWidth = 0;
                    pricePerHour = new PdfPCell(new Phrase(service.Price.ToString("C",
                                                                                  new CultureInfo(CultureType)), helvetica12));
                    pricePerHour.BorderWidth = 0;
                    subTotal = new PdfPCell(new Phrase(service.ServiceTotalWithoutVat.ToString("C",
                                                                                               new CultureInfo(CultureType)), helvetica12));
                    subTotal.BorderWidth = 0;
                    servicesTable.AddCell(servicesDescription);
                    servicesTable.AddCell(amountOfHours);
                    servicesTable.AddCell(pricePerHour);
                    servicesTable.AddCell(subTotal);
                }
                MasterServiceTable.AddCell(servicesTable);
                #endregion
                #region Table with totals and bank info.
                //Table with totals and the bank account information
                PdfPTable accountInfoAndtotalTable = new PdfPTable(2);
                accountInfoAndtotalTable.SpacingBefore           = 80;
                accountInfoAndtotalTable.SpacingAfter            = 20;
                accountInfoAndtotalTable.WidthPercentage         = 100;
                accountInfoAndtotalTable.DefaultCell.BorderWidth = 0;
                accountInfoAndtotalTable.DefaultCell.FixedHeight = 120;


                PdfPTable subTableLeft = new PdfPTable(2);
                subTableLeft.DefaultCell.BorderWidth = 0;
                float[] subTableLeftWidths = new float[] { 2f, 5f };
                subTableLeft.SetWidths(subTableLeftWidths);
                subTableLeft.AddCell(new Phrase(
                                         Environment.NewLine + Environment.NewLine + Environment.NewLine + giroGloss, helvetica11));
                subTableLeft.AddCell(new Phrase(
                                         Environment.NewLine + Environment.NewLine + Environment.NewLine
                                         + Model.User.Giro, helvetica11));
                subTableLeft.AddCell(new Phrase(bankAccountGloss, helvetica11));
                subTableLeft.AddCell(new Phrase(Model.User.BankAccount, helvetica11));
                subTableLeft.AddCell(new Phrase(ibanGloss, helvetica11));
                subTableLeft.AddCell(new Phrase(Model.User.Iban, helvetica11));
                subTableLeft.AddCell(new Phrase(bicSwiftGloss, helvetica11));
                subTableLeft.AddCell(new Phrase(Model.User.BicSwift, helvetica11));

                PdfPTable subTableRight = new PdfPTable(2);
                subTableRight.DefaultCell.BackgroundColor     = new BaseColor(229, 229, 229);
                subTableRight.DefaultCell.BorderWidth         = 0;
                subTableRight.DefaultCell.HorizontalAlignment = 0;
                subTableRight.AddCell((new Phrase(
                                           Environment.NewLine + Environment.NewLine + "    " + netGloss, helvetica12)));
                subTableRight.AddCell(new Phrase(
                                          Environment.NewLine + Environment.NewLine + Model.ServicesTotal().ToString("C",
                                                                                                                     new CultureInfo(CultureType)), helvetica12));//högerställ dessa fält?
                subTableRight.AddCell(new Phrase("    " + vatGloss, helvetica12));
                subTableRight.AddCell(new Phrase(Model.Vatamount.ToString("C",
                                                                          new CultureInfo(CultureType)), helvetica12));
                subTableRight.AddCell(new Phrase(
                                          Environment.NewLine + "   " + totalGloss, helveticaBold16));
                subTableRight.AddCell(new Phrase(Environment.NewLine + Model.Total.ToString("C",
                                                                                            new CultureInfo(CultureType)), helveticaBold16));
                accountInfoAndtotalTable.AddCell(subTableLeft);
                accountInfoAndtotalTable.AddCell(subTableRight);
                #endregion
                #region Table with bottom border, different company info.
                //The bottom border with contact information
                PdfPTable bottomBorder = new PdfPTable(3);
                bottomBorder.DefaultCell.BorderWidth    = 0;
                bottomBorder.DefaultCell.BorderWidthTop = 1;
                bottomBorder.WidthPercentage            = 100;
                bottomBorder.AddCell(new Phrase(Environment.NewLine + Model.User.Street + Environment.NewLine + Model.User.PostalAddress +
                                                " " + Model.User.City, helvetica12));
                bottomBorder.AddCell(new Phrase(Environment.NewLine + Model.User.Phone, helvetica12));
                bottomBorder.AddCell(new Phrase(Environment.NewLine + "Some Info", helvetica12));
                #endregion
                #region Assembly of document and closure,
                //Assembly of tables on document
                doc.Add(logoTable);
                doc.Add(customerTable);
                doc.Add(inVoiceNumber);
                doc.Add(invoiceInformation);
                doc.Add(MasterServiceTable);
                doc.Add(accountInfoAndtotalTable);
                doc.Add(bottomBorder);

                //close the document
                doc.Close();
                // fileStream.Dispose();
                fileStream.Flush(); //Always catches me out
                fileStream.Position = 0;
                byte[] file = fileStream.ToArray();
                return(file);
            }
            //view the result pdf file
            // System.Diagnostics.Process.Start(path + Path.DirectorySeparatorChar + "faktura_" + Model.InvoiceNumber + ".pdf");
            #endregion
        }
    protected void btnfactura_Click(object sender, EventArgs e)
    {
        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            Document  document = new Document(PageSize.A4, 30, 55, 70, 10);
            PdfWriter writer   = PdfWriter.GetInstance(document, memoryStream);
            document.Open();

            //Chunk chunk = new Chunk("Comprobante generado ");
            //document.Add(chunk);

            //titulo
            BaseFont  bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntHead  = new Font(bfntHead, 20, 1, BaseColor.BLACK);
            Paragraph prgHead  = new Paragraph();
            prgHead.SpacingBefore = 30;
            prgHead.SpacingAfter  = 5;
            prgHead.Alignment     = Element.ALIGN_CENTER;
            prgHead.Add(new Chunk("COMPROBANTE GENERADO", fntHead));
            document.Add(prgHead);

            //Paragraph para = new Paragraph(txtNombres.Text + " " + txtapellido.Text);
            ////document.Add(para);

            //RUC
            Font      fntRUC = new Font(bfntHead, 12, 1, BaseColor.BLACK);
            Paragraph prgRUC = new Paragraph();
            prgRUC.SpacingBefore = 30;
            prgRUC.SpacingAfter  = 5;
            prgRUC.Alignment     = Element.ALIGN_RIGHT;
            prgRUC.Add(new Chunk("R.U.C. 10007456085", fntHead));
            document.Add(prgRUC);

            //Num comprobante
            Font      fntNum = new Font(bfntHead, 8, 2, BaseColor.BLACK);
            Paragraph prgNum = new Paragraph();
            prgNum.SpacingBefore = 10;
            prgNum.SpacingAfter  = 5;
            prgNum.Alignment     = Element.ALIGN_RIGHT;
            prgNum.Add(new Chunk("N° comprobante: 000 - 000020", fntHead));
            document.Add(prgNum);

            //nombre del cliente
            Font      fntname = new Font(bfntHead, 16, 1, BaseColor.BLACK);
            Paragraph prgname = new Paragraph();
            prgname.SpacingBefore = 30;
            prgname.SpacingAfter  = 5;
            prgname.Add(new Chunk("Sr(a): " + txtNombres.Text + " " + txtapellido.Text, fntHead));
            document.Add(prgname);

            //Cp, telefono,fecha y hora
            string    text      = "Lima Pe, CP 06";
            string    text1     = Environment.NewLine + "Telefono : (213) 484 - 6829";
            string    time      = Environment.NewLine + "Fecha de emision: " + Convert.ToString(DateTime.Now.ToShortDateString());
            string    direc     = Environment.NewLine + "San Juan de Miraflores --- 1025  ";
            Paragraph paragraph = new Paragraph();
            paragraph.SpacingBefore = 5;
            paragraph.SpacingAfter  = 5;
            paragraph.Alignment     = Element.ALIGN_LEFT;
            paragraph.Font          = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12f, BaseColor.BLACK);
            paragraph.Add(text);
            paragraph.Add(text1);
            paragraph.Add(time);
            document.Add(paragraph);

            //line separadora
            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
            document.Add(line);

            //line
            document.Add(new Chunk("\n", fntHead));

            //contenido
            BaseFont  bfnCont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntCont = new Font(bfntHead, 14, 1, BaseColor.BLACK);
            Paragraph prgCont = new Paragraph();
            prgCont.SpacingBefore = 10;
            prgCont.SpacingAfter  = 15;
            prgCont.Alignment     = Element.ALIGN_CENTER;
            prgCont.Add(new Chunk("Contenido", fntHead));
            document.Add(prgCont);


            //sesion table gv2
            dt = (DataTable)ViewState["Records"];
            //write table
            PdfPTable table = new PdfPTable(dt.Columns.Count);

            //table header
            BaseFont BsColumnHeader  = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader = new Font(BsColumnHeader, 10, 1, BaseColor.BLACK);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                cell.AddElement(new Chunk(dt.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    table.AddCell(dt.Rows[i][j].ToString());
                }
            }
            document.Add(table);

            //import total
            //Font fntImp = new Font(bfntHead, 4, 1, BaseColor.BLACK);
            Paragraph prgImp = new Paragraph();
            prgImp.SpacingBefore   = 5;
            prgImp.SpacingAfter    = 5;
            prgImp.IndentationLeft = 245;
            //prgImp.Alignment = Element.ALIGN_RIGHT;
            prgImp.Add(new Chunk("Importe total: S/." + txtimporttot.Text, fntHead));
            document.Add(prgImp);



            document.Close();
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            Response.Clear();
            Response.ContentType = "application/pdf";
            //string pdfName = "User";
            Response.AddHeader("Content-Disposition", "attachment; filename=Boleta" + txtIdentificadorUsuario.Text + ".pdf");
            Response.ContentType = "application/pdf";
            Response.Buffer      = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
            Response.Close();
            writer.Close();
        }
    }