Dispose() public method

public Dispose ( ) : void
return void
Example #1
0
        public ActionResult Report()
        {
            var orders = from Order in db.Orders select new { id = Order.Order_id, cost = Order.Total_price };

            if (orders == null)
            {
                return(HttpNotFound());
            }
            var costs = from Order in db.Orders select Order.Total_price;

            if (costs == null)
            {
                return(HttpNotFound());
            }
            var    totalcost  = costs.Sum();
            string reportname = @"C:\Users\hone\Desktop\report" + DateTime.Now.ToShortDateString() + ".pdf";

            iTextSharp.text.Document report = new iTextSharp.text.Document(PageSize.A4);//отчет
            string ttf      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
            var    baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var    font     = new Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

            try
            {
                PdfWriter.GetInstance(report, new FileStream(reportname, FileMode.CreateNew));
                report.Open();
                foreach (var order in orders)
                {
                    report.Add(new Paragraph("Заказ №:" + order.id, font));
                    report.Add(new Paragraph("Общая стоимость:" + order.cost, font));
                    report.Add(new Paragraph(" ", font));
                }
                report.Add(new Paragraph("Стоимость всех заказов: " + totalcost, font));
                report.Close();
                report.Dispose();
                // отправка билета в принтер(в комментариях)
                //  PrintDocument printDoc = new PrintDocument();
                //printDoc.DocumentName = filename;
                //printDoc.Print();
                //printDoc.Dispose();
                // удаление билета, чтобы не занимал память, и еще не придумал как сохранять билеты с разными именами
                // System.IO.File.Delete(filename);
            }

            catch (Exception ex)
            {
            }
            finally
            {
                report.Close();
                report.Dispose();
            }
            return(File(reportname, "MIME"));
        }
Example #2
0
        public ActionResult Cheque(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Order order = db.Orders.Find(id);

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

            string chequename = @"C:\Users\hone\Desktop\cheque" + DateTime.Now.ToShortDateString() + ".pdf";

            iTextSharp.text.Document cheque = new iTextSharp.text.Document(PageSize.A4);//отчет
            string ttf      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
            var    baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var    font     = new Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

            try
            {
                PdfWriter.GetInstance(cheque, new FileStream(chequename, FileMode.CreateNew));
                cheque.Open();
                cheque.Add(new Paragraph("Номер заказа: " + order.Order_id, font));
                cheque.Add(new Paragraph("Наименование товара: " + order.Mebel.Mebel_name + " " + order.Material.Material_name, font));
                cheque.Add(new Paragraph("Цена товара: " + order.Price_for_one, font));
                cheque.Add(new Paragraph("Количество товара: " + order.Amount, font));
                cheque.Add(new Paragraph("Общая стоимость: " + order.Total_price, font));
                cheque.Add(new Paragraph("Клиент: " + order.Client, font));
                cheque.Close();
                cheque.Dispose();
                // отправка билета в принтер(в комментариях)
                //  PrintDocument printDoc = new PrintDocument();
                //printDoc.DocumentName = filename;
                //printDoc.Print();
                //printDoc.Dispose();
                // удаление билета, чтобы не занимал память, и еще не придумал как сохранять билеты с разными именами
                // System.IO.File.Delete(filename);
            }

            catch (Exception ex)
            {
            }
            finally
            {
                cheque.Close();
                cheque.Dispose();
            }
            return(File(chequename, "MIME"));
        }
Example #3
0
        public ActionResult GetImagePdf(string ID)
        {
            it.Font      font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10);
            MemoryStream ms   = new MemoryStream();

            it.Document document = new it.Document();
            PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new it.Paragraph("Yes Master!"));
            document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font));
            List <string> imageStringList = GetImageString(ID, 1);

            foreach (var item in imageStringList)
            {
                try
                {
                    //如果传过来的是Base64
                    //it.Image image = it.Image.GetInstance(base64ToPic(item), System.Drawing.Imaging.ImageFormat.Jpeg);
                    //如果传过来的是地址
                    it.Image image = it.Image.GetInstance(Server.MapPath("~") + "/pdfimage/" + item + ".jpg");

                    image.Alignment = it.Image.ALIGN_LEFT;
                    image.ScalePercent(30);
                    document.Add(image);
                }
                catch (Exception e)
                {
                    document.Add(new it.Paragraph("图片" + item + "不存在"));
                }
            }
            document.Close();
            document.Dispose();
            return(File(ms.ToArray(), "application/pdf", "ceshi.pdf"));
        }
Example #4
0
        /// <summary>
        /// Create a new PDF text document.
        /// </summary>
        /// <param name="pdf">The PDF file stream.</param>
        /// <param name="text">The text to add to the document.</param>
        /// <param name="font">The text font to create.</param>
        /// <param name="password">The password used to protect the document.</param>
        /// <exception cref="System.Exception"></exception>
        public void CreateText(Stream pdf, string text, Nequeo.Drawing.Pdf.Font font, string password)
        {
            iTextSharp.text.Document document = null;

            try
            {
                // Create the document.
                document = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfAWriter.GetInstance(document, pdf);
                pdfWriter.SetEncryption(iTextSharp.text.pdf.PdfWriter.ENCRYPTION_AES_256, password, password, 0);
                document.Open();

                // Add the text.
                iTextSharp.text.Font fontText = font.GetFont();
                document.Add(new iTextSharp.text.Paragraph(text, fontText));

                // Close the document.
                document.Close();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (document != null)
                {
                    document.Dispose();
                }
            }
        }
Example #5
0
        private PdfReader GetPdf(ICollection <byte[]> pages)
        {
            if (pages == null || pages.Count() == 0)
            {
                return(null);
            }

            MemoryStream streamOut = new MemoryStream();
            PdfReader    reader    = null;

            using (its.Document doc = new its.Document(iTextSharp.text.PageSize.A4, -70, -70, 0, 0))
            {
                PdfWriter.GetInstance(doc, streamOut);
                doc.Open();

                foreach (byte[] page in pages)
                {
                    iTextSharp.text.Image image = its.Image.GetInstance(page);
                    doc.NewPage();
                    PdfPTable table = new PdfPTable(1);
                    table.AddCell(new PdfPCell(image));
                    doc.Add(table);
                }
                doc.Close();
                doc.Dispose();
                reader = new PdfReader(streamOut.ToArray());
            }
            return(reader);
        }
 /// <summary>
 /// 关闭PDF文档流
 /// </summary>
 /// <param name="doc"></param>
 public void DisposePdf(Document doc)
 {
     if (doc.IsOpen())
     {
         doc.Close();
     }
     doc.Dispose();
 }
Example #7
0
        public ActionResult GetTablePdf()
        {
            it.Font      font = new it.Font(BaseFont.CreateFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10);
            MemoryStream ms   = new MemoryStream();

            it.Document document = new it.Document();
            PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new it.Paragraph("Yes Master!"));
            document.Add(new it.Paragraph("其疾如风,其徐如林,侵掠如火,不动如山,难知如阴,动如雷震", font));
            List <Person> personList = new List <Person>();

            personList.Add(new Person {
                Name = "wlz", Address = "1111"
            });
            personList.Add(new Person {
                Name = "xiaoming", Address = "1112"
            });
            personList.Add(new Person {
                Name = "xiaohong", Address = "1113"
            });
            List <NameToColName> nameList = new List <NameToColName>();

            nameList.Add(new NameToColName {
                ModelName = "Name", ColName = "姓名"
            });
            nameList.Add(new NameToColName {
                ModelName = "Address", ColName = "地址"
            });
            var       properties = personList.First().GetType().GetProperties() as System.Reflection.PropertyInfo[];
            PdfPTable nameTable  = new PdfPTable(properties.Length);

            //创建表头
            for (int i = 0; i < properties.Length; i++)
            {
                var    property = properties[i];
                string colName  = (nameList.Where(p => p.ModelName == property.Name).ToList())[0].ColName;
                nameTable.AddCell(new it.Phrase(colName, font));//注意加上中文字体
            }

            personList.ForEach(item =>
            {
                for (int i = 0; i < properties.Length; i++)
                {
                    var property = properties[i];
                    nameTable.AddCell(new it.Phrase(property.GetValue(item, null).ToString(), font));
                }
            });
            document.Add(nameTable);

            document.Close();
            document.Dispose();
            return(File(ms.ToArray(), "application/pdf", "TableDemo.pdf"));
        }
        public ActionResult MergeFiless(IFormFile[] files)
        {
            ViewBag.Message = string.Empty;
            if (files.Length == 0)
            {
                ViewBag.Message = "Select some file before you click merge.";
                return(View("MergeFiles"));
            }
            byte[] password = Encoding.ASCII.GetBytes("123456");

            try
            {
                for (int i = 0; i < files.Length; i++)
                {
                    Stream fileStream = files[i].OpenReadStream();
                    var    mStreamer  = new MemoryStream();

                    mStreamer.SetLength(fileStream.Length);
                    fileStream.Read(mStreamer.GetBuffer(), 0, (int)fileStream.Length);
                    mStreamer.Seek(0, SeekOrigin.Begin);
                    PdfReader pdfReader = new PdfReader(mStreamer, password);
                    readerListpdf.Add(pdfReader);
                    mStreamer.Flush();
                    mStreamer.Dispose();
                }

                Document ManagementReportDoc = new iTextSharp.text.Document(PageSize.A4, 15f, 15f, 75f, 75f);

                FileStream file = new FileStream(outPutFilePath, FileMode.OpenOrCreate);

                PdfWriter writer = PdfWriter.GetInstance(ManagementReportDoc, file); // PdfWriter.GetInstance(ManagementReportDoc, file);

                ManagementReportDoc.Open();

                foreach (PdfReader reader in readerListpdf)
                {
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        ManagementReportDoc.Add(iTextSharp.text.Image.GetInstance(page));
                    }
                }
                ManagementReportDoc.Close();
                writer.Dispose();
                ManagementReportDoc.Dispose();
                ViewBag.fileDownload = outPutFilePath;
                return(View());
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                return(View(ex.Message));
            }
        }
Example #9
0
        /// <summary>
        /// 导出数据到pdf文件
        /// </summary>
        /// <param name="dt">要导出的数据表</param>
        /// <param name="path">文件路径</param>
        public static void ExportToPDF(System.Data.DataTable dt, string path)
        {
            try
            {
                if (dt.Columns.Count == 1)
                {
                    dt.Columns.Add("  ");
                }
                float wh = dt.Columns.Count * 72.0f;
                iTextSharp.text.Rectangle rec      = new iTextSharp.text.Rectangle(0.0f, 0.0f, wh, wh);
                iTextSharp.text.Document  document = new iTextSharp.text.Document(rec, 36.0f, 36.0f, 36.0f, 36.0f);
                System.IO.FileStream      fs       = new System.IO.FileStream(path, FileMode.Create);
                PdfWriter.GetInstance(document, fs); //在当前路径下创一个文件  
                document.Open();
                BaseFont bfChinese = null;
                if (File.Exists(@"C:\Windows\Fonts\simsun.ttf"))
                {
                    bfChinese = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                }
                else if (File.Exists(@"simsun.ttf"))
                {
                    bfChinese = BaseFont.CreateFont(@"simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                }
                iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                PdfPTable            table       = new PdfPTable(dt.Columns.Count);

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

                try
                {
                    //表格相对空白宽度占比
                    table.WidthPercentage = 100.0f;
                    document.Add(table);   //添加table
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                document.Close();
                document.Dispose();
            }
            catch (DocumentException ex)
            {
                throw ex;
            }
        }
Example #10
0
        public static List <byte[]> Split(PdfReader reader)
        {
            int p = 0;

            Document document;

            var data = new List <byte[]>();


            for (p = 1; p <= reader.NumberOfPages; p++)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    document = new iTextSharp.text.Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_2);
                    writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
                    writer.SetFullCompression();
                    document.SetPageSize(reader.GetPageSize(p));
                    document.NewPage();
                    document.Open();
                    document.AddDocListener(writer);
                    PdfContentByte  cb         = writer.DirectContent;
                    PdfImportedPage pageImport = writer.GetImportedPage(reader, p);
                    int             rot        = reader.GetPageRotation(p);
                    if (rot == 90 || rot == 270)
                    {
                        cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                    }
                    else
                    {
                        cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                    }
                    document.Close();
                    document.Dispose();
                    //File.WriteAllBytes(DestinationFolder + "/" + p + ".pdf", memoryStream.ToArray());

                    data.Add(memoryStream.ToArray());

                    if (OnSplitProcess != null)
                    {
                        OnSplitProcess(p, null);
                    }
                }
            }
            reader.Close();
            reader.Dispose();

            return(data);
        }
Example #11
0
        /// <summary>
        /// 自动回收
        /// </summary>
        public override void Dispose()
        {
            if (_document != null)
            {
                _document.Dispose();
                _document = null;
            }

            if (_writer != null)
            {
                _writer.Dispose();
            }

            if (File.Exists(_tempFileName))
            {
                File.Delete(_tempFileName);
            }
            base.Dispose();
        }
Example #12
0
        public void Close()
        {
            if (pdfDocument != null)
            {
                pdfDocument.Close();
                pdfDocument.Dispose();
                writer.Close();
                writer.Dispose();
                stream.Close();
                stream.Dispose();
                pdfDocument = null;
                writer      = null;
                pdfDocument = null;
            }

            if (reader != null)
            {
                reader.Close();
            }
        }
Example #13
0
        }//print

        #region private Func


        /// <summary> 合併PDF檔 </summary>
        /// <param name="fileList">欲合併PDF檔之List(byte[])(一筆以上)</param>
        /// <returns>byte[]</returns>
        private byte[] MergePDFFiles(List <byte[]> fileList)
        {
            string actionName = "MergePDFFiles";

            byte[]    result = null;
            PdfReader reader = null;

            iTextSharp.text.Document document = new iTextSharp.text.Document();
            try
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    //creating a sample Document
                    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms);
                    document.Open();
                    PdfContentByte  cb = writer.DirectContent;
                    PdfImportedPage newPage;
                    foreach (byte[] file in fileList)
                    {
                        reader = new PdfReader(file);
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, 0);
                        }
                    }
                    document.Close();
                    document.Dispose();
                    reader.Close();
                    reader.Dispose();
                    result = ms.ToArray();
                }
            }
            catch (Exception ex)
            {
                LogTool.SaveLogMessage(ex, actionName, this.csName);
            }
            return(result);
        }
Example #14
0
        public override void SaveDocument()
        {
            base.SaveDocument();
            PdfWriter wri = PdfWriter.GetInstance(pdf, File.Create(Path.Combine(OutputFolder, FileName + ".pdf")));

            pdf.Open();

            if (!string.IsNullOrEmpty(lnParameters.urlCover))
            {
                AddCover();
            }

            foreach (PdfChapter pdfChapter in pdfChapters)
            {
                pdf.NewPage();
                wri.PageEvent = null;
                wri.PageEvent = new PdfFooterEvent(pdfChapter.Title.Content);
                pdf.Add(pdfChapter);
            }

            pdf.Close();
            pdf.Dispose();
        }
Example #15
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    if (m_doc != null)
                    {
                        m_doc.Dispose();
                    }
                    if (m_stream != null)
                    {
                        m_stream.Dispose();
                    }
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }
Example #16
0
        public void MergePdf(string outPutFilePath, params string[] filesPath)
        {
            List <PdfReader> readerList = new List <PdfReader>();
            PdfReader        pdfReader  = null;

            foreach (string filePath in filesPath)
            {
                pdfReader = new PdfReader(filePath);
                readerList.Add(pdfReader);
            }

            //Define a new output document and its size, type
            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 0, 0, 0, 0);
            //Create blank output pdf file and get the stream to write on it.
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outPutFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite));

            document.Open();

            foreach (PdfReader reader in readerList)
            {
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    document.Add(iTextSharp.text.Image.GetInstance(page));
                }
            }
            document.Close();
            document.Dispose();
            foreach (PdfReader pdfRead in readerList)
            {
                pdfRead.Close();
                pdfRead.Dispose();
            }
            pdfReader.Dispose();
            writer.Dispose();
        }
        /// <summary>
        /// ExecuteResult
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = "application/pdf";

            if (Download)
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);

            Html = RenderRazorViewToString(context);

            Format(context.HttpContext);

            using (var document = new Document(Settings.PageSize, Settings.Margin.Left, Settings.Margin.Right, Settings.Margin.Top, Settings.Margin.Bottom))
            {
                var memoryStream = new MemoryStream();
                TextReader textReader = new StringReader(Html);
                var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
                var htmlPipelineContext = new HtmlPipelineContext(null);
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);

                document.Open();

                FontFactory.RegisterDirectories();

                htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                foreach (var styleSheet in StyleSheets)
                {
                    cssResolver.AddCssFile(context.HttpContext.Server.MapPath(styleSheet), true);
                }

                var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));
                var worker = new XMLWorker(pipeline, true);
                var xmlParse = new XMLParser(true, worker);

                xmlParse.Parse(textReader);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                context.HttpContext.Response.BinaryWrite(memoryStream.ToArray());
            }

            context.HttpContext.Response.End();
            context.HttpContext.Response.Flush();
        }
        private void SplitWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            object[] args = (object[])e.Argument;
            PdfFile pdfFile = (PdfFile)args[0];
            PageRangeParser pageRangeParser = (PageRangeParser)args[1];
            string destinationPath = (string)args[2];
            bool overwriteFile = (bool)args[3];
            FileStream outFileStream = null;
            Document destinationDoc = null;
            PdfCopy pdfCopy = null;
            int skippedFiles = 0;
            string exportFileName = string.Empty;
            string errorMsg = string.Empty;
            int exportFileCnt = 0, totalNumberOPages = 0, pageCnt = 0;
            EasySplitAndMergePdf.Helper.PageRange[] pageRanges = null;

            if (pageRangeParser.TryParse(out pageRanges) != Define.Success)
            {
                errorMsg = "An error occurred while parsing PDF page ranges" + pageRangeParser.ErrorMsg;
            }
            else if ((totalNumberOPages = pageRanges.Sum(range => range.PageCount)) < 1)
            {
                errorMsg = "The number of PDF pages to extract from source file is zero.";
            }
            else
            {
                pdfFile.Reader.RemoveUnusedObjects();

                while (exportFileCnt < pageRanges.Length && !splitBackgroundWorker.CancellationPending)
                {
                    exportFileName = destinationPath + (exportFileCnt + 1).ToString("D4") + ".pdf";
                    if (FileHelpers.FileIsAvailable(exportFileName, overwriteFile, out outFileStream, out errorMsg) == Define.Success)
                    {
                        destinationDoc = new Document();
                        pdfCopy = new PdfCopy(destinationDoc, outFileStream);
                        destinationDoc.Open();

                        splitBackgroundWorker.ReportProgress(pageCnt * 100 / totalNumberOPages,
                            string.Format("Creating and processing PDF file: {0}", exportFileName));

                        if (pageRanges[exportFileCnt].Pages != null)
                        {
                            int pageArrayIndex = 0;
                            while (pageArrayIndex < pageRanges[exportFileCnt].Pages.Length &&
                                !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageRanges[exportFileCnt].Pages[pageArrayIndex]));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageRanges[exportFileCnt].Pages[pageArrayIndex]));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageArrayIndex++;
                            }
                        }
                        else if (pageRanges[exportFileCnt].PageFrom <= pageRanges[exportFileCnt].PageTo)
                        {
                            int pageNumber = pageRanges[exportFileCnt].PageFrom;
                            while (pageNumber <= pageRanges[exportFileCnt].PageTo &&
                                !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageNumber));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageNumber));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageNumber++;
                            }
                        }
                        else if (pageRanges[exportFileCnt].PageFrom > pageRanges[exportFileCnt].PageTo)
                        {
                            int pageNumber = pageRanges[exportFileCnt].PageFrom;
                            while (pageNumber >= pageRanges[exportFileCnt].PageTo &&
                                !splitBackgroundWorker.CancellationPending)
                            {
                                destinationDoc.SetPageSize(pdfFile.Reader.GetPageSizeWithRotation(pageNumber));
                                destinationDoc.NewPage();
                                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfFile.Reader, pageNumber));
                                splitBackgroundWorker.ReportProgress(++pageCnt * 100 / totalNumberOPages);
                                pageNumber--;
                            }
                        }

                        //Exception on document.Close() when doc is empty
                        //if (pages.Count == 0) { throw new IOException("The document has no pages.") };
                        //When canceling pages.Count could be zero therefore skip cleanup.
                        if (destinationDoc != null &&
                            !splitBackgroundWorker.CancellationPending)
                        {
                            destinationDoc.Close();
                            destinationDoc.Dispose();
                            destinationDoc = null;
                        }

                        if (pdfCopy != null &&
                            !splitBackgroundWorker.CancellationPending)
                        {
                            pdfCopy.Close();
                            pdfCopy.Dispose();
                            pdfCopy = null;
                        }

                        if (outFileStream != null)
                        {
                            outFileStream.Close();
                            outFileStream.Dispose();
                            outFileStream = null;
                        }
                    }
                    else
                    {
                        skippedFiles++;
                        Debug.WriteLine(string.Format("File: {0}, error: {1}", exportFileName, errorMsg));
                    }
                    exportFileCnt++;
                }
            }

            if (string.IsNullOrEmpty(errorMsg) &&
                exportFileCnt == pageRanges.Length &&
                skippedFiles == 0)
            {
                errorMsg = string.Format("Successfully created {0} PDF export files.", pageRanges.Length);
            }
            else if (skippedFiles > 0)
            {
                errorMsg = string.Format("Created {0} PDF export files, skipped {1} PDF files.",
                    pageRanges.Length - skippedFiles, skippedFiles);
            }

            if (splitBackgroundWorker.CancellationPending)
            {
                e.Cancel = true;
            }

            e.Result = errorMsg;
        }
        private void runInDebugMode()
        {
            PdfDoc = new Document(DocumentSettings.GetPageSizeAndColor(_pdfRptData.DocumentPreferences),
                        _pdfRptData.DocumentPreferences.PagePreferences.Margins.Left,
                        _pdfRptData.DocumentPreferences.PagePreferences.Margins.Right,
                        _pdfRptData.DocumentPreferences.PagePreferences.Margins.Top,
                        _pdfRptData.DocumentPreferences.PagePreferences.Margins.Bottom);

            createPdf();
            PdfDoc.Dispose();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)
                {
                    string tType = Request.Form["type"].ToString();
                    string tSvg = Request.Form["svg"].ToString();
                    string tFileName = Request.Form["filename"].ToString();
                    if (tFileName == "") tFileName = "chart";

                    MemoryStream data = new MemoryStream(Encoding.ASCII.GetBytes(tSvg));
                    MemoryStream stream = new MemoryStream();

                    switch (tType)
                    {
                        case "image/png":
                            tFileName += ".png";
                            SvgDocument.Open(data).Draw().Save(stream, ImageFormat.Png);
                            break;
                        case "image/jpeg":
                            tFileName += ".jpg";
                            SvgDocument.Open(data).Draw().Save(stream, ImageFormat.Jpeg);
                            break;
                        case "image/svg+xml":
                            tFileName += ".svg";
                            stream = data;
                            break;
                        case "application/pdf":
                            tFileName += ".pdf";

                            PdfWriter tWriter = null;
                            Document tDocumentPdf = null;
                            try
                            {
                                SvgDocument tSvgObj = SvgDocument.Open(data);

                                tSvgObj.Draw().Save(stream, ImageFormat.Png);

                                // Creating pdf document
                                tDocumentPdf = new Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));

                                // setting up margin to full screen image
                                tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);

                                // creating image
                                iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(stream.ToArray());
                                tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                                stream = new MemoryStream();

                                // create writer
                                tWriter = PdfWriter.GetInstance(tDocumentPdf, stream);

                                tDocumentPdf.Open();
                                tDocumentPdf.NewPage();
                                tDocumentPdf.Add(tGraph);
                                tDocumentPdf.CloseDocument();
                                tDocumentPdf.Close();
                            }
                            catch (Exception ex)
                            {
                                throw ex;

                            }
                            finally
                            {
                                tDocumentPdf.Close();
                                tDocumentPdf.Dispose();
                                tWriter.Close();
                                tWriter.Dispose();
                            }
                            break;
                    }

                    if (stream != null)
                    {
                        Response.ClearContent();
                        Response.ClearHeaders();
                        Response.ContentType = tType;
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName);
                        Response.BinaryWrite(stream.ToArray());
                        Response.End();
                    }
                }
            }
        }
Example #21
0
        public void NewBillPDF(String BillNO)
        {
            DAL.BillLayoutMaster Bill = null;
            IEnumerable<DAL.BillConsumption> Consumption = null;
            IEnumerable<DAL.BillFixchargesList> Fixcharges = null;
            IEnumerable<DAL.BiLLVatChargeList> Vatcharges = null;
            Bill = BAL.BillModel.GetBillHeader(BillNO);
            Consumption = BAL.BillModel.BillConsumptionRecordList(BillNO);
            Fixcharges = BAL.BillModel.BillFixedChargeConsumptionRecordList(BillNO);
            Vatcharges = BAL.BillModel.BillVarChargedList(BillNO);
            //------------------------------------------PDF download -----------------------------------------------------------------
            MemoryStream workStream = new MemoryStream();
            var document = new Document(PageSize.A4,10,10,10,10);
            //  var document = new Document();
            String PDFName = BillNO + ".pdf";

            // var filePath = Path.Combine(Server.MapPath("~/PdfContent/Bill"), PDFName);
            //  var output = new MemoryStream();
               // PdfWriter.GetInstance(document, workStream).CloseStream = false;
            //  PdfWriter.GetInstance(document, System.Web.HttpContext.Current.Response.OutputStream);

            //  var output = new FileStream(filePath, FileMode.Create);
            //var writer = PdfWriter.GetInstance(document, output);

            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, workStream);

            writer.PageEvent = new HeaderFooter(BillNO);

            try
            {

                document.Open();

                String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/BillTemplate.htm"));

                //---------------------------------style -------------------------------------------
                StyleSheet styles = new StyleSheet();
                // styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.COLOR, "left");
                styles.LoadStyle("maintable", "color", "#ff0000");
                styles.LoadStyle(HtmlTags.TABLE, HtmlTags.ALIGN, "center");
             //   styles.LoadTagStyle("#headerdiv", "padding-left", "50px");

                styles.LoadStyle("headerdiv", "align", "center");
                styles.LoadStyle("headerdiv", "color", "#ff0000");
                //--------------------------------End -style -------------------------------------------

                String clientLogo = String.Empty;
                // Replace the placeholders with the user-specified text
                //if (!(String.IsNullOrEmpty(Bill.CompanyLogo)) && (Bill.CompanyLogo != ""))
                //{

                //    clientLogo = "<img border='0' src='" + Server.MapPath("~/UserPicture/" + Bill.CompanyLogo) + "' width='190' height='46'>";
                //}
                //else
                //{
                //    clientLogo = "<img border='0' src='" + Server.MapPath("~/Images/logo.png") + "' width='190' height='46'>";
                //}
                contents = contents.Replace("[ClientImage]", clientLogo);
                contents = contents.Replace("[ConsumerName]", Bill.ConsumerName.Trim());
               // contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim());
                contents = contents.Replace("[ConsumerAddress]", Bill.ConsumerAddress);
                if (Bill.ConsumerAddress2 != null)
                {
                    contents = contents.Replace("[ConsumerAddress2]", "<br/>" + Bill.ConsumerAddress2);
                }
                else
                {
                    contents = contents.Replace("[ConsumerAddress2]", " ");
                }
                contents = contents.Replace("[ConsumerCity]", Bill.ConsumerCity);
                contents = contents.Replace("[ConsumerCountry]", Bill.ConsumerCounty);
                contents = contents.Replace("[ConsumerZipCode]", Bill.ConsumerZipCode);
                contents = contents.Replace("[ClientName]", Bill.Client);
                if (Bill.FixedBillNotice == "Yes")
                {
                    contents = contents.Replace("[FixedBillNote]", Bill.FixedBillNote);
                }
                else
                {
                    contents = contents.Replace("[FixedBillNote]", "");
                }
                contents = contents.Replace("[PropertyAddress]", Bill.PropertyAddress);
                contents = contents.Replace("[PaymentDate]", Bill.paymentDate);
               // contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                contents = contents.Replace("[BillFromDate]", Bill.BillFromDate);
                contents = contents.Replace("[BillToDate]", Bill.BillToDate);
                contents = contents.Replace("[previousBalance]", Bill.previousBalance != null ? Bill.previousBalance.ToString() : "");
                contents = contents.Replace("[EngergyList]", "");
                contents = contents.Replace("[NoofDays]", Bill.NoofDays);
                contents = contents.Replace("[Othercharges]", Bill.Othercharges.ToString());
                contents = contents.Replace("[NetAmount]", Bill.NetAmount != null ? Bill.NetAmount.ToString() : "");
                contents = contents.Replace("[VATNumber]", Bill.VATNumber);
                contents = contents.Replace("[VatAmount]", Bill.VatAmount != null ?    Bill.VatAmount.ToString() : "");
                contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
               // contents = contents.Replace("[paymentReceived]", Bill.paymentReceived != null ? Bill.paymentReceived.ToString() : "");

                contents = contents.Replace("[paymentReceived]", Bill.PaybleAmount != null ? Bill.PaybleAmount.ToString() : "");

              contents = contents.Replace("[DirectDebitAmount]", Bill.DirectDebitAmount != null ? Bill.DirectDebitAmount.ToString() : "");

                if(Bill.DirectDebitType ==1)
                {
                    contents = contents.Replace("[DirectDebitDate]", Bill.DirectDebitDate != null ? Bill.DirectDebitDate : "");
                }
                else
                {
                    contents = contents.Replace("[DirectDebitDate]", Bill.paymentDate != null ? Bill.paymentDate : "");
                }

                contents = contents.Replace("[NewBalance]", Bill.NewBalance != null ? Convert.ToString(Bill.previousBalance + Bill.GrossAmount) : "");
                contents = contents.Replace("[Client]", Bill.Client);
                contents = contents.Replace("[ClientAddress]", Bill.ClientAddress);
                if (Bill.ClientAddress2 != null)
                {
                    contents = contents.Replace("[ClientAddress2]", "<br/>" + Bill.ClientAddress2);
                }
                else { contents = contents.Replace("[ClientAddress2]", ""); }

                contents = contents.Replace("[paymentDate]", Bill.paymentDate);
                contents = contents.Replace("[ClientCity]", Bill.ClientCity);
                contents = contents.Replace("[ClientCounty]", Bill.ClientCounty);
                contents = contents.Replace("[ClientZipCode]", Bill.ClientZipCode);
                contents = contents.Replace("[CompRegistrationNo]", Bill.CompRegistrationNo);
                contents = contents.Replace("[BillDate]", Bill.BillDate);
                contents = contents.Replace("[BillDate]", Bill.BillDate);
                contents = contents.Replace("[BillID]", Bill.BillID);
                contents = contents.Replace("[BillNO]", Bill.BillNO);
                contents = contents.Replace("[AccountNo]", Bill.AccountNo);
                contents = contents.Replace("[TemplateTelephone]", Bill.TemplateTelephone);
                contents = contents.Replace("[TemplateEmail]", Bill.TemplateEmail);
                contents = contents.Replace("[OpeningHour]", Bill.OpeningHour);
                contents = contents.Replace("[ClosingHour]", Bill.ClosingHour);
                contents = contents.Replace("[CurrentTariff]", Bill.CurrentTariff);
                contents = contents.Replace("[PaymentDueDate]", Bill.PaymentDueDate);
                contents = contents.Replace("[TemplateAddress]", Bill.TemplateAddress);
                contents = contents.Replace("[TemplateCity]", Bill.TemplateCity);
                contents = contents.Replace("[TemplateCounty]", Bill.TemplateCounty);
                contents = contents.Replace("[TemplateZipcode]", Bill.TemplateZipcode);
                contents = contents.Replace("[Fixedcharges]", Bill.Fixedcharges.ToString());
                //-------------------EnergyList----------------------

                StringBuilder Sbenergy = new StringBuilder();
                StringBuilder SbenergyList = new StringBuilder();
                StringBuilder PaymentList = new StringBuilder();
                StringBuilder Fixedcharge = new StringBuilder();
                StringBuilder Varcharge = new StringBuilder();
                foreach (var item in Consumption)
                {
                    Sbenergy.Append("<tr >");
                    Sbenergy.Append("<td>" + item.Engergy + "</td>");
                    Sbenergy.Append("<td>&nbsp;</td>");
                    Sbenergy.Append("<td align='right'>£" + item.TotalAmount + "</td></tr>");

                }

                foreach (var item in Fixcharges)
                {
                    Fixedcharge.Append("<tr>");
                    Fixedcharge.Append("<td>" + item.ChargeName + "</td>");
                    Fixedcharge.Append("<td align='center' >" + item.DailyCharge.ToString() + "</td>");
                    Fixedcharge.Append("<td align='center' >" + item.VatRate.ToString() + "</td></tr>");
                }

                foreach (var item in Vatcharges)
                {
                    Varcharge.Append("<tr>");
                    Varcharge.Append("<td> VAT " + item.VatRate + " %</td>");
                    Varcharge.Append("<td> </td>");
                    Varcharge.Append("<td align='right'> &pound;" + item.VatAmount.ToString() + "</td></tr>");
                }

                foreach (var item in Consumption)
                {
                    SbenergyList.Append("<tr>");
                    SbenergyList.Append("<td align='center'>" + item.Engergy + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.DeviceID + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.UnitCode + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.StartMeterReading + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.EndMeterReading + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.DailyConsumption + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.TariffRate + "</td>");
                    SbenergyList.Append("<td align='center'>" + item.TariffVAT + "</td>");
                    SbenergyList.Append("</tr>");

                }

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

                contents = contents.Replace("[EngergyRecordList]", Sbenergy.ToString());
                contents = contents.Replace("[BillConsumption]", SbenergyList.ToString());
                contents = contents.Replace("[FixedCharged]", Fixedcharge.ToString());
                contents = contents.Replace("[VatChargeList]", Varcharge.ToString());

                String SmilyImage = "<img src='" + Server.MapPath("~/Images/smily.jpg") + "' width='14' height='12' alt=' '>";
                contents = contents.Replace("[SmilyImage]", SmilyImage);

                if (Bill.DirectDebit.Trim() == "1")
                {
                   // String DirectDebitImg = "<img src='" + Server.MapPath("~/Images/direct_debit_pdf.png") + "'  height='30' align='center'  alt=' '>  ";
                    PaymentList.Append("<td align='center'  valign='top' ><table><tr><td align='center'  valign='top'> <img src='" + Server.MapPath("~/Images/img1.jpg") + "'  height='50' align='center'  alt=' '></td> </tr><tr><td align='center' >Please call us on " + Bill.TemplateTelephone + "  to set up or amend your fixed or variable Direct Debit </td></tr></table></td>");
                }
                if (Bill.PayPoint == "1")
                {

                    PaymentList.Append("<td  valign='top'  style='font-size:10px; text-align:center; padding:10px;'>");
                    String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(PayPointImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>");
                }

                if (Bill.PayZone == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30'  alt=' '>";
                    PaymentList.Append(PayZoneImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>");
                }

                if (Bill.PostOffice == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(PostOfficeImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>");
                }

                if (Bill.BankTransfer == "1")
                {

                    PaymentList.Append("<td  valign='top'>");
                    String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30'  alt=' '>";
                    PaymentList.Append(BankTransferImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Our account details for Bank Transfers:     ");
                    if (Bill.SortCode != null)
                    {
                        PaymentList.Append("Sort Code " + Bill.SortCode);
                    }

                    if (Bill.ClientBankAccountNo != null)
                    {
                        PaymentList.Append("  Account Number   ");
                        PaymentList.Append(Bill.ClientBankAccountNo);
                    }
                    PaymentList.Append("</td>");
                }

                if (Bill.TelephonePay == "1")
                {

                    PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                    String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30'  alt=' '>";
                    PaymentList.Append(telephonepaypngImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card by calling   ");
                    PaymentList.Append(Bill.TemplateTelephone);
                    PaymentList.Append("</td>");
                }
                if (Bill.OnlinePay == "1")
                {

                    PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                    String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>";
                    PaymentList.Append(OnlinePaypngImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details");
                    PaymentList.Append("</td>");
                }

                if (Bill.OnlineNTelephonePay == "1")
                {

                    PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                    String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "'  height='30' alt=' '>";
                    PaymentList.Append(OnlineNTelephonePayImg);
                    PaymentList.Append("<div style='clear:both'></div>");
                    PaymentList.Append("Pay by Credit or Debit Card calling    ");
                    PaymentList.Append(Bill.TemplateTelephone);
                    PaymentList.Append("    visit www.mysycous.com</td>");
                }

                contents = contents.Replace("[PaymentOption]", PaymentList.ToString());
                // document.NewPage();
                // Step 4: Parse the HTML string into a collection of elements...
                var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                // Enumerate the elements, adding each one to the Document...
                foreach (var htmlElement in parsedHtmlElements)
                {
                    document.Add(htmlElement as IElement);
                }

                // writer.CloseStream = false;
                document.Close();
                writer.Close();
                byte[] file = workStream.ToArray();
                MemoryStream output = new MemoryStream();
                output.Write(file, 0, file.Length);
                output.Position = 0;
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-disposition", "attachment; filename=" + PDFName + ""); // open in a new window
                Response.OutputStream.Write(output.GetBuffer(), 0, output.GetBuffer().Length);
                Response.Flush();

            }
            catch (Exception ex)
            {
                //workStream.Dispose();
                //output.Dispose();
                document.Dispose();
            }
        }
        public void GeneralLetter(String CreditControlID)
        {
            try
               {

               BillCreditControlList Vwobj = new BillCreditControlList();
               Vwobj = BAL.BillCreditControlModel.ViewCreditControlReminderLetter(CreditControlID);

               if (Vwobj != null)
               {
                   var document = new Document(PageSize.A4, 50, 50, 25, 25);
                   String PDFName = Vwobj.BillNo + "-" + Vwobj.ID.ToString() + ".pdf";
                   var filePath = Path.Combine(Server.MapPath("~/PdfContent/CreditControl/Letter"), PDFName);
                   //  var output = new MemoryStream();
                   var output = new FileStream(filePath, FileMode.Create);

                   var writer = PdfWriter.GetInstance(document, output);
                   try
                   {
                       // Open the Document for writing
                       document.Open();
                       // Read in the contents of the Receipt.htm file...

                       StyleSheet styles = new StyleSheet();
                       //styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONTSIZE, "16");
                       //styles.LoadTagStyle(HtmlTags.P, HtmlTags.FONTSIZE, "10");
                       //styles.LoadTagStyle(HtmlTags.P, HtmlTags.m, "#ff0000");

                       //styles.LoadTagStyle(HtmlTags.CLASS, HtmlTags.COLOR, "#ff0000");
                       styles.LoadTagStyle(HtmlTags.TD, HtmlTags.ALIGN, "left");
                       styles.LoadTagStyle(HtmlTags.TD, HtmlTags.CELLPADDING, "10");
                       styles.LoadTagStyle(HtmlTags.P, HtmlTags.P, "margin-bottom:20px");
                       styles.LoadTagStyle(HtmlTags.P, HtmlTags.SPAN, "text-decoration:underline;");
                       styles.LoadStyle("Subject", "ALIGN", "center");
                       styles.LoadStyle("Subject", "FONTSIZE", "26px");
                       styles.LoadStyle("Subject", "color", "#ff0000");
                       styles.LoadStyle("c_outstanding", "font-size", "20px");
                       styles.LoadStyle("c_outstanding", "text-align", "center");

                       String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/GeneralLetter.htm"));

                       // Replace the placeholders with the user-specified text
                       contents = contents.Replace("[CustomerName]", Vwobj.ConsumerName.Trim());
                       contents = contents.Replace("[AddressLine1]", Vwobj.ConsumerAddress.Trim());
                       contents = contents.Replace("[AddressLine2]", Vwobj.ConsumerCounty.Trim());
                       contents = contents.Replace("[AddressLine3]", Vwobj.ConsumerCity.Trim());

                       contents = contents.Replace("[PostCode]", Vwobj.ConsumerZipCode.Trim());
                       contents = contents.Replace("[Amount]", Vwobj.LastBillAmount.ToString().Trim());
                      //' contents = contents.Replace("[propertyAddress]", Vwobj.PropertyNo.Trim());
                       contents = contents.Replace("[sitename]", Vwobj.SiteName.Trim());
                       contents = contents.Replace("[balanceofaccount]", Vwobj.Balance.ToString());
                       contents = contents.Replace("[invoicedateFrom]", Vwobj.InvoiceDateForm);
                       contents = contents.Replace("[invoicedateTo]", Vwobj.InvoiceDateTo);
                       contents = contents.Replace("[InvioceDate]", Vwobj.InvoiceDate);
                       contents = contents.Replace("[ClientName]", Vwobj.ClientName);
                       contents = contents.Replace("[ClientTelephoneNumber]", Vwobj.ClientTelephone);
                       contents = contents.Replace("[ClientEmailAddress]", Vwobj.ClientEmail);
                       var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                       // Enumerate the elements, adding each one to the Document...
                       foreach (var htmlElement in parsedHtmlElements)
                       {
                           document.Add(htmlElement as IElement);
                       }

                       writer.CloseStream = false;
                       document.Close();
                       output.Dispose();

                   }
                   catch (Exception ex)
                   {
                       output.Dispose();
                       document.Dispose();
                   }

               }//if
               }//try
               catch (Exception ex)
               {
               throw;
               }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)
                {
                    string tType = Request.Form["type"].ToString();
                    string tSvg = Request.Form["svg"].ToString();
                    string tFileName = Request.Form["filename"].ToString();

                    if (tFileName == "")
                    {
                        tFileName = "chart";
                    }

                    string tTmp = new Random().Next().ToString();

                    string tExt = "";
                    string tTypeString = "";

                    switch (tType)
                    {
                        case "image/png":
                            tTypeString = "-m image/png";
                            tExt = "png";
                            break;
                        case "image/jpeg":
                            tTypeString = "-m image/jpeg";
                            tExt = "jpg";
                            break;
                        case "application/pdf":
                            tTypeString = "-m application/pdf";
                            tExt = "pdf";
                            break;
                        case "image/svg+xml":
                            tTypeString = "-m image/svg+xml";
                            tExt = "svg";
                            break;
                    }

                    string tSvgOuputFile = tTmp + "." + "svg";
                    string tOutputFile = tTmp + "." + tExt;

                    if (tTypeString != "")
                    {
                        string tWidth = Request.Form["width"].ToString();
                        //WRITING SVG TO DISK
                        StreamWriter tSw = new StreamWriter(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                        tSw.Write(tSvg);
                        tSw.Close();
                        tSw.Dispose();

                        Svg.SvgDocument tSvgObj = SvgDocument.Open(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);

                        switch (tExt)
                        {
                            case "jpg":
                                tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, ImageFormat.Jpeg);
                                //DELETING SVG FILE 
                                if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                {
                                    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                }
                                break;
                            case "png":
                                tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, ImageFormat.Png);
                                //DELETING SVG FILE
                                if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                {
                                    File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                }
                                break;
                            case "pdf":

                                PdfWriter tWriter = null;
                                Document tDocumentPdf = null;
                                try
                                {
                                    // First step saving png that would be used in pdf
                                    tSvgObj.Draw().Save(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png", ImageFormat.Png);

                                    // Creating pdf document
                                    tDocumentPdf = new Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                                    // setting up margin to full screen image
                                    tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                                    // creating image
                                    iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png");
                                    tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                                    // Insert content
                                    tWriter = PdfWriter.GetInstance(tDocumentPdf, new FileStream(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile, FileMode.Create));
                                    tDocumentPdf.Open();
                                    tDocumentPdf.NewPage();
                                    tDocumentPdf.Add(tGraph);
                                    tDocumentPdf.CloseDocument();

                                    // deleting png
                                    if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png"))
                                    {
                                        File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile.Substring(0, tOutputFile.LastIndexOf(".")) + ".png");
                                    }

                                    // deleting svg
                                    if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile))
                                    {
                                        File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tSvgOuputFile);
                                    }

                                }
                                catch (Exception ex)
                                {
                                    throw ex;

                                }
                                finally
                                {
                                    tDocumentPdf.Close();
                                    tDocumentPdf.Dispose();
                                    tWriter.Close();
                                    tWriter.Dispose();

                                }


                                break;

                            case "svg":
                                tOutputFile = tSvgOuputFile;
                                break;
                        }





                        if (File.Exists(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile))
                        {

                            //Putting session to be able to delete file in temp directory
                            Session["sFileToTransmit_highcharts_export"] = File.ReadAllBytes(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);
                            //First step deleting disk file;
                            File.Delete(Server.MapPath(null) + ConfigurationManager.AppSettings["EXPORT_TEMP_FOLDER"].ToString() + tOutputFile);
                            
                            Response.ClearContent();
                            Response.ClearHeaders();
                            Response.ContentType = tType;
                            Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName + "." + tExt + "");
                            Response.BinaryWrite((byte[])Session["sFileToTransmit_highcharts_export"]);
                            Response.End();
                        }

                    }
                }
            }
        }
Example #24
0
        public string MergePDFs(string[] transids)
        {
            string targetPDF = "PaymentReceipts" + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString() + ".pdf";
                targetPDF = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\" + targetPDF;
                using (FileStream stream = new FileStream(targetPDF, FileMode.Create))
                {
                    Document pdfDoc = new Document();

                    PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                    pdfDoc.Open();
                    var files = Directory.GetFiles(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\");
                    Console.WriteLine("Merging files count: " + files.Length);
                    int i = 1;
                    foreach (string file in transids)
                    {
                        Console.WriteLine(i + ". Adding: " + file);
                        pdf.AddDocument(new PdfReader(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + file + ".pdf"));
                        i++;
                    }

                    if (pdfDoc != null)
                    {
                        pdfDoc.Close();
                        pdfDoc.Dispose();
                    }

                    return targetPDF;
                }
        }
Example #25
0
    void CreateFromRawdataFile(string sourceTxtPath, string destinationPDFPath)
    {
        pdfdoc = new iTextSharp.text.Document();
        pdfdoc.SetPageSize(currentPageSize);

        gridCountInBlockRowHorizontal = (int)(currentPageSize.Width / gridSideLength);
        blockRowHeight         = gridSideLength * gridCountInBlockRowVertical;
        blockRowCount          = (int)(currentPageSize.Height / (blockRowHeight + blockRowInterval));
        rawDataCountInBlockRow = (int)(gridCountInBlockRowHorizontal * 40 * 512 / 1000);
        rawDataInterval        = currentPageSize.Width / rawDataCountInBlockRow;

        Debug.Log("gridCountInBlockRowHorizontal:" + gridCountInBlockRowHorizontal);
        Debug.Log("rawDataCountInBlockRow" + rawDataCountInBlockRow);

        if (File.Exists(destinationPDFPath))
        {
            File.Delete(destinationPDFPath);
        }

        pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(destinationPDFPath, FileMode.CreateNew));

        pdfdoc.Open();

        iTextSharp.text.pdf.PdfContentByte cb = pdfwriter.DirectContent;

        pdfdoc.NewPage();
        blockRowIndex = 0;
        rawDataIndex  = 0;

        iTextSharp.text.pdf.BaseFont font = iTextSharp.text.pdf.BaseFont.CreateFont();
        cb.SetFontAndSize(font, 60);
        cb.BeginText();
        cb.SetTextMatrix(100, currentPageSize.Height - 50);
        cb.ShowText("Test String .......");
        cb.EndText();

        System.IO.StreamReader reader = new StreamReader(sourceTxtPath);
        string theLine;
        int    rawData;

        while (!reader.EndOfStream)
        {
            theLine = reader.ReadLine();
            try{
                rawData = int.Parse(theLine);
            }catch (Exception e) {
                Debug.Log("Exception");
                continue;
            }

            rawData       = rawData > maxRawData ? maxRawData : rawData;
            rawData       = rawData < -maxRawData ? -maxRawData : rawData;
            scaledRawData = (rawData * (blockRowHeight / 2)) / maxRawData;

            if (rawDataIndex == 0)
            {
                currentBaseLine = currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + (blockRowHeight / 2));

                cb.SetColorStroke(iTextSharp.text.BaseColor.RED);

                //draw horizontal lines
                for (int i = 0; i <= gridCountInBlockRowVertical; i++)
                {
                    if (i % 5 == 0)
                    {
                        cb.SetLineWidth(2.5f);
                    }
                    else
                    {
                        cb.SetLineWidth(0.5f);
                    }
                    cb.MoveTo(0, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength));
                    cb.LineTo(currentPageSize.Width, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength));
                    cb.Stroke();
                }

                //draw vertical lines
                for (int j = 0; j <= gridCountInBlockRowHorizontal; j++)
                {
                    if (j % 5 == 0)
                    {
                        cb.SetLineWidth(2.5f);
                    }
                    else
                    {
                        cb.SetLineWidth(0.5f);
                    }
                    cb.MoveTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval)));
                    cb.LineTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + blockRowHeight));
                    cb.Stroke();
                }
                //prepare to draw ECG
                cb.SetLineWidth(1.5f);
                cb.SetColorStroke(iTextSharp.text.BaseColor.BLACK);

                cb.MoveTo(0, currentBaseLine);
            }

            cb.LineTo(rawDataIndex * rawDataInterval, currentBaseLine + scaledRawData);
            rawDataIndex++;
            if (rawDataIndex >= rawDataCountInBlockRow)
            {
                cb.Stroke();
                rawDataIndex = 0;
                blockRowIndex++;
            }
        }
        cb.Stroke();
        reader.Close();



        pdfdoc.Dispose();
        System.Diagnostics.Process.Start(destinationPDFPath);
    }
        public void PDF(string beginDate, string dept_ID, string dept_name, string monday)
        {
            List<test> all = new List<test>();
            List<WorkingPerDay> WorkingHoursPerDay = new List<WorkingPerDay>();
            Array recordweek = new Array[6];

            //  DateTime newdate = DateTime.Parse(monday);

            Document document = new Document(PageSize.A1, 5, 5, 15, 15);
            string filepath = @"C:\\Users\\rcalix\\Documents\\Report_" + dept_name + "_" + monday + ".pdf";
            if ((!System.IO.File.Exists(filepath)))
            {
                using (FileStream output = new FileStream((filepath), FileMode.Create))
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(document, output))
                    {

                        document.Open();
                        PdfPTable table = new PdfPTable(24);
                        table.TotalWidth = 5000f;
                        float[] widths = new float[] { 1300f, 1300, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f, 1300f };
                        table.SetWidths(widths);
                        PdfPCell cell = new PdfPCell();
                        PdfPCell cellName = new PdfPCell();
                        Array[] list = { };
                        iTextSharp.text.Font georgia = FontFactory.GetFont("georgia", 14f);
                        georgia.Color = iTextSharp.text.BaseColor.BLUE;
                        string begindate = "09-14-2015";
                        try
                        {
                            var init = Convert.ToInt32(dept_ID.ToString());
                            using (ReportSupEntities1 dc = new ReportSupEntities1())
                            {
                                //   all = (from e in dc).ToList();

                                all = (from e in dc.sp_matrix_weekdays(init, begindate) select new test { Nombre = e.name, FechaEntradaMonday = e.Hora_de_LLegada_Lunes, FechaSalidaMonday = e.Hora_de_salida_Lunes, HorasMonday = e.Monday, FechaEntradaTuesday = e.Hora_de_LLegada_Martes, FechaSalidaTuesday = e.Hora_de_salida_Martes, HorasTuesday = e.Tuesday, FechaEntradaWendnsday = e.Hora_de_LLegada_Miercoles, FechaSalidaWendnsday = e.Hora_de_salida_Miercoles, HorasWendnsday = e.Wednsday, FechaEntradaThursday = e.Hora_de_LLegada_Jueves, FechaSalidaThursday = e.Hora_de_salida_Jueves, HorasThursday = e.Thursday, FechaEntradaFriday = e.Hora_de_LLegada_Viernes, FechaSalidaFriday = e.Hora_de_salida_Viernes, HorasFriday = e.Friday, FechaEntradaSaturday = e.Hora_de_LLegada_Sabado, FechaSalidaSaturday = e.Hora_de_salida_Sabado, HorasSaturday = e.Saturday, FechaEntradaSunday = e.Hora_de_LLegada_Domingo, FechaSalidaSunday = e.Hora_de_salida_Domingo, HorasSunday = e.Sunday }).ToList();
                                //    WorkingHoursPerDay = (from i in dc.sp_GetWorkingHoursPerDay(1, Convert.ToDateTime("08-13-2015").AddDays(w)) select new WorkingPerDay { Name = i.Name, HourInput = i.horaEntrada, HourOutput = i.horasalida, workingHours = Convert.ToInt32(i.horaTrabajada) }).ToList();
                                //     list[w] = WorkingHoursPerDay.ToList().ToArray();
                            }
                            DateTime date = Convert.ToDateTime(begindate);

                            //PdfPCell june = new PdfPCell(new Phrase("Cell 2",georgia));

                            PdfPCell nombre = new PdfPCell(new Phrase("Name"));

                            nombre.Rowspan = 2;
                            nombre.Colspan = 2;
                            nombre.HorizontalAlignment = 1;
                            nombre.VerticalAlignment = 0;
                            table.AddCell(nombre);

                            PdfPCell june = new PdfPCell(new Phrase("Moday :" + Convert.ToDateTime(date).ToShortDateString().ToString(), georgia));
                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);
                            june = new PdfPCell(new Phrase("Tuesday :" + Convert.ToDateTime(date).AddDays(1).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);
                            june = new PdfPCell(new Phrase("Wednsday :" + Convert.ToDateTime(date).AddDays(2).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);
                            june = new PdfPCell(new Phrase("Thursday :" + Convert.ToDateTime(date).AddDays(3).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);

                            june = new PdfPCell(new Phrase("Friday :" + Convert.ToDateTime(date).AddDays(4).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);

                            june = new PdfPCell(new Phrase("Saturday :" + Convert.ToDateTime(date).AddDays(5).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);
                            june = new PdfPCell(new Phrase("Sunday :" + Convert.ToDateTime(date).AddDays(6).ToShortDateString(), georgia));

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);

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

                            june.HorizontalAlignment = 1;
                            june.Colspan = 3;
                            table.AddCell(june);

                            PdfPCell second = new PdfPCell();
                            for (var i = 0; i <= 6; i++)
                            {
                                second = new PdfPCell(new Phrase("In"));
                                second.HorizontalAlignment = 1;
                                table.AddCell(second);

                                second = new PdfPCell(new Phrase("Out"));
                                second.HorizontalAlignment = 1;
                                table.AddCell(second);

                                second = new PdfPCell(new Phrase("Worked Hours"));
                                second.HorizontalAlignment = 1;
                                table.AddCell(second);

                            }
                            second = new PdfPCell(new Phrase("Weekly Hours Worked"));
                            second.HorizontalAlignment = 1;
                            table.AddCell(second);

                            foreach (var item in all)
                            {

                                cellName.Phrase = new Phrase(item.Nombre);
                                cellName.HorizontalAlignment = 1;
                                cellName.Colspan = 2;
                                table.AddCell(cellName);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaMonday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaMonday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasMonday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaTuesday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaTuesday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasTuesday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaWendnsday).ToShortTimeString().ToString());

                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaWendnsday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasWendnsday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaThursday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaThursday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasThursday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaFriday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaFriday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasFriday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaSaturday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaSaturday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasSaturday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaEntradaSunday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase(Convert.ToDateTime(item.FechaSalidaSunday).ToShortTimeString().ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                cell.Phrase = new Phrase((item.HorasSunday).ToString());
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);
                                // DateTime d1 = DateTime.Parse(Convert.ToDateTime(item.HorasMonday).ToString());
                                //DateTime d2 = DateTime.Parse(Convert.ToDateTime(item.HorasMonday).ToString());
                                //   double span = (d1 - d2).TotalHours;
                                cell.Phrase = new Phrase(Convert.ToString(Convert.ToDecimal(item.HorasMonday) + Convert.ToDecimal(item.HorasTuesday) + Convert.ToDecimal(item.HorasWendnsday) + Convert.ToDecimal(item.HorasThursday) + Convert.ToDecimal(item.HorasFriday) + Convert.ToDecimal(item.HorasSaturday) + Convert.ToDecimal(item.HorasSunday)));
                                cell.HorizontalAlignment = 1;
                                table.AddCell(cell);

                                //table.Rows.Add(cell);
                                //

                            }

                            //            document.Add(table);

                            document.Add(table);
                            document.Close();
                            document.Dispose();
                            writer.Close();
                            output.Close();

                        }

                        catch (Exception)
                        {

                        }
                        //  DateTime date =Convert.ToDateTime(Convert.ToDateTime("09-21-2015")).ToShortDateString();

                    }
                }
                //  var output = new MemoryStream();
            }
        }
Example #27
0
    void CreateFromFolder(string folderPath)
    {
        pdfdoc = new iTextSharp.text.Document();
        pdfdoc.SetPageSize(iTextSharp.text.PageSize.A0);

        Debug.Log("000000");

        string pdfPath = Path.Combine(folderPath, "output.pdf");

        if (File.Exists(pdfPath))
        {
            File.Delete(pdfPath);
        }
        Debug.Log("1111111");

        pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(pdfPath, FileMode.CreateNew));

        Debug.Log("22222");
        pdfdoc.Open();

        pdfdoc.NewPage();

        string[] paths = Directory.GetFiles(folderPath);

        int rows;
        int columns;

        int rowIndex  = 1;
        int pageIndex = 1;

        float pageWidth  = iTextSharp.text.PageSize.A0.Width;
        float pageHeight = iTextSharp.text.PageSize.A0.Height;

        pdfImg = iTextSharp.text.Image.GetInstance(paths[0]);

        rows    = (int)(pageHeight / pdfImg.Height);
        columns = (int)(pageWidth / pdfImg.Width);
        Debug.Log("Rows:" + rows);
        Debug.Log("Columns:" + columns);

        for (int i = 0; i < paths.Length; i++)
        {
            if (paths[i].EndsWith(".png"))
            {
                Debug.Log(paths[i]);
                pdfImg = iTextSharp.text.Image.GetInstance(paths[i]);

                if (i == columns * rows * pageIndex)
                {
                    pageIndex++;
                    Debug.Log("pageIndex:" + pageIndex);

                    pdfdoc.NewPage();
                    rowIndex = 1;
                    Debug.Log("rowIndex:" + rowIndex);
                }
                else if (i != 0 && i % columns == 0)
                {
                    rowIndex++;
                    Debug.Log("rowIndex:" + rowIndex);
                }
                pdfImg.SetAbsolutePosition(pdfImg.Width * (i % columns), pageHeight - pdfImg.Height * rowIndex);

                pdfdoc.Add(pdfImg);
            }
        }

        pdfdoc.Dispose();
    }
Example #28
0
        public ActionResult cvdownload(int js_id)
        {
            jobseeker_info js             = db.jobseeker_info.Find(js_id);
            StringBuilder  status         = new StringBuilder("");
            DateTime       dTime          = DateTime.Now;
            string         strPDFFileName = string.Format("CvPdf" + dTime.ToString("yyyyMMdd") + "-" + ".pdf");
            string         strAttachment  = Server.MapPath("~/Content/pdfs/" + strPDFFileName);

            status.Append("<!DOCTYPE html>");
            status.Append("<html>");
            status.Append("<head><title></title></head>");
            status.Append("<body style='margin: 20px 100px;'><h2 style='text-align:center'>Curriculum Vitae</h2>");
            status.Append("<b>" + js.full_name + "</b><br>");
            status.Append("<b>(+977)" + js.contact + "</b><br>");
            status.Append("<b>" + js.email + "</b><br>");
            status.Append("<b>" + js.current_address + "</b><br><br>");
            List <jobseeker_education> ed = db.jobseeker_education.Where(a => a.js_id == js_id).OrderByDescending(a => a.jsed_id).ToList();

            if (ed.Count > 0)
            {
                status.Append("<h3><b>Education</b></h3>");
                foreach (var item in ed)
                {
                    status.Append("<b>" + item.education_level + "</b><br><ul>");
                    status.Append("<li>" + item.start_date + " - " + item.end_date + "</li>");
                    status.Append("<li>" + item.institution + "</li></ul>");
                }
            }
            List <js_experience> ex = db.js_experience.Where(a => a.js_id == js_id).ToList();

            if (ex.Count > 0)
            {
                status.Append("<h3><b>Experience</b></h3><br>");
                foreach (var item in ex)
                {
                    status.Append("<b>" + item.title + "</b><br><ul>");
                    status.Append("<li>" + item.start_date + " - " + item.end_date + "</li>");
                    status.Append("<li>" + item.institution + "</li></ul>");
                }
            }
            List <string> skills = js.skills.Split(',').ToList();

            if (skills.Count > 0)
            {
                status.Append("<h3><b>Skills</b></h3><br><ul>");
                foreach (var item in ex)
                {
                    status.Append("<b>" + item + "</b><br><br>");
                }
                status.Append("</ul>");
            }
            string cv = db.tbl_cv.Where(a => a.jobseeker_id == js.js_id).Select(a => a.cv).FirstOrDefault().ToString();

            status.Append(cv);
            status.Append("</body>");
            status.Append("</html>");
            StringReader str = new StringReader(status.ToString());
            MemoryStream ms  = new MemoryStream();

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4);

            PdfWriter pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms);

            document.Open();
            using (TextReader sReader = new StringReader(status.ToString()))
            {
                List <IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
                foreach (IElement elm in list)
                {
                    document.Add(elm);
                }
            }
            document.Close();
            document.Dispose();
            Response.Buffer = true;
            Response.Clear();
            Response.AppendHeader("Content-Type", "application/x-pdf");
            Response.AppendHeader("Content-disposition", "attachment; filename=" + js.full_name + "cv.pdf");
            Response.BinaryWrite(ms.GetBuffer());
            Response.Flush();
            Response.Close();
            return(View());
        }
Example #29
0
        public string HTMLToPdfTemp(string HTML, string FilePath)
        {
            //FilePath = FilePath.ToString() +DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
                Document document = new Document();
                try
                {
                    PdfWriter.GetInstance(document, new FileStream(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + FilePath.ToString() + ".pdf", FileMode.Create));
                }
                catch (IOException ex)
                {
                    PdfWriter.GetInstance(document, new FileStream(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\PDF\\Temp\\" + FilePath.ToString() + ".pdf", FileMode.Create));
                }
                document.Open();
                //iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.png"));
                //pdfImage.ScaleToFit(200, 200);
                //pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING;
                //pdfImage.SetAbsolutePosition(20, 730);

                //iTextSharp.text.Image pdfsign = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Images/sign.png"));
                //pdfsign.ScaleToFit(150, 150);
                //pdfsign.Alignment = iTextSharp.text.Image.ALIGN_BOTTOM;
                //pdfsign.SetAbsolutePosition(400, 365);

                //  document.Add(pdfImage);
                // document.Add(pdfsign);

                iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
                iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
                hw.Parse(new StringReader(HTML));
                document.Close();
                document.Dispose();
                return FilePath + ".pdf";
        }
        public void GenerateReminder1(String CreditControlID )
        {
            try
               {

               BillCreditControlList Vwobj = new BillCreditControlList();
               Vwobj = BAL.BillCreditControlModel.ViewCreditControlReminderLetter(CreditControlID);

               if (Vwobj != null)
               {
                       // Boolean flag = false;
                       var document = new Document(PageSize.A4, 10, 10, 10, 10);
                       String PDFName = Vwobj.BillNo.ToString() + Vwobj.ValidationType + "_"+Vwobj.ID + ".pdf";
                       var filePath = Path.Combine(Server.MapPath("~/PdfContent/CreditControl/Reminder"), PDFName);
                       //  var output = new MemoryStream();
                       var output = new FileStream(filePath, FileMode.Create);

                       var writer = PdfWriter.GetInstance(document, output);

                       writer.PageEvent = new HeaderFooter(CreditControlID);

                       try
                       {
                       // Open the Document for writing
                       document.Open();
                       // Read in the contents of the Receipt.htm file...

                       StyleSheet styles = new StyleSheet();

                       String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/ReminderLetter1.htm"));

                       // Replace the placeholders with the user-specified text
                       String clientLogo = String.Empty;

                     //  contents = contents.Replace("[ClientImage]", clientLogo);
                       contents = contents.Replace("[ConsumerName]", Vwobj.ConsumerName.Trim());
                       // contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim());
                       contents = contents.Replace("[ConsumerAddress]", Vwobj.ConsumerAddress.Trim());
                       if (Vwobj.ConsumerAddress2 != null)
                       {
                           contents = contents.Replace("[ConsumerAddress2]", "<br/>" + Vwobj.ConsumerAddress2.Trim());
                       }
                       else
                       {
                           contents = contents.Replace("[ConsumerAddress2]", " ");
                       }
                       contents = contents.Replace("[ConsumerCity]", Vwobj.ConsumerCity.Trim());
                       contents = contents.Replace("[ConsumerCountry]", Vwobj.ConsumerCounty.Trim());
                       contents = contents.Replace("[ConsumerZipCode]", Vwobj.ConsumerZipCode.Trim());
                       contents = contents.Replace("[balanceofaccount]", Vwobj.Balance.ToString());

                       contents = contents.Replace("[Client]", Vwobj.ClientName.Trim());
                       contents = contents.Replace("[ClientAddress]", Vwobj.ClientAddress.Trim());
                       if (Vwobj.ClientAddress2 != null)
                       {
                           contents = contents.Replace("[ClientAddress2]", "<br/>" + Vwobj.ClientAddress2.Trim());
                       }
                       else { contents = contents.Replace("[ClientAddress2]", ""); }

                       contents = contents.Replace("[ClientCity]", Vwobj.ClientCity.Trim());
                       contents = contents.Replace("[ClientCounty]", Vwobj.ClientCounty.Trim());
                       contents = contents.Replace("[ClientZipCode]", Vwobj.ClientZipCode.Trim());
                       contents = contents.Replace("[CompRegistrationNo]", Vwobj.CompRegistrationNo !=null? Vwobj.CompRegistrationNo :"");
                       contents = contents.Replace("[Amount]", Vwobj.LastBillAmount.ToString().Trim());
                       contents = contents.Replace("[ReminderDate]", Vwobj.ReminderDate != null? Vwobj.ReminderDate.ToString().Trim():"");
                       if (Vwobj.PropertyAddress != null)
                       {
                           contents = contents.Replace("[PropertyAddress]", Vwobj.PropertyAddress.ToString().Trim());
                       }
                       else
                       {
                           contents = contents.Replace("[PropertyAddress]", "");
                       }
                       if (Vwobj.TemplateTelephone != null)
                       {
                           contents = contents.Replace("[TemplateTelephone]", Vwobj.TemplateTelephone);
                       }
                       else
                       {
                           contents = contents.Replace("[TemplateTelephone]", "");
                       }
                       if (Vwobj.TemplateEmail != null)
                       {
                           contents = contents.Replace("[TemplateEmail]", Vwobj.TemplateEmail);
                       }
                       else
                       { contents = contents.Replace("[TemplateEmail]", ""); }

                       if (Vwobj.OpeningHour != null)
                       {
                           contents = contents.Replace("[OpeningHour]", Vwobj.OpeningHour);
                       }
                       else { contents = contents.Replace("[OpeningHour]", ""); }

                       contents = contents.Replace("[ClosingHour]", Vwobj.ClosingHour != null?  Vwobj.ClosingHour:"" );
                       contents = contents.Replace("[TemplateAddress]", Vwobj.TemplateAddress != null? Vwobj.TemplateAddress :"");
                       contents = contents.Replace("[TemplateCity]", Vwobj.TemplateCity != null? Vwobj.TemplateCity:"");
                       contents = contents.Replace("[TemplateCounty]", Vwobj.TemplateCounty != null ? Vwobj.TemplateCounty:"" );
                       contents = contents.Replace("[TemplateZipcode]", Vwobj.TemplateZipcode != null? Vwobj.TemplateZipcode:"");
                       StringBuilder PaymentList = new StringBuilder();

                       if (Vwobj.DirectDebit == "1")
                       {

                           PaymentList.Append("<td align='center'  valign='top' ><table><tr><td align='center'  valign='top'> <img src='" + Server.MapPath("~/Images/img1.jpg") + "'  height='50' align='center'  alt=' '></td> </tr><tr><td align='center' >Please call us on " + Vwobj.TemplateTelephone + "  to set up or amend your fixed or variable Direct Debit </td></tr></table></td>");
                       }
                       if (Vwobj.PayPoint == "1")
                       {

                           PaymentList.Append("<td  valign='top'  style='font-size:10px; text-align:center; padding:10px;'>");
                           String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>";
                           PaymentList.Append(PayPointImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>");
                       }

                       if (Vwobj.PayZone == "1")
                       {

                           PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                           String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30'  alt=' '>";
                           PaymentList.Append(PayZoneImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>");
                       }

                       if (Vwobj.PostOffice == "1")
                       {

                           PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                           String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>";
                           PaymentList.Append(PostOfficeImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>");
                       }

                       if (Vwobj.BankTransfer == "1")
                       {

                           PaymentList.Append("<td  valign='top'>");
                           String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30'  alt=' '>";
                           PaymentList.Append(BankTransferImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append("Our account details for Bank Transfers:     ");
                           if (Vwobj.SortCode != null)
                           {
                               PaymentList.Append("Sort Code " + Vwobj.SortCode);
                           }

                           if (Vwobj.ClientBankAccountNo != null)
                           {
                               PaymentList.Append("  Account Number   ");
                               PaymentList.Append(Vwobj.ClientBankAccountNo != null?Vwobj.ClientBankAccountNo :"");
                           }
                           PaymentList.Append("</td>");
                       }

                       if (Vwobj.TelephonePay == "1")
                       {

                           PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                           String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30'  alt=' '>";
                           PaymentList.Append(telephonepaypngImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append("Pay by Credit or Debit Card by calling   ");
                           PaymentList.Append(Vwobj.TemplateTelephone != null? Vwobj.TemplateTelephone:"");
                           PaymentList.Append("</td>");
                       }
                       if (Vwobj.OnlinePay == "1")
                       {

                           PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                           String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>";
                           PaymentList.Append(OnlinePaypngImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details");
                           PaymentList.Append("</td>");
                       }

                       if (Vwobj.OnlineNTelephonePay == "1")
                       {

                           PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                           String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "'  height='30' alt=' '>";
                           PaymentList.Append(OnlineNTelephonePayImg);
                           PaymentList.Append("<div style='clear:both'></div>");
                           PaymentList.Append("Pay by Credit or Debit Card calling    ");
                           PaymentList.Append(Vwobj.TemplateTelephone != null?Vwobj.TemplateTelephone :"" );
                           PaymentList.Append("    visit www.mysycous.com</td>");
                       }

                       contents = contents.Replace("[PaymentOption]", PaymentList.ToString());

                       // Step 4: Parse the HTML string into a collection of elements...
                       var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                       // Enumerate the elements, adding each one to the Document...
                       foreach (var htmlElement in parsedHtmlElements)
                       {
                           document.Add(htmlElement as IElement);
                       }

                       writer.CloseStream = false;
                       document.Close();
                       output.Dispose();

                       //Get the pointer to the beginning of the stream.
                    //   output.Position = 0;

                       //  MailCls email = new MailCls();
                       // email.EmailTo = "*****@*****.**";
                       ////  email.EmailTo = "*****@*****.**";
                       //  email.EmailSubject = "Reminder Letter 1";
                       //  email.Body = " Plz check It";
                       //  email.DispalyName = "sarajit";
                       //  email.Attachment = 0;
                       //  email.stream = output;
                       //  email.Email_Sent();
                       //  output.Dispose();
                       //  document.Dispose();

                   }
                   catch (Exception ex)
                   {
                         output.Dispose();
                         document.Dispose();
                   }

               }//if
               }//try
               catch (Exception ex)
               {
               throw;
               }
        }
Example #31
0
        /// <summary>Converts the Tif files into a multi page PDF multiple.</summary>
        /// <param name="sourceDir">The source dir.</param>
        /// <param name="destinationDir">The destination dir.</param>
        /// <exception cref="System.Exception">Source folder '"+ sourceDir + "' contains no files!!!</exception>
        private static void ConvertMultiple(string sourceDir, string destinationDir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(sourceDir);

                int totalFiles = di.GetFiles().Length;
                if (totalFiles == 0)
                {
                    throw new System.Exception("Source folder '" + sourceDir + "' contains no files!!!");
                }
                Console.WriteLine("Total Files in Source Folder = " + totalFiles);

                foreach (var file in di.GetFiles())
                {
                    totalFiles = totalFiles -= 1;

                    if (file.Extension.ToString() == ".tif" || file.Extension.ToString() == ".tiff")
                    {
                        iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
                        string     fileName                  = Path.GetFileNameWithoutExtension(file.ToString());
                        string     filePath                  = string.Format("{0}\\{1}.{2}", destinationDir, fileName, "pdf");
                        string     sourceFilePath            = string.Format("{0}\\{1}.{2}", sourceDir, fileName, "tif");
                        FileStream fs                        = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
                        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs);

                        // Counts the files remaining to be converting
                        Console.WriteLine("Converting: " + file.Name + " Total Files Left: " + totalFiles);

                        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(sourceFilePath);

                        document.Open();
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;

                        int total = bmp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
                        for (int k = 0; k < total; ++k)
                        {
                            bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp);

                            // Scale the image to fit in the page
                            img.ScalePercent(72f / img.DpiX * 100);
                            img.SetAbsolutePosition(0, 0);
                            cb.AddImage(img);
                            document.NewPage();
                        }

                        bmp.Dispose();
                        writer.Flush();
                        document.Close();
                        document.Dispose();
                    }
                    else
                    {
                        Console.WriteLine("Not Converting: " + file.Name + " Total Files Left: " + totalFiles);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
Example #32
0
        private byte[] runInDebugMode()
        {
            byte[] data;
            try
            {
                PdfDoc = new Document(DocumentSettings.GetPageSizeAndColor(_pdfRptData.DocumentPreferences),
                            _pdfRptData.DocumentPreferences.PagePreferences.Margins.Left,
                            _pdfRptData.DocumentPreferences.PagePreferences.Margins.Right,
                            _pdfRptData.DocumentPreferences.PagePreferences.Margins.Top,
                            _pdfRptData.DocumentPreferences.PagePreferences.Margins.Bottom);

                data = createPdf();
            }
            finally
            {
                PdfDoc.Dispose();
            }
            return data;
        }
Example #33
0
        public ActionResult GenerateEmail(String BillNO)
        {
            if (Session["Login"] != null)
            {
                LoginSession loginsession = (LoginSession)Session["Login"];
                String actionName = this.ControllerContext.RouteData.Values["action"].ToString();
                String controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
                ViewBag.Menu = BAL.Common.GetActiveMenu(controllerName, BAL.Common.LayoutType(loginsession.UserType));

                try
                {

                    if (BillNO != null)
                    {
                        String DecBill = BAL.Security.URLDecrypt(BillNO);

                        DAL.BillLayoutMaster Bill = null;
                        IEnumerable<DAL.BillConsumption> Consumption = null;
                        IEnumerable<DAL.BillFixchargesList> Fixcharges = null;
                        IEnumerable<DAL.BiLLVatChargeList> Vatcharges = null;
                        Bill = BAL.BillModel.GetBillHeader(BillNO);
                        Consumption = BAL.BillModel.BillConsumptionRecordList(BillNO);
                        Fixcharges = BAL.BillModel.BillFixedChargeConsumptionRecordList(BillNO);
                        Vatcharges = BAL.BillModel.BillVarChargedList(BillNO);
                      //  ------------------------------------------------------pdf-----------------------------------

                       var document = new Document(PageSize.A4,10, 10, 10, 10);
                      //  var document = new Document();
                        String PDFName = DecBill + ".pdf";
                        var filePath = Path.Combine(Server.MapPath("~/PdfContent/Bill"), PDFName);
                        //  var output = new MemoryStream();
                        var output = new FileStream(filePath, FileMode.Create);
                        var writer = PdfWriter.GetInstance(document, output);
                        try
                        {
                            document.Open();
                            String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/BillTemplate.htm"));

                            //---------------------------------style -------------------------------------------
                           StyleSheet styles = new StyleSheet();
                          // styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.COLOR, "left");
                           styles.LoadStyle("maintable", "color", "#ff0000");

                            //--------------------------------End -style -------------------------------------------

                           String clientLogo = String.Empty;
                           // Replace the placeholders with the user-specified text
                           if (!(String.IsNullOrEmpty(Bill.CompanyLogo)) && (Bill.CompanyLogo != ""))
                           {

                               clientLogo = "<img border='0' src='" + Server.MapPath("~/UserPicture/" + Bill.CompanyLogo) + "' width='190' height='46'>";
                           }
                           else
                           {
                               clientLogo = "<img border='0' src='" + Server.MapPath("~/Images/logo.png") + "' width='190' height='46'>";
                           }
                           contents = contents.Replace("[ClientImage]", clientLogo);
                           contents = contents.Replace("[ConsumerName]", Bill.ConsumerName.Trim());
                           contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim());
                           contents = contents.Replace("[ConsumerAddress]", Bill.ConsumerAddress);
                           contents = contents.Replace("[ConsumerCity]", Bill.ConsumerCity);
                           contents = contents.Replace("[ConsumerCountry]", Bill.ConsumerCounty);
                           contents = contents.Replace("[ConsumerZipCode]", Bill.ConsumerZipCode);
                           contents = contents.Replace("[ClientName]", Bill.Client);
                           if (Bill.FixedBillNotice == "Yes")
                           {
                               contents = contents.Replace("[FixedBillNote]", Bill.FixedBillNote);
                           }
                           else
                           {
                               contents = contents.Replace("[FixedBillNote]", "");
                           }
                           contents = contents.Replace("[PropertyAddress]", Bill.PropertyAddress);
                           contents = contents.Replace("[PaymentDate]", Bill.paymentDate);
                           contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                           contents = contents.Replace("[BillFromDate]", Bill.BillFromDate);
                           contents = contents.Replace("[BillToDate]", Bill.BillToDate);
                           contents = contents.Replace("[previousBalance]", Bill.previousBalance != null ? Bill.previousBalance.ToString() : "");
                           contents = contents.Replace("[EngergyList]", "");
                           contents = contents.Replace("[NoofDays]", Bill.NoofDays);
                           contents = contents.Replace("[Othercharges]", Bill.Othercharges.ToString());
                           contents = contents.Replace("[NetAmount]", Bill.NetAmount != null ? Bill.NetAmount.ToString() : "");
                           contents = contents.Replace("[VATNumber]", Bill.VATNumber);
                           contents = contents.Replace("[VatAmount]", Bill.VatAmount != null ? Bill.VatAmount.ToString() : "");
                           contents = contents.Replace("[GrossAmount]", Bill.GrossAmount != null ? Bill.GrossAmount.ToString() : "");
                           contents = contents.Replace("[paymentReceived]", Bill.paymentReceived != null ? Bill.paymentReceived.ToString() : "");
                           contents = contents.Replace("[NewBalance]", Bill.NewBalance != null ? Bill.NewBalance.ToString() : "");
                           contents = contents.Replace("[Client]", Bill.Client);
                           contents = contents.Replace("[ClientAddress]", Bill.ClientAddress);
                           //contents = contents.Replace("[ClientAddress2]", Bill.ClientAddress2);
                           contents = contents.Replace("[paymentDate]", Bill.paymentDate);
                           contents = contents.Replace("[ClientCity]", Bill.ClientCity);
                           contents = contents.Replace("[ClientCounty]", Bill.ClientCounty);
                           contents = contents.Replace("[ClientZipCode]", Bill.ClientZipCode);
                           contents = contents.Replace("[CompRegistrationNo]", Bill.CompRegistrationNo);
                           contents = contents.Replace("[BillDate]", Bill.BillDate);
                           contents = contents.Replace("[BillDate]", Bill.BillDate);
                           contents = contents.Replace("[BillID]", Bill.BillID);
                           contents = contents.Replace("[BillNO]", Bill.BillNO);
                           contents = contents.Replace("[AccountNo]", Bill.AccountNo);
                           contents = contents.Replace("[TemplateTelephone]", Bill.TemplateTelephone);
                           contents = contents.Replace("[TemplateEmail]", Bill.TemplateEmail);
                           contents = contents.Replace("[OpeningHour]", Bill.OpeningHour);
                           contents = contents.Replace("[ClosingHour]", Bill.ClosingHour);
                           contents = contents.Replace("[CurrentTariff]", Bill.CurrentTariff);
                           contents = contents.Replace("[PaymentDueDate]", Bill.PaymentDueDate);
                           contents = contents.Replace("[TemplateAddress]", Bill.TemplateAddress);
                           contents = contents.Replace("[TemplateCity]", Bill.TemplateCity);
                           contents = contents.Replace("[TemplateCounty]", Bill.TemplateCounty);
                           contents = contents.Replace("[TemplateZipcode]", Bill.TemplateZipcode);
                           //-------------------EnergyList----------------------

                           StringBuilder Sbenergy = new StringBuilder();
                           StringBuilder SbenergyList = new StringBuilder();
                           StringBuilder PaymentList = new StringBuilder();
                           StringBuilder Fixedcharge = new StringBuilder();
                           StringBuilder Varcharge = new StringBuilder();
                           foreach (var item in Consumption)
                           {
                               Sbenergy.Append("<tr>");
                               Sbenergy.Append("<td>" + item.Engergy + "</td>");
                               Sbenergy.Append("<td>&nbsp;</td>");
                               Sbenergy.Append("<td align='right'>£" + item.TotalAmount + "</td></tr>");
                           }

                           foreach (var item in Fixcharges)
                           {
                               Fixedcharge.Append("<tr>");
                               Fixedcharge.Append("<td>" + item.ChargeName + "</td>");

                               Fixedcharge.Append("<td >" + item.DailyCharge.ToString() + "</td></tr>");
                           }

                           foreach (var item in Vatcharges)
                           {
                               Varcharge.Append("<tr>");
                               Varcharge.Append("<td> VAT " + item.VatRate + " %</td>");
                               Varcharge.Append("<td> </td>");
                               Varcharge.Append("<td align='right'> &pound;" + item.VatAmount.ToString() + "</td></tr>");
                           }

                           foreach (var item in Consumption)
                           {
                               SbenergyList.Append("<tr>");
                               SbenergyList.Append("<td align='center'>" + item.Engergy + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.DeviceID + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.UnitCode + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.StartMeterReading + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.EndMeterReading + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.DailyConsumption + "</td>");
                               SbenergyList.Append("<td align='center'>" + item.TariffRate + "</td>");
                               SbenergyList.Append("</tr>");

                           }

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

                           contents = contents.Replace("[EngergyRecordList]", Sbenergy.ToString());
                           contents = contents.Replace("[BillConsumption]", SbenergyList.ToString());
                           contents = contents.Replace("[FixedCharged]", Fixedcharge.ToString());
                           contents = contents.Replace("[VatChargeList]", Varcharge.ToString());

                           String SmilyImage = "<img src='" + Server.MapPath("~/Images/smily.jpg") + "' width='14' height='12' alt=' '>";
                           contents = contents.Replace("[SmilyImage]", SmilyImage);

                           if (Bill.DirectDebit.Trim() == "1")
                           {
                               PaymentList.Append("<td align='center'  valign='top' ><div id='headerdiv'> ");
                               String DirectDebitImg = "<img src='" + Server.MapPath("~/Images/direct_debit_pdf.png") + "'  height='30'  alt=' '> </div>";
                               PaymentList.Append(DirectDebitImg);
                               PaymentList.Append("<div style='clear:both'>Please call us on </div>");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("  to set up your Direct Debit  </td>");
                           }
                           if (Bill.PayPoint == "1")
                           {

                               PaymentList.Append("<td  valign='top'  style='font-size:10px; text-align:center; padding:10px;'>");
                               String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(PayPointImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>");
                           }

                           if (Bill.PayZone == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30'  alt=' '>";
                               PaymentList.Append(PayZoneImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>");
                           }

                           if (Bill.PostOffice == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(PostOfficeImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>");
                           }

                           if (Bill.BankTransfer == "1")
                           {

                               PaymentList.Append("<td  valign='top'>");
                               String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30'  alt=' '>";
                               PaymentList.Append(BankTransferImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Our account details for Bank Transfers:     ");
                               if (Bill.SortCode != null)
                               {
                                   PaymentList.Append("Sort Code " + Bill.SortCode);
                               }

                               if (Bill.ClientBankAccountNo != null)
                               {
                                   PaymentList.Append("  Account Number   ");
                                   PaymentList.Append(Bill.ClientBankAccountNo);
                               }
                               PaymentList.Append("</td>");
                           }

                           if (Bill.TelephonePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                               String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30'  alt=' '>";
                               PaymentList.Append(telephonepaypngImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card by calling   ");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("</td>");
                           }
                           if (Bill.OnlinePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>");
                               String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>";
                               PaymentList.Append(OnlinePaypngImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details");
                               PaymentList.Append("</td>");
                           }

                           if (Bill.OnlineNTelephonePay == "1")
                           {

                               PaymentList.Append("<td  valign='top' style='font-size:10px; text-align:center; padding:10px;'>");
                               String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "'  height='30' alt=' '>";
                               PaymentList.Append(OnlineNTelephonePayImg);
                               PaymentList.Append("<div style='clear:both'></div>");
                               PaymentList.Append("Pay by Credit or Debit Card calling    ");
                               PaymentList.Append(Bill.TemplateTelephone);
                               PaymentList.Append("    visit www.mysycous.com</td>");
                           }

                              contents = contents.Replace("[PaymentOption]", PaymentList.ToString());
                           // document.NewPage();
                            // Step 4: Parse the HTML string into a collection of elements...
                            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
                            // Enumerate the elements, adding each one to the Document...
                            foreach (var htmlElement in parsedHtmlElements)
                            {
                                document.Add(htmlElement as IElement);
                            }

                            writer.CloseStream = false;
                            document.Close();
                            output.Dispose();
                            BAL.BillModel.BillSendByMail(DecBill);
                        }
                        catch (Exception ex)
                        {
                            output.Dispose();
                            document.Dispose();
                            return Content(ex.Message.ToString());
                        }
                     //-------------------------------------------------------------------------------
                        return RedirectToAction("Index", "Bill");
                    }
                    else
                    { return Content("Select View Of Bill "); }
                }
                catch (Exception ex)
                {
                    return Content("ERROR :" + ex.Message);
                }

            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }