I'm developing a Web application using MVC (.NET 7.0), I need to convert a View with data to PDF, to do that I'm using Rotativa.
Problem is, when I'm calling my method to convert the View
<a href="@Url.Action("ConvertToPdf", "Home", new { html = ViewData["html"] })">Convert to PDF</a>
The model is not loaded and an exception is thrown
Object reference not set to an instance of an object.
Which is understandable as the code doesn't reach the action that loads my view data.
Here is my controller Action
public ActionResult ConvertToPdf()
{
return new ViewAsPdf("ListUsers", _listUsers);
}
And this is the action to feed the list view I want to convert
public async Task<IActionResult> ListUsers()
{
_listUsers = await _context.Users.ToListAsync();
return View(_listUsers);
}
Any Idea of how I can load data into my view when exporting it to PDF? I'm using ViewAsPdf as I'm running Rotativa.AspNETCOre nuget package
I eventually found the answer by myself.
Just need to load data from my context
var model = _context.Users.Select(u => new Users
{
Username = u.Username,
OfficeLocation= u.OfficeLocation,
ContractType = u.ContractType,
UserDept = u.UserDept
});
return new ViewAsPdf("ListUsers", model) { FileName = "PDF File.pdf"};
The PDF conversion of the view works pretty well.