DLL Requirements
- RazorEngine.dll(3.10.0) -Bind template with model
- Rotativa -Converts Razor View to PDF
Introduction
In MVC, we return a View for every action method and pass the Model to the View and bind it to the View. So, we need an action method and a View for every action. That's a lot of action methods, right? Well, we can have only one action method and in that, we can get Razor templates from the database or file and bind the data to the code and pass the result to View. This is possible with the help of RazorEngine.
RazorEngine
RazorEngine is a templating engine built upon Microsoft's Razor parsing technology. The RazorEngine allows you to use Razor syntax to build robust templates.
Rotativa
Generating a PDF for a report or any document that can be printable in .NET is a bit cumbersome. But this can be achieved in ASP.NET MVC very easily and quickly using Rotativa tools which are available in the NuGet packages. It gives you the flexibility to create PDFs directly from Views or Partial Views or URLs too.
Step 1
Get template from the database.
- var razorTemplate = "<div class='row'>" +
- "<div class='text-center'>" +
- "<div>@Model.Title</div>" +
- "<div>@Model.Name</div>" +
- "<div>@Model.Age</div>" +
- "</div> </div>";
Step 2
Model to bind.
- SampleModel sampleModel = new SampleModel()
- {
- Title = "Mr",
- Name = "Raj",
- Age = 24
- };
Step 3
Bind the Razor template with model.
- var razorTemplateString = Engine.Razor.RunCompile(razorTemplate, DateTime.Now.TimeOfDay.ToString(), null, sampleModel);
Step 4
Rotativa returns the View as pdf.
- var PDFView = new ViewAsPdf("Print", razorTemplateString)
- {
- FileName = "Sample.pdf",
- };
- return PDFView;
- }
Complete Code
- public class TemplateController: Controller {
- public ActionResult Print() {
-
- var razorTemplate = "<div class='row'>" + "<div class='text-center'>" + "<div>@Model.Title</div>" + "<div>@Model.Name</div>" + "<div>@Model.Age</div>" + "</div> </div>";
-
- SampleModel sampleModel = new SampleModel() {
- Title = "Mr",
- Name = "Raj",
- Age = 24
- };
-
- var razorTemplateString = Engine.Razor.RunCompile(razorTemplate, DateTime.Now.TimeOfDay.ToString(), null, sampleModel);
-
- var PDFView = new ViewAsPdf("Print", razorTemplateString) {
- FileName = "Sample.pdf",
- };
- return PDFView;
- }
- }
- public class SampleModel {
- public string Title {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public int Age {
- get;
- set;
- }
- }
Print View
- <div style="display: none;">@Model string</div>
- @{
- Layout = "~/Views/Shared/_PrintLayout.cshtml";
- }
- @Html.Raw(Model)