public static void GeneratePdfReport(DateTime startDate, DateTime endDate, SupermarketChainData data)
        {
            var htmlContent = new StringBuilder();

            htmlContent.Append(
                @"<!DOCTYPE html>
                <html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">
                <head>
                    <meta charset=""utf-8"" />
                    <title>Aggregated Sales Report</title>
                    <style>
                        table, td {
                            border: 1px solid black;
                        }
                        tr td:nth-child(1) {
                            width: 250px;
                        }

                        tr td:nth-child(2) {
                            width: 150px;
                            text-align: center;
                        }

                        tr td:nth-child(3) {
                            width: 150px;
                            text-align: center;
                        }

                        tr td:nth-child(4) {
                            width: 300px;
                        }

                        tr td:nth-child(5) {
                            width: 150px;
                            text-align: right;
                        }

                        .dateFormat {
                            background-color: lightgray;
                        }

                        tr.DailyReportHeader td {
                            background-color: grey;
                            text-align: center;
                            font-weight: bold;
                        }

                        tr.subtotal td:nth-child(1) {
                            text-align: right;
                        }

                        tr.subtotal td:nth-child(2) {
                            font-weight: bold;
                            text-align: right;
                        }

                        tfoot {
                            background-color: lightblue;
                        }

                        tfoot td:nth-child(1) {
                            text-align: right;
                        }

                        tfoot td:nth-child(2) {
                            text-align: right;
                            font-weight: bold;
                        }
                    </style>
                </head>
                <body>
                    <table>
                        <thead>
                            <tr><th colspan=""5"">Aggregated Sales Report</th></tr>
                        </thead>
                        <tbody>");

            var currentDate = startDate;
            decimal totalSum = 0;

            while (currentDate <= endDate)
            {
                decimal subTotalSum = 0;
                var currentDateSales = data.Sales.All().Where(s => s.Date == currentDate)
                        .Include(s => s.Product).Include(s => s.Product.Measure).Include(s => s.Supermarket.Name);

                if (currentDateSales.Any())
                {
                    htmlContent.AppendLine(@"<tr><td class=""dateFormat"" colspan=""5"">Date: " + currentDate.ToString("dd-MMM-yyyy") + "</td></tr>"
                                                           + @"<tr class=""DailyReportHeader"">
                                        <td>Product</td>
                                        <td>Quantity</td>
                                        <td>Unit Price</td>
                                        <td>Location</td>
                                        <td>Sum</td>
                                        </tr>");

                    foreach (var sale in currentDateSales)
                    {
                        htmlContent.AppendLine(@"<tr class=""ProductList"">")
                            .AppendLine("<td>" + sale.Product.Name + "</td>")
                            .AppendLine("<td>" + sale.Quantity + " " + sale.Product.Measure.Name + "</td>")
                            .AppendLine("<td>" + sale.UnitPrice + "</td>")
                            .AppendLine("<td>" + sale.Supermarket.Name + "</td>")
                            .AppendLine("<td>" + sale.Sum + "</td>");

                        subTotalSum += sale.Sum;

                    }

                    htmlContent.AppendLine(@"<tr class=""subtotal"">
                        <td colspan=""4"">Total sum for " + currentDate.ToString("dd-MMM-yyyy") + @":</td>
                        <td colspan=""1"">" + subTotalSum + "</td></tr>");
                }

                currentDate = currentDate.AddDays(1);
                totalSum += subTotalSum;
            }

            htmlContent.AppendLine(@"</tbody>
                <tfoot>
                    <tr>
                    <td colspan=""4"">Grand total:</td>
                    <td colspan=""1"">" + totalSum + @"</td>
                    </tr>
                    </tfoot>
                </table>
            </body>
            </html>");

            var pdfBytes = new NReco.PdfGenerator.HtmlToPdfConverter().GeneratePdf(htmlContent.ToString());
            File.WriteAllBytes(Path.GetFullPath(@".\..\..\..\..\..\Sales Report from " + startDate.ToString("dd-MMM-yyyy") + " to " + endDate.ToString("dd-MMM-yyyy") + ".pdf"), pdfBytes);

            Console.WriteLine("PDF Report Successfully generated!");
        }
Ejemplo n.º 2
0
        public IHttpActionResult PostPDFReport(PdfReportRequest pdfReportRequest)
        {
            var returnUrl = string.Empty;

            try
            {
                // Generate the filename
                Uri    baseUri       = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));
                string fileName      = $"Survey_Report_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.pdf";
                var    localFilePath = System.Web.HttpContext.Current.Server.MapPath("\\pdfreports\\" + fileName);

                //Phantom
                var htmlContent = pdfReportRequest.PrintHtml;
                var htmlToPdf   = new NReco.PdfGenerator.HtmlToPdfConverter();
                var pdfBytes    = htmlToPdf.GeneratePdf(htmlContent);

                //TODO: Remove this is to temporarily log
                htmlToPdf.LogReceived += (sender, a) => {
                    var logLine = a.Data;
                    _fileLogger.LogInfo(logLine);
                };

                File.WriteAllBytes(localFilePath, pdfBytes);

                returnUrl = $"{baseUri}pdfreports/{fileName}";
            }
            catch (Exception ex)
            {
                _fileLogger.LogError(ex);
            }

            return(Content(HttpStatusCode.OK, returnUrl));
        }
        public void ListarLinks(DateTime comp)
        {
            contador = comp.Month;

            while (contador > 0)
            {
                IWebElement pesquisa = driver.FindElement(By.LinkText(contador.ToString("00") + "/" + comp.Year.ToString("0000")));
                pesquisa.SendKeys(OpenQA.Selenium.Keys.Enter);


                ICollection <IWebElement> links   = driver.FindElements(By.TagName("a"));
                ICollection <IWebElement> valores = driver.FindElements(By.TagName("td"));
                for (int i = 0; i < links.Count() - 1; i++)
                {
                    links = driver.FindElements(By.TagName("a"));
                    var numDoc = links.ElementAt(i).Text;
                    links.ElementAt(i).Click();
                    string path  = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "aux.html";
                    string path2 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\GPS";
                    Directory.CreateDirectory(path2);
                    File.WriteAllText(path, driver.PageSource, Encoding.UTF8);
                    string html      = File.ReadAllText(path, Encoding.UTF8);
                    var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                    htmlToPdf.GeneratePdfFromFile(path, null, Path.GetFullPath(path2) + "\\" + contador.ToString("00") + comp.Year + "_" + numDoc + ".pdf");
                    driver.Navigate().Back();
                }

                driver.FindElements(By.TagName("a"));
                driver.FindElements(By.TagName("a")).LastOrDefault().Click();
                contador--;
            }

            driver.Close();
            Console.WriteLine("Finalizado");
        }
Ejemplo n.º 4
0
        private static bool GeneraPDF(string readContents, string _file_pdf_destino)
        {
            Boolean _valida = false;

            try
            {
                //string readContents;
                //using (StreamReader streamReader = new StreamReader(@_file_html, Encoding.UTF8))
                //{
                //    readContents = streamReader.ReadToEnd();
                //}
                //readContents = readContents.Replace("XXXXXXXX", "AAAAAAA");
                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                htmlToPdf.PageHeight = 180;
                htmlToPdf.PageWidth  = 140;
                var margins = new NReco.PdfGenerator.PageMargins();
                margins.Bottom        = 2;
                margins.Top           = 1;
                margins.Left          = 3;
                margins.Right         = 5;
                htmlToPdf.Margins     = margins;
                htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Portrait;
                htmlToPdf.Zoom        = 1F;
                htmlToPdf.Size        = NReco.PdfGenerator.PageSize.A4;
                var pdfBytes = htmlToPdf.GeneratePdf(readContents);
                File.WriteAllBytes(@_file_pdf_destino, pdfBytes);
                _valida = true;
            }
            catch
            {
                _valida = false;
            }
            return(_valida);
        }
Ejemplo n.º 5
0
        public JsonResponse HtmlToPdf(string html, string conNum)
        {
            try
            {
                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter()
                {
                    Quiet = false,
                };
                //htmlToPdf.WkHtmlToPdfExeName = "wkhtmltopdf.exe";
                htmlToPdf.CustomWkHtmlArgs = " --load-media-error-handling ignore ";
                htmlToPdf.LogReceived     += HtmlToPdf_LogReceived;
                var pdfBytes = htmlToPdf.GeneratePdf(html);

                string Path = Server.MapPath("~/Uploads/ConsignmentInvoices");
                if (!System.IO.Directory.Exists(Path))
                {
                    System.IO.Directory.CreateDirectory(Path);
                }
                string filePath = System.IO.Path.Combine(Path, conNum + "_Invoice.pdf");

                using (var fileStream = System.IO.File.Create(filePath))
                {
                    fileStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
                return(new JsonResponse()
                {
                    IsSucess = true, Result = filePath
                });
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 6
0
        private static bool GeneraPDF(string readContents, string _file_pdf_destino)
        {
            Boolean _valida = false;

            try
            {
                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                htmlToPdf.PageHeight = 242;
                htmlToPdf.PageWidth  = 170;
                var margins = new NReco.PdfGenerator.PageMargins();
                margins.Bottom        = 2;
                margins.Top           = 1;
                margins.Left          = 2;
                margins.Right         = 5;
                htmlToPdf.Margins     = margins;
                htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Portrait;
                htmlToPdf.Zoom        = 1F;
                htmlToPdf.Size        = NReco.PdfGenerator.PageSize.A4;
                var pdfBytes = htmlToPdf.GeneratePdf(readContents);
                //File.WriteAllBytes(@_file_pdf_destino, pdfBytes);
                _valida = true;
            }
            catch
            {
                _valida = false;
            }
            return(_valida);
        }
Ejemplo n.º 7
0
        public byte[] pdf(System.Text.StringBuilder head)
        {
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            byte[] pdfBytes = htmlToPdf.GeneratePdf(head.ToString());
            return(pdfBytes);
        }
Ejemplo n.º 8
0
        public JsonResponse HtmlToPdf(string html, string InvoiceNumber)
        {
            try
            {
                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                var pdfBytes  = htmlToPdf.GeneratePdf(html);

                string Path = Server.MapPath("~/Downloads/ClientInvoices");
                if (!System.IO.Directory.Exists(Path))
                {
                    System.IO.Directory.CreateDirectory(Path);
                }
                string filePath = System.IO.Path.Combine(Path, InvoiceNumber + ".pdf");

                using (var fileStream = System.IO.File.Create(filePath))
                {
                    fileStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
                return(new JsonResponse()
                {
                    IsSucess = true, Result = filePath
                });
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 9
0
        // render as PDF for download/print
        public void DailyDepositsPrint(DateTime fromDate, DateTime toDate)
        {
            ViewBag.fromDate = fromDate;
            ViewBag.toDate   = toDate;

            var footerHtml = $@"<div style=""text-align:center"">page <span class=""page""></span> of <span class=""topage""></span></div>";

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter
            {
                PageFooterHtml = footerHtml,
                Margins        = new NReco.PdfGenerator.PageMargins {
                    Bottom = 15, Top = 15, Left = 10, Right = 10
                },
                Size        = NReco.PdfGenerator.PageSize.Letter,
                Orientation = NReco.PdfGenerator.PageOrientation.Portrait
            };

            var htmlContent = RenderViewToString(ControllerContext, "~/Views/DailyPayments/DailyDepositsPrint.cshtml", GetDepositModel(fromDate, toDate), true);
            var pdfBytes    = htmlToPdf.GeneratePdf(htmlContent);

            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = string.Empty;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0} DailyDepositsPrint.pdf", fromDate.ToString("MM/dd/yy")));
            Response.BinaryWrite(pdfBytes);
            Response.Flush();
        }
Ejemplo n.º 10
0
        public void HtmlToPdf(string html, string filePath, bool isLandscape)
        {
            try
            {
                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter()
                {
                    Quiet = false,
                };
                //htmlToPdf.WkHtmlToPdfExeName = "wkhtmltopdf.exe";
                htmlToPdf.CustomWkHtmlArgs = " --load-media-error-handling ignore ";
                if (isLandscape)
                {
                    htmlToPdf.CustomWkHtmlArgs += " -O landscape ";
                }

                htmlToPdf.LogReceived += HtmlToPdf_LogReceived;
                var pdfBytes = htmlToPdf.GeneratePdf(html);

                using (var fileStream = System.IO.File.Create(filePath))
                {
                    fileStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 11
0
        public HttpResponseMessage getPDF(string RegistroClinicoId)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);

            try
            {
                var service  = new PDFService();
                var registro = service.PDFRegistroHistoria(RegistroClinicoId);


                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                var pdfBytes  = htmlToPdf.GeneratePdf(registro);

                var stream = new MemoryStream(pdfBytes);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType        = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "RegistroClinico.pdf"
                };
            }
            catch (Exception ex)
            {
                // response.State = false;
                //  response.Message = ex.Message;
            }

            return(response);
        }
Ejemplo n.º 12
0
        public void SendMailToUser(string generatedPdfTemplateString, string IpMailID, string subject, string body, string pdfName)
        {
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes  = htmlToPdf.GeneratePdf(generatedPdfTemplateString);

            MailMessage mailMessage = new MailMessage(FromMailID, IpMailID)
            {
                Subject    = subject,
                Body       = body,
                IsBodyHtml = true
            };

            //mailMessage.CC.Add(_ccMailID);
            mailMessage.Attachments.Add(new Attachment(new MemoryStream(pdfBytes), pdfName));
            SmtpClient smtp = new SmtpClient
            {
                Host      = "smtp.gmail.com",
                EnableSsl = true
            };

            NetworkCredential networkCredentialObj = new NetworkCredential
            {
                UserName = FromMailID,
                Password = MailPassword
            };

            smtp.UseDefaultCredentials = true;
            smtp.Credentials           = networkCredentialObj;
            smtp.Port = 587;
            smtp.Send(mailMessage);
        }
Ejemplo n.º 13
0
        private void BtnClick_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(TxtURL.Text);
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.GeneratePdfFromFile("TxtURL.Text", null, "export.pdf");
        }
Ejemplo n.º 14
0
        //protected void btnprint_Click1(object sender, EventArgs e)
        //{
        //    try
        //    {


        //        string filname = h3Exmaname.InnerText.Replace(" ","").Trim() + ".pdf";

        //        PdfPrintOptions printopt = new PdfPrintOptions();
        //        printopt.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
        //        string csspath = Server.MapPath("~/admin/css/AdminStyle.css");
        //        var uri = new System.Uri(csspath);
        //        var converted = uri.AbsoluteUri;
        //        printopt.CustomCssUrl = uri;
        //        HtmlToPdf Renderer = new IronPdf.HtmlToPdf(printopt);
        //        string html = divquestion.InnerHtml;
        //        Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;

        //        var PDF = Renderer.RenderHtmlAsPdf(html, uri);

        //        string watermarktext = "<label style=font-family:ravel;>APURVA STAR PLUSE COMPUTER CLASSES</label> <br> FF - 6, Vishwash City-1,Shayonacity,Chanakyapuri, Ghatlodia, Ahmedabad, Gujarat 380061 <br>Email: apurvastarpulse @yahoo.com <br>Mobile : 9978532833 ";
        //        PDF.WatermarkAllPages("<h2 style='color:blue'>" + watermarktext + "</h2>", IronPdf.PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);

        //        #region header
        //        SimpleHeaderFooter head = new SimpleHeaderFooter();
        //        head.CenterText = h3Exmaname.InnerText;
        //        head.FontFamily = "Ravel";
        //        head.DrawDividerLine = true;
        //        head.FontSize = 14;
        //        #endregion
        //        PDF.AddHeaders(head, false);

        //        SimpleHeaderFooter Footer = new SimpleHeaderFooter()
        //        {
        //            LeftText = "{date} {time}",
        //            RightText = "Page {page} of {total-pages}",
        //            DrawDividerLine = true,
        //            FontSize = 8
        //        };
        //        PDF.AddFooters(Footer, false);
        //        //Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
        //        //or



        //        string uploadPath = Server.MapPath("~/QuestionPdf");
        //        if (!Directory.Exists(uploadPath))
        //        {
        //            Directory.CreateDirectory(uploadPath);
        //        }
        //        PDF.SaveAs(Path.Combine(uploadPath, filname));

        //        Response.ContentType = "application/pdf";
        //        Response.AppendHeader("Content-Disposition", "attachment; filename="+ filname);
        //        Response.TransmitFile(Path.Combine(uploadPath, filname.Trim()));
        //        Response.End();

        //    }
        //    catch (Exception ex)
        //    {
        //        com.Loginsert(HttpContext.Current.Request.Url.AbsolutePath, "btnprint_Click1", ex.StackTrace, ex.Message);
        //    }

        //}

        protected void btnprint_Click1(object sender, EventArgs e)
        {
            try
            {
                string filname = h3Exmaname.InnerText.Replace(" ", "").Trim() + ".pdf";

                PdfPrintOptions printopt = new PdfPrintOptions();
                printopt.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
                string csspath   = Server.MapPath("~/admin/css/AdminStyle.css");
                var    uri       = new System.Uri(csspath);
                var    converted = uri.AbsoluteUri;
                printopt.CustomCssUrl = uri;
                HtmlToPdf Renderer = new IronPdf.HtmlToPdf(printopt);
                string    html     = divquestion.InnerHtml;

                var htmlContent = String.Format(html, DateTime.Now);
                var htmlToPdf   = new NReco.PdfGenerator.HtmlToPdfConverter();
                var pdfBytes    = htmlToPdf.GeneratePdf(htmlContent);

                htmlToPdf.GeneratePdf(htmlContent, null, "export.pdf");
            }
            catch (Exception ex)
            {
                com.Loginsert(HttpContext.Current.Request.Url.AbsolutePath, "btnprint_Click1", ex.StackTrace, ex.Message);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Create Pdf method
 /// </summary>
 /// <param name="distributorCartData"></param>
 public static byte[] CreateProductPDF(DataTable distributorCartData, int inventoryType)
 {
     try
     {
         var html      = SettingsKeyInfoProvider.GetValue($@"{SiteContext.CurrentSiteName}.KDA_DistributorCartPDFHTML");
         var groupCart = distributorCartData.AsEnumerable().GroupBy(x => x["ShoppingCartID"]).ToList();
         var PDFBody   = "";
         groupCart.ForEach(cart =>
         {
             PDFBody     += CreateCarOuterContent(cart.FirstOrDefault(), SiteContext.CurrentSiteName);
             var cartData = cart.ToList();
             PDFBody      = PDFBody.Replace("{INNERCONTENT}", CreateCartInnerContent(cartData, SiteContext.CurrentSiteName, inventoryType));
         });
         html = html.Replace("{OUTERCONTENT}", PDFBody);
         NReco.PdfGenerator.HtmlToPdfConverter PDFConverter = new NReco.PdfGenerator.HtmlToPdfConverter();
         PDFConverter.License.SetLicenseKey(SettingsKeyInfoProvider.GetValue("KDA_NRecoOwner", SiteContext.CurrentSiteID), SettingsKeyInfoProvider.GetValue("KDA_NRecoKey", SiteContext.CurrentSiteID));
         PDFConverter.LowQuality = SettingsKeyInfoProvider.GetBoolValue("KDA_NRecoLowQuality", SiteContext.CurrentSiteID);
         return(PDFConverter.GeneratePdf(html));
     }
     catch (Exception ex)
     {
         EventLogProvider.LogInformation("CartPDFHelper", "CreateProductPDF", ex.Message);
         return(null);
     }
 }
Ejemplo n.º 16
0
        public static byte[] Generate(string html, string css)
        {
            var doc = $"{c_head} {html} <style>{css}</style>";

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            return(htmlToPdf.GeneratePdf(doc));
        }
Ejemplo n.º 17
0
        public void GeneratePdfBytes()
        {
            var htmlContent = GetHtmlPdf();
            var htmlToPdf   = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes    = htmlToPdf.GeneratePdf(htmlContent);

            Save(pdfBytes);
        }
Ejemplo n.º 18
0
        private string GetPdf(string html)
        {
            var htmlContent      = html;
            var htmlToPdf        = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes         = htmlToPdf.GeneratePdf(htmlContent);
            var base64EncodedPdf = System.Convert.ToBase64String(pdfBytes);

            return(base64EncodedPdf);
        }
Ejemplo n.º 19
0
        protected void Imprimir(object sender, EventArgs e)
        {
            var htmlContent = String.Format("<body>Tiquete de Cine: {0}</body>",
                                            DateTime.Now);
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes  = htmlToPdf.GeneratePdf(htmlContent);

            htmlToPdf.GeneratePdfFromFile("Ticket.html/", null, "export.pdf");
        }
Ejemplo n.º 20
0
        public async Task sendInvoiceEmail(string invoiceHtml, string userEmail, string path, string pdfPathToSave)
        {
            try
            {
                //var order = GetOrderById(orderId);

                //order.PaymentMethodName = Utility.GetPaymentMethodName(order.PaymentMethod);

                //string invoiceHtml = MvcControllerCustom.RenderViewToString("Home", "~/Views/Home/GenerateInvoiceReport.cshtml", order, contextBase);

                //string path = @"~/Content/bootstrap.min.css";
                //path = HttpContext.Current.Server.MapPath(path);
                if (File.Exists(path))
                {
                    string readText = File.ReadAllText(path);
                    if (!string.IsNullOrWhiteSpace(readText))
                    {
                        invoiceHtml = invoiceHtml.Replace(".testClass {}", readText);
                    }
                }
                NReco.PdfGenerator.HtmlToPdfConverter pdfGenerator = new NReco.PdfGenerator.HtmlToPdfConverter();
                byte[] pdfDocument = pdfGenerator.GeneratePdf(invoiceHtml);

                var url = SaveFile.SaveFileFromBytes(pdfDocument, "PDFReports", pdfPathToSave);

                string       subject = "New Order Has been placed - " + EmailUtil.FromName;
                const string body    = "Please find attached Invoice file";

                var smtp = new SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(EmailUtil.FromMailAddress.Address, EmailUtil.FromPassword)
                };

                var message = new MailMessage(EmailUtil.FromMailAddress, new MailAddress(userEmail))
                {
                    Subject = subject,
                    Body    = body + " Invoice Attached"
                };
                var AdminEmail = BasketSettings.GetAdminEmailForOrders();
                if (AdminEmail != null)
                {
                    message.To.Add(new MailAddress(AdminEmail));
                }
                Attachment attachment = new Attachment(url);
                message.Attachments.Add(attachment);
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                Utility.LogError(ex);
            }
        }
Ejemplo n.º 21
0
        public async Task <byte[]> GetPdfReco(TemplateModel model)
        {
            var documentContent = await _templateService.RenderTemplateAsync("~/PdfTemplate/Pdf.cshtml", model);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes  = htmlToPdf.GeneratePdf(documentContent);

            return(pdfBytes);
        }
Ejemplo n.º 22
0
        private void GerarArquivoPDF(string html, string nomeArquivo)
        {
            var pdf = new NReco.PdfGenerator.HtmlToPdfConverter().GeneratePdf(html);

            using (FileStream fs = new FileStream(nomeArquivo, FileMode.Create))
            {
                fs.Write(pdf, 0, pdf.Length);
                fs.Close();
            }
        }
        public static HttpPostedFileBase Create(string ansattnavn, string personnr, string formaal, string stilling, string stillingstype, string oppdragsgiver, string kontaktinfo, string stedDato)
        {
            var templateText = Maltekst.HentMalTekst("VedleggTilSøknadOmPolitiattest");

            var htmlNotat = string.Format(templateText, ansattnavn, personnr, formaal, stilling, stillingstype, LovhjemmelListe.Where(f => f.Navn.Equals(formaal)).FirstOrDefault().Hjemmel, oppdragsgiver, kontaktinfo, stedDato);

            var pdfBytes = new NReco.PdfGenerator.HtmlToPdfConverter().GeneratePdf(htmlNotat); // lag pdf-filen

            return(new NotatFil(pdfBytes, ""));
        }
Ejemplo n.º 24
0
        private static void GenerateReportFile <TModel>(string templateContent, string outputFile, TModel model, ILogger logger, bool showReport)
        {
            const string GridStylesCss = "GridStyles";
            var          findString    = $"<!-- import {GridStylesCss}.css -->";

            if (templateContent.Contains(findString))
            {
                var importContent  = TemplateResources.GridStyles.Replace("@", "@@");
                var replaceContent = $"<style>\r\n{importContent}\r\n</style>";
                templateContent = templateContent.Replace(findString, replaceContent);
            }

            var config = new TemplateServiceConfiguration
            {
                DisableTempFileLocking = true,
                Language        = Language.CSharp,
                CachingProvider = new DefaultCachingProvider(t => { })
            };

            var service = RazorEngineService.Create(config);

            var templateKey = System.IO.Path.GetFileNameWithoutExtension(outputFile);

            service.Compile(templateContent, templateKey);

            var htmlContent = service.Run(templateKey, null, model);

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter
            {
                Grayscale = false,
                Margins   = new NReco.PdfGenerator.PageMargins
                {
                    Bottom = 4,
                    Top    = 4,
                    Left   = 5,
                    Right  = 5
                }
            };

            // To write to PDF
            outputFile = outputFile + ".pdf";
            htmlToPdf.GeneratePdf(htmlContent, null, outputFile);

            // To write to HTML
            //outputFile = outputFile + ".htm";
            //System.IO.File.WriteAllText(outputFile, htmlContent);


            logger.WriteInfo($"Generated report at: {outputFile}");

            if (showReport)
            {
                Process.Start(outputFile);
            }
        }
Ejemplo n.º 25
0
        public bool ConvertHtmlToPdf(string url, string storePath)
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(storePath))
            {
                return(false);
            }
            var pdfGenerator = new NReco.PdfGenerator.HtmlToPdfConverter();

            pdfGenerator.GeneratePdfFromFile(url, null, storePath);
            return(true);
        }
Ejemplo n.º 26
0
        public void StampaFinali(List <AtletaEliminatorie> campo1,
                                 List <AtletaEliminatorie> campo2)
        {
            ProgressBar p = new ProgressBar();

            String temp;
            String HtmlReport = FormattedString.header;

            #region campo1
            p.InizializeProgressBar(1, campo1.Count + campo2.Count + 2);

            p.Show();
            int i = 1;

            temp  = "<A NAME=\"table1\"><H1>Campo 1</H1></A>";
            temp += FormattedString.match.Replace("##a##", campo1[0].Cognome + " " + campo1[0].Nome);
            temp  = temp.Replace("##b##", campo1[1].Cognome + " " + campo1[1].Nome);
            temp  = temp.Replace("##INCONTRO##", "Finale Primo e Secondo Posto");
            p.IncrementProgressBar(i++);

            temp += FormattedString.footer;

            HtmlReport += temp;
            HtmlReport += "<div style=\"page-break-after:always\"></div>";
            p.IncrementProgressBar(i + 1);

            #endregion

            #region campo2
            temp  = "<A NAME=\"table1\"><H1>Campo 2</H1></A>";
            temp += FormattedString.match.Replace("##a##", campo2[0].Cognome + " " + campo2[0].Nome);
            temp  = temp.Replace("##b##", campo2[1].Cognome + " " + campo2[1].Nome);
            temp  = temp.Replace("##INCONTRO##", "Finale Terzo e Quarto Posto");
            p.IncrementProgressBar(i++);

            temp += FormattedString.footer;

            HtmlReport += temp;
            HtmlReport += "</BODY></HTML>";
            p.IncrementProgressBar(i + 1);

            p.Close();
            p.Dispose();

            #endregion

            var htmlContent = String.Format(HtmlReport, DateTime.Now);
            var htmlToPdf   = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes    = htmlToPdf.GeneratePdf(htmlContent);

            System.IO.File.WriteAllBytes(".\\PDF\\IncontriDirettiFinali.pdf", pdfBytes);

            Process.Start(".\\PDF\\IncontriDirettiFinali.pdf");
        }
        public ActionResult ExportToPdf(Report report)
        {
            var htmlToConvert      = RenderViewToString("Report", GenerateDataReport(report));
            var htmlToPdfConverter = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdfConverter.PdfToolPath = Server.MapPath("~/Uploads/Reports/");
            var        pdfBytes   = htmlToPdfConverter.GeneratePdf(htmlToConvert);
            FileResult fileResult = new FileContentResult(pdfBytes, "application/pdf");

            fileResult.FileDownloadName = "Report.pdf";
            return(fileResult);
        }
 public override void OnResultExecuted(ResultExecutedContext filterContext)
 {
     if (filterContext.RequestContext.HttpContext.Request.QueryString.GetValues("convert") != null)
     {
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         filterContext.RequestContext.HttpContext.Response.Clear();
         filterContext.RequestContext.HttpContext.Response.ContentType = "application/pdf";
         htmlToPdf.GeneratePdfFromFile(
             filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri.Split('?')[0], null,
             filterContext.RequestContext.HttpContext.Response.OutputStream);
     }
     base.OnResultExecuted(filterContext);
 }
Ejemplo n.º 29
0
        public static string createPdf(string HTML, string attachFilenamePrefix)
        {
            var outputPath = AppDomain.CurrentDomain.BaseDirectory + "DataFiles\\";

            System.IO.Directory.CreateDirectory(outputPath);
            var outputFile = outputPath + attachFilenamePrefix + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";

            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();

            htmlToPdf.GeneratePdf(HTML, null, outputFile);

            return(outputFile);
        }
Ejemplo n.º 30
0
 private void BtnClick_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         MessageBox.Show(TxtURL.Text);
         var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
         htmlToPdf.GeneratePdfFromFile(TxtURL.Text, null, "export.pdf");
     }
     catch (Exception TxtURL)
     {
         MessageBox.Show("The URL you have entered is invalid" + TxtURL.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
 }
Ejemplo n.º 31
0
        public void toPDFPaketi()
        {
            var htmlContent = String.Format("<body>Hello world: {0}</body>",
                                            DateTime.Now);
            var pdfBytes = new NReco.PdfGenerator.HtmlToPdfConverter().GeneratePdfFromFile("http://localhost:58499/Korisnici/NarudzbePaketa", null);

            Response.ContentType     = "application/pdf";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "Inline; filename=TEST.pdf");
            Response.BinaryWrite(pdfBytes);
            Response.Flush();
            Response.End();
        }
Ejemplo n.º 32
0
        public ActionResult PDF(string Facultet, string Gruppa, string Disciplina)
        {
            try
            {
                var    htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                string nazvanie  = "";
                htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
                int GruppaID     = int.Parse(Gruppa);
                int DisciplinaID = int.Parse(Disciplina);

                string GruppaName =
                    (from g in contextDB.tableGrupp
                     where g.ID == GruppaID
                     select g.Name).First().ToString();

                string DisciplinaName =
                    (from g in contextDB.tableDisciplin
                     where g.ID == DisciplinaID
                     select g.Name).First().ToString();

                string Host   = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf("Teacher") - 1);
                string Zapros = Url.Action("ProsmotrAttVedomosti", "Teacher", new { Facultet = Facultet, Gruppa = Gruppa, Disciplina = Disciplina });
                string put    = Host + Zapros;
                int    rol    = 0;
                try
                {
                    rol =
                        (from r in contextDB.teachersAccounts
                         where r.Login == User.Identity.Name
                         select r.Role_ID).First();
                }
                catch
                {
                }
                if (rol == 2)
                {
                    byte[] pdfBytes = htmlToPdf.GeneratePdfFromFile(put, null);
                    Response.AddHeader("Content-Disposition", "inline; filename=" + nazvanie);
                    return(File(pdfBytes, "application/pdf"));
                }
                else
                {
                    return(View("NotFound"));
                }
            }
            catch
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 33
0
        private void GeneratePDF(object obj)
        {
            var htmlContent = obj.ToString();
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
            var filename = "Question.pdf";

            var tempFolder = System.IO.Path.GetTempPath();
            filename = System.IO.Path.Combine(tempFolder, filename);
            System.IO.File.WriteAllBytes(filename, pdfBytes);
            System.Diagnostics.Process.Start(filename);
        }
Ejemplo n.º 34
0
 public byte[] MontaBytesPDF(bool convertLinhaDigitavelToImage = false)
 {
     var converter = new NReco.PdfGenerator.HtmlToPdfConverter();
     if (!string.IsNullOrEmpty(this.PdfToolPath)) {
         converter.PdfToolPath = this.PdfToolPath;
     }
     return converter.GeneratePdf(this.MontaHtmlEmbedded(convertLinhaDigitavelToImage, true));
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Lista de Boletos, objetos do tipo
 /// BoletoBancario
 /// </summary>
 /// <param name="boletos">Lista de Boletos, objetos do tipo BoletoBancario</param>
 /// <param name="tituloNaView">Título Que aparecerá na Aba do Navegador</param>
 /// <param name="CustomSwitches">Custom WkHtmlToPdf global options</param>
 /// <param name="tituloPDF">Título No Início do PDF</param>
 /// <param name="PretoBranco">Preto e Branco = true</param>
 /// <param name="convertLinhaDigitavelToImage">bool Converter a Linha Digitavel Em Imagem</param>
 /// <returns>byte[], Vetor de bytes do PDF</returns>
 public byte[] MontaBytesListaBoletosPDF(List<BoletoBancario> boletos, string tituloNaView = "", string CustomSwitches = "", string tituloPDF = "", bool PretoBranco = false, bool convertLinhaDigitavelToImage = false)
 {
     StringBuilder htmlBoletos = new StringBuilder();
     htmlBoletos.Append("<html><head><title>");
     htmlBoletos.Append(tituloNaView);
     htmlBoletos.Append("</title><style type='text/css' media='screen,print'>");
     htmlBoletos.Append(".break{ display: block; clear: both; page-break-after: always;}");
     htmlBoletos.Append("</style></head><body>");
     if (!string.IsNullOrEmpty(tituloPDF))
     {
         htmlBoletos.Append("<br/><center><h1>");
         htmlBoletos.Append(tituloPDF);
         htmlBoletos.Append("</h1></center><br/>");
     }
     foreach (BoletoBancario boleto in boletos)
     {
         htmlBoletos.Append("<div class='break'>");
         htmlBoletos.Append(boleto.MontaHtmlEmbedded(convertLinhaDigitavelToImage, true));
         htmlBoletos.Append("</div>");
     }
     htmlBoletos.Append("</body></html>");
     var converter = new NReco.PdfGenerator.HtmlToPdfConverter()
     {
       CustomWkHtmlArgs = CustomSwitches,
       Grayscale = PretoBranco
     };
     if (!string.IsNullOrEmpty(this.PdfToolPath)) {
         converter.PdfToolPath = this.PdfToolPath;
     }
     return converter.GeneratePdf(htmlBoletos.ToString());
 }
        public string GenertePDF(string pdfData)
        {
            StringWriter sw = new StringWriter();
            string css = System.IO.File.ReadAllText(Server.MapPath("~/Content/bootstrap.min.css"));
            string responsive = System.IO.File.ReadAllText(Server.MapPath("~/Content/responsive.css"));
            string html = "<html><head><style>"
                + css
                + "#header{display:none;}#printbtn{display:none;}@media screen and (max-width:768px){body{font-size:11px!important;}#mainDiv{font-size:11px!important;}.s-p-sign>.p-sign{min-width: 22%;padding: 8px 4px; margin-right:2px; font-size: 10px;text-align: center;word-wrap: break-word;width: auto;}.legendmilestone2 {font-weight: normal; font-size: 11px;padding: 8px 4px; margin-right:2px; margin-top:10px;display:inline-block;}.fa-stop{transform: rotate(45deg);}}</style></head><body >"
                + pdfData
                + "</body></html>";

            string path = Server.MapPath("~/Temp/PDF" + Guid.NewGuid().ToString().Substring(0, 6) + ".html");

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(html);
                fs.Write(info, 0, info.Length);

            }
            string pdfFileName = "ProjectSummaryDetail" + Guid.NewGuid().ToString().Substring(0, 6) + ".pdf";
            string filePath = Server.MapPath("~/Temp/" + pdfFileName);
            StringBuilder sb = new StringBuilder();
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
            var coverHTML = "";
            htmlToPdf.GeneratePdfFromFile(path, coverHTML, filePath);
            System.IO.File.Delete(path);
            return filePath;
        }
Ejemplo n.º 37
0
        //Burdan pdf kaydettirilip mail gönderilecek
        public ActionResult SavePdf(string mailTemplate,int id)
        {
            try
            {
                //string mailTemplate = (new MailTemplateUtil()).GetMailTemplate("teklif");
                //mailTemplate = (new MailTemplateUtil()).CustomFormat(mailTemplate, new string[] { });
                //var htmlContent = String.Format("<body>Hello world: {0}</body>",DateTime.Now);

                mailTemplate = System.Uri.UnescapeDataString(mailTemplate);

                var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                var pdfBytes1 = htmlToPdf.GeneratePdf(mailTemplate);
                string targetFolder = Server.MapPath("/Content/pdf");
                string targetPath = Path.Combine(targetFolder, id.ToString() + ".pdf");
                //file.SaveAs(targetPath);

                System.IO.File.WriteAllBytes(targetPath, pdfBytes1);
            }
            catch (Exception)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }
Ejemplo n.º 38
0
        /// <summary>
        ///   Restituisce la conversione in PDF del file di CHANGELOG, leggedo direttamente il file
        ///   di testo presente alla radice del servizio.
        /// </summary>
        /// <returns>Il file di CHANGELOG in formato PDF.</returns>
        public virtual async Task<HttpResponseMessage> GetChangelogPdf()
        {
            var changelogPath = string.Empty;
            var changelogText = string.Empty;

            try
            {
                changelogPath = PortableEnvironment.MapPath("~/CHANGELOG.md");
                using (var changelogStream = File.OpenRead(changelogPath))
                using (var streamReader = new StreamReader(changelogStream))
                {
                    changelogText = await streamReader.ReadToEndAsync();
                }

                // Genero l'HTML partendo dal Markdown.
                var md = new MarkdownSharp.Markdown();
                var changelogHtml = md.Transform(changelogText);

                // Genero il PDF partendo dall'HTML.
                var pdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                var changelogPdf = pdf.GeneratePdf(changelogHtml);

                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(changelogPdf);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = $"{CaravanCommonConfiguration.Instance.AppName}-CHANGELOG.pdf";
                return response;
            }
            catch (Exception ex)
            {
                var errorMsg = $"CHANGELOG file at path '{changelogPath}' could not be read or processed";
                throw new HttpException(HttpStatusCode.NotFound, errorMsg, ex, new HttpExceptionInfo
                {
                    UserMessage = "CHANGELOG file is currently not available. Please retry later.",
                    ErrorCode = CaravanErrorCodes.CVE99998
                });
            }
        }      
Ejemplo n.º 39
-1
		private string GetPdf(string html)
		{
			var htmlContent = html;
			var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
			var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
			var base64EncodedPdf = System.Convert.ToBase64String(pdfBytes);

			return base64EncodedPdf;
		}