1

I have two action methods in my Controller class:

  1. DetailsAll: to get some data and display in the view
  2. SaveAsPDF: Called on windows.load of DetailsAll.cshtml which should save DetailsAll view as pdf

My issue is in SaveAsPDF Action method. Here I am trying to use Rotativa ActionAsPdf and subsequently BuildFile methods to generate and save the PDF. However, when executing the line "BuildFile", it is not hitting the breakpoint in my DetailsAll Action method, subsequently causing the PDF to be generated blank.

Could you please help where I am going wrong?

    [HttpGet]
    public ActionResult DetailsAll()
    {
        var selectionBuilder = builderFactory.GetGeocodeReportSelectionViewModelBuilder();
        var companyList = selectionBuilder.Build();

        List<GeocodeReportViewModel> viewModel = new List<GeocodeReportViewModel>();
        foreach(SelectListItem record in companyList.Companies)
        {
            var builder = builderFactory.GetGeocodeReportViewModelBuilder(int.Parse(record.Value));
            viewModel.Add(builder.Build());
        }
        var model = new AllGeocodeReportViewModel
        {
            GeocodeReports = viewModel
        };
        return View(model);
    }

    [HttpGet]
    public string SaveAsPDF()
    {
        var report = new ActionAsPdf("DetailsAll")
        {
            FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMYY") + ".pdf",
            PageSize = Size.A4,
            PageOrientation = Orientation.Landscape,
            PageMargins = { Left = 1, Right = 1 }
        };
        byte[] pdf = report.BuildFile(ControllerContext);
        System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
        return "true";
    }


   
Divya
  • 11
  • 3

1 Answers1

0

Finally found the issue after extensive search. I need to send Authentication cookies along with the BuildFile request for this to work. Added the below code and it generates PDF correctly now:

 public void SaveAsPDF()
    {
        var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
        var report = new ActionAsPdf("DetailsAll")
        {
            FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMyy") + ".pdf",
            PageSize = Size.A4,
            PageOrientation = Orientation.Portrait,
            PageMargins = { Left = 3, Right = 3 },
            FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName,
            Cookies = cookies
        };
        byte[] pdf = report.BuildFile(ControllerContext);
        System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);            
    }
Divya
  • 11
  • 3