Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access mvc controller in web api controller to get pdf from view

I created Web Api and MVC combined for single page web app. I want to call web api and render mvc controller to create pdf from view using Rotativa api. Problem is when i access mvc controller in web api it's not work.

How i access mvc controller in web api to get pdf from view?

Note: mvc controller object declared in web api so it gives "ControllerContext" is null in "GetPdfBytesFormView" method.

Web Api:

[RoutePrefix("api/reports/TestReport")]
public class TestReportController : ApiController
{     
    [HttpPost]
    [Route("GetRequistionPdf")]
    public HttpResponseMessage GetRequistionPdf(modelClass oModel)  
    {       
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        ReportController _Report = new ReportController();
        response.Content = new ByteArrayContent(_Report.GetPdfBytesFormView(oModel));       
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");            
        return response;
    }
}

MVC Controller:

public class ReportController : Controller
{       
    public ActionResult GenerateReport(modelClass oModel)
    {
        return View(oModel);
    }

    public byte[] GetPdfBytesFormView(modelClass oModel)
    {            
        var actionPDF = new Rotativa.ActionAsPdf("GenerateReport", oModel) 
        {                
            PageSize = Size.A4,
            PageOrientation = Orientation.Portrait,
            PageMargins = { Left = 6, Right = 7 }
        };

        byte[] applicationPDFData = actionPDF.BuildPdf(ControllerContext);            
        return applicationPDFData;
    }
}

Angularjs web api call

$http.post('http://localhost:54527/api/reports/TestReport/GetRequistionPdf', { data }, { responseType: 'arraybuffer' })
                .success(function (data) {
                    var file = new Blob([data], { type: 'application/pdf' });
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL);
                });
like image 367
Raju Padhara Avatar asked Mar 28 '16 12:03

Raju Padhara


1 Answers

Finally get solution.

Let say your controller name is "PDFController" and action name is "GetPDF". Write following code in your api controller

    // Add key value    
    RouteData route = new RouteData();
    route.Values.Add("action", "GetPDF"); // ActionName
    route.Values.Add("controller", "PDF"); // Controller Name
    System.Web.Mvc.ControllerContext newContext = new System.Web.Mvc.ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, controller);
    controller.ControllerContext = newContext;
    controller.GetPDF();

Your are done now. Your pdf should get generated.

Hope it help

like image 130
Naveen Motwani - AIS Avatar answered Nov 15 '22 00:11

Naveen Motwani - AIS