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);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With