How to send PDF as email attachment in asp.net mvc C#
Microsoft Net Framework

How to send PDF as email attachment in asp.net mvc C#

Controller code:


using ServiceProvider.EF;
using ServiceProvider.WebUI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceProvider.Common;
using System.Configuration;
using System.Text;
using SelectPdf;
using ServiceProvider.WebUI.App_Start;

namespace ServiceProvider.WebUI.Controllers
{
    [SessionExpire]
    public class PaymentController : Controller
    {
        private ServiceProviderDatabasev5Entities5 db = new ServiceProviderDatabasev5Entities5();

        // GET: Payment
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SendEmail(int id = 0)
        {
            var list = db.PrintInvoiceDetails2(id).ToList();
            return View(list);
        }
        public ActionResult SendInvoice(int id = 0)
        {
            var invoiceDetail = db.PrintInvoiceDetails2(id).FirstOrDefault();
            var eo = new EmailMessageObject();
            var strmailto = ConfigurationManager.AppSettings["adminemail"].ToString();
            String clientemail = invoiceDetail.Email;
            eo.CCEmail = strmailto.Split(",".ToCharArray());
            eo.MailTo = clientemail.Split(",".ToCharArray());
            eo.FromEmail = ConfigurationManager.AppSettings["ContactEmail"];
            eo.Subject = "ServiceProvider.PK - Invoice" + DateTime.Now.Month.ToString();

            // string url = BusinessManager.FullyQualifiedApplicationPath + "Account/Confirmation/";
            StringBuilder sb = new StringBuilder();

            var invitems = db.InvoiceItems.Where(w => w.InvoiceID == id);
            decimal gt = 0;
            int sn = 0;
            foreach (var item in invitems)
            {
                sn++;
                decimal total = item.Quantity * item.Price;

                gt = gt + total;
                sb.Append("<tr>");
                sb.Append("<td class='no'>");
                /// sb.Append(item.InvoiceItemID);
                sb.Append(sn.ToString());
                sb.Append("</td>");

                sb.Append("<td class='desc'>");
                sb.Append(item.ItemName);
                sb.Append("</td>");

                sb.Append("<td class='unit'>");
                sb.Append(BusinessManager.CurrencySymbol() + item.Price);
                sb.Append("</td>");
                sb.Append("<td class='qty'>");
                sb.Append(item.Quantity);
                sb.Append("</td>");

                sb.Append("<td class='total'>");
                sb.Append(BusinessManager.CurrencySymbol() + total);
                sb.Append("</td>");
                sb.Append("</tr>");

            }

            String msgbody = System.IO.File.ReadAllText(Server.MapPath("~/EmailTemplate/invemail.html"));
            var strBody = msgbody
                 .Replace("__InvoiceID__", Convert.ToString(invoiceDetail.InvoiceID))
                .Replace("__UserName__", invoiceDetail.Name)
                .Replace("__Email__", invoiceDetail.Email)
                .Replace("__CreatedDate__", invoiceDetail.CreatedDate.ToShortDateString())
                .Replace("__DueDate__", invoiceDetail.DueDate.ToShortDateString())
                .Replace("__tr__", sb.ToString())
                .Replace("__GTotal__", gt.ToString())
                .Replace("__Address__", invoiceDetail.Address);
            if (invoiceDetail.InvoiceStatusID==2)
            {
                string pd = "Paid Date:" + Convert.ToDateTime(invoiceDetail.PaidDate).ToShortDateString();
                strBody = strBody.Replace("__status__", "Paid"); // __DueDate__
                strBody = strBody.Replace("___paiddatetime__", pd);

            }
            else
            {
                string dd = "Due Date:" + invoiceDetail.DueDate.ToShortDateString();
                strBody = strBody.Replace("__status__", "Pending");
                strBody = strBody.Replace("___paiddatetime__", dd);

            }

            eo.Body = strBody;

            var mylist = CreatePDFDocument(strBody);
            if (mylist.Any())
            {
                eo.AttachmentFiles = mylist;
            }

            BusinessManager.SendEmail(ref eo);

            TempData["SuccessMessage"] = "Your Invoice is successfully send to Customer";
            return RedirectToAction("Index", "InvoiceManager");
        }

        public List<string> CreatePDFDocument(string body)
        {

            HtmlToPdf converter = new HtmlToPdf();
            //PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), "A6", true);
            PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), "A4", true);


            PdfPageOrientation pdfOrientation =
               (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
               "Portrait", true);  // Landscape   Portrait
            converter.Options.PdfPageSize = pageSize;
            //  converter.Options.PdfPageOrientation = pdfOrientation; 
            ////  converter.Options.WebPageWidth = 595;
            //  converter.Options.WebPageHeight = 300;
            //////   converter.Options.MarginTop =0;
            //    converter.Options.MarginLeft = 0;
            //  converter.Options.MarginRight = 0;


            converter.Options.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
            converter.Options.AutoFitWidth = HtmlToPdfPageFitMode.AutoFit;


            PdfDocument doc = converter.ConvertHtmlString(body);
            var random = new Random();

            var fileName = "Invoice_SPPK" + DateTime.Now.ToFileTimeUtc().ToString() + ".pdf";

            string path = String.Format(AppDomain.CurrentDomain.BaseDirectory + "UploadedStuff\\" + fileName);
            var bytes = doc.Save(); //convert doc to byte array 2480px*1064
                                    //doc.Save(path);

            System.IO.File.WriteAllBytes(path, bytes);
            var listString = new List<string>();
            listString.Add(path);
            //    Session[SessionItemKeys.PDFFile.ToString()] = listString;


            return listString;

        }


        public ActionResult SendSMS(int id=0)
        {
            var list = db.PrintInvoiceDetails(id).ToList();
            return View(list);
        }

    }
}

- Html View

Share This with your friend by choosing any social account


Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM