Requirements: On ajax post, save data to database, generate invoice and download as PDF file. There are many open source packages available to generate PDF file. So I’m not going describe that using which paid/free package is used to generate PDF file. I am going to describe the trick how can download the generated PDF file without saving on hard drive.

HomeController.CS


public class HomeController : Controller
    {
        public ActionResult Index()
        {         
            return View();
        }

        public ActionResult Download()
        {
            //using (var ms = new MemoryStream())
            //{
                //using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                //{
                //    PdfWriter.GetInstance(document, ms);
                //    document.Open();
                //    document.Add(new Paragraph("HelloWorld"));
                //    document.Close();
                //}
                //Response.Clear();
                ////Response.ContentType = "application/pdf";
                //Response.ContentType = "application/octet-stream";
                //Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
                //Response.Buffer = true;
                //Response.Clear();
                //var bytes = ms.ToArray();
                //Response.OutputStream.Write(bytes, 0, bytes.Length);
                //Response.OutputStream.Flush();
           // }

            return View();
        }

        [HttpPost]
        public ActionResult Save()
        {

// write code here to save the data in database. 
            var fName = string.Format("MYPDF-{0}.pdf", DateTime.Now.ToString("s"));
            using (var ms = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                {
                    PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph("HelloWorld"));
                    document.Close();
                }

                var bytes = ms.ToArray();              
                Session[fName] = bytes;
            }

            return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
            //return View();
        }
         public ActionResult DownloadInvoice(string fName)
         {
             var ms =  Session[fName] as byte[] ;
             if(ms == null)
                 return new EmptyResult();
             Session[fName] = null;
             return File(ms, "application/octet-stream", fName);
         }
    }

Index.cshtml

 <input type="button" id="btnSave" value="Save & Download PDF" />
 
 $(document).ready(function () {
 $("#btnSave").click(function () {
 $.ajax({
 type: 'POST',
 url: "/home/save",
 dataType: "json",
 success: function (resultData)
 {
 if (resultData.success) {
 window.location = "/home/DownloadInvoice" + "?fName=" + resultData.fName;
 }
 }
 });
 })
 })
 

On ajax post method, data will save into the database. Here Save is a post method. Check the HomeController.CS file. Generate file and save an array of byte in Session. In JSON result, send the name of file. Ajax post method retrieve the data and using window.location send request to server to download the file. Now, check DownloadInvoice method in HomeController.cs.

Thank you for reading this post.