2

I have two controllers, 1 is an api controller, the other is a view controller, what I am trying to do is generate the PDF from the api controller from a view in the view controller...is this possible and how would I do it?

API Controller - This is where I want to generate the PDF

public byte[] getReportsPDF(string community, string procedure)
{
            byte[] pdfBytes = new byte[] { };

            System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext();

            if(procedure == "GetProductionTasks")
            {
                var actionPDF = new Rotativa.ActionAsPdf("RedBluePDF", new { community = community, procedure = procedure })
            {
                    PageSize = Size.A4,
                    PageOrientation = Rotativa.Options.Orientation.Landscape,
                    PageMargins = { Left = 1, Right = 1 }
                };
                pdfBytes = actionPDF.BuildFile(context);
            }

            return pdfBytes;
}

View Controller - This is the view I want to generate.

public ActionResult RedBluePDF(string community, string procedure)
{
    return View();            
}
user979331
  • 11,039
  • 73
  • 223
  • 418
  • 1
    Ideally you should not call API controller from View controller. What you can do is have a separate PDF generation class and Invoke the PDF generate from both View and API controller. Check [this link](https://stackoverflow.com/questions/29699884/calling-web-api-from-mvc-controller) – karthickj25 Jan 15 '19 at 06:11
  • Hey I’m trying to call a view controller from API controller – user979331 Jan 15 '19 at 06:16
  • If you isolate the GeneratePDF method, you can then call it from the api. – karthickj25 Jan 15 '19 at 06:22
  • try this https://stackoverflow.com/questions/36262064/how-to-access-mvc-controller-in-web-api-controller-to-get-pdf-from-view?rq=1 – Mohammad Ghanem Jan 15 '19 at 07:10

1 Answers1

1

After trying for a very long time, finally I managed to solve by this:

var controller = DependencyResolver.Current.GetService<ViewController>();
RouteData route = new RouteData();
route.Values.Add("action", "RedBluePDF");
route.Values.Add("controller", "ApiController");
ControllerContext newContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, controller);

controller.ControllerContext = newContext;
controller.RedBluePDF(community, procedure);

I have been trying:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

But this will give me the wrong pdf, because it will use your current controller (API Controller in this case) to make the call for ActionAsPdf()

Credit to this answer

lrh09
  • 557
  • 4
  • 13