Coimbatore, , India
C Sharp Dot Net, Software Development, HTML
0 टिप्पणी करें | 2 लोगो ने देखा है | 23 अगस्त 19  | Kavipriya Palanisamy
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 = "" +
"" +
"@Model.Title" +
"@Model.Name" +
"@Model.Age" +
" ";
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() {
//Get template from database
var razorTemplate = "" + "" + "@Model.Title" + "@Model.Name" + "@Model.Age" + " ";
//Model to bind
SampleModel sampleModel = new SampleModel() {
Title = "Mr",
Name = "Raj",
Age = 24
};
//Bind razor template with model
var razorTemplateString = Engine.Razor.RunCompile(razorTemplate, DateTime.Now.TimeOfDay.ToString(), null, sampleModel);
//Rotativa to convert view as pdf
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
@Model string
@{
Layout = "~/Views/Shared/_PrintLayout.cshtml";
}
@Html.Raw(Model)

    • इस ब्लॉग के लिए सामाजिक शेयर

पोर्फोलिओ और ब्लॉग
Kavipriya Palanisamy विभिन्न कंपनियों का अनुसरण करता है, ये कंपनियां और नियोक्ता Kavipriya के फिर से शुरू देख सकते हैं
सबसे अच्छा नौकरी के अवसर पाने के लिए अपना फिर से शुरू करें अपलोड करें

मुफ्त रजिस्टर करें!