Click here to Skip to main content
15,892,005 members
Articles / All Topics

Using Rotativa in MVC Application

Rate me:
Please Sign up or sign in to vote.
4.30/5 (6 votes)
2 Jul 2015CPOL3 min read 28.7K   7   2
Using Rotativa in MVC application

Introduction

Generating PDF from your web applications is easy, simple and reliable. There are many tools/packages available in the Nuget. Here, in this article, we would learn how to use Rotativa in the MVC applications. Rotativa makes it very easy to generate pdf from an HTML. It is actually derived version of wkhtmltopdf which converts HTML to pdf. The browsers use the webkit engine to render the HTML. According to wiki, WebKit is a layout engine software component for rendering webpages in web browsers. Making custom changes to the pdf document generated is quite simple too. Using this, we can directly download the pdf document for the user or else we can also prompt the document inside an i-frame. Let's see how to implement this wonderful tool.

Implementation

Of course, we need to install the package before starting the implementation. To install the package from the package manager console, the command goes like:

Install-Package Rotativa

Then, we can find the rotativa reference under the reference, with a separate folder named ‘Rotativa’ with the following contents.

Another folder named App_Browsers which has the contents required by the package Rotativa.

Rotativa1

Now we are ready to implement the Rotativa using the codes, we will discuss below to generate pdf to directly download it as well as show it in another window. Thus, let's have a look.
To implement the pdf using rotativa, we just need to specify the codes below in a separate action method.

C#
public ActionResult Test()
        {
            var students = new List<xx>
            {
                new xx() {action = "ABC", email = "xx@gg.xom", 
                firstName = "test", lastName = "test"},
                new xx() {action = "ABC", email = "xx@gg.xom", 
                firstName = "test", lastName = "test"},
                new xx() {action = "ABC", email = "xx@gg.xom", 
                firstName = "test", lastName = "test"},
                new xx() {action = "ABC", email = "xx@gg.xom", 
                firstName = "test", lastName = "test"}
            };

            return new Rotativa.ViewAsPdf("TestView", students);
        }

The above code is a simple action method, where we have created a new model and then as we can see, the return statement here, new Rotativa.ViewAsPdf(“TestView”,students). This states that a new rotativa type is created which is used to view the pdf. To this method as you can see, we have passed the first parameter as the View Name and the second parameter as the View Model set for the view. Only the view name can also be used/passed to the overloaded parameter of that method.

  • ViewAsPdf: This method just displays the view as pdf in the same window and to display the same pdf in another window, we can manipulate in the JavaScript as:
    JavaScript
    window.open(url)
  • ViewAsPdf-To Download: This is not property method of the Rotativa class, but can be used differently to download directly the pdf file. Let's see the code below:
    C#
    public ActionResult Test()
            {           
                var pdfResult = new ViewAsPdf("TestView")
                {
                    FileName = "ExamReport.pdf",
                    CustomSwitches =
                        "--footer-center \"Name: " + "XYZ" + "  DOS: " +
                        DateTime.Now.Date.ToString("MM/dd/yyyy") + "  
                        Page: [page]/[toPage]\"" +
                        " --footer-line --footer-font-size \"9\" 
                        --footer-spacing 6 --footer-font-name \"calibri light\""
                };
    
               return pdfResult;            
            }

    User to declare a new type as ViewAsPdf and just return to the action. This will directly download the file for you.

  • ActionAsPdf: This would return the specified action which returns a view with a viewmodel as pdf. The code would go as below:
    C#
    public ActionResult Test(int testID)
    {
         var students = new List<xx>
                {
                    new xx() {action = "ABC", email = "xx@gg.xom", 
                    firstName = "test", lastName = "test"},
                    new xx() {action = "ABC", email = "xx@gg.xom", 
                    firstName = "test", lastName = "test"},
                    new xx() {action = "ABC", email = "xx@gg.xom", 
                    firstName = "test", lastName = "test"},
                    new xx() {action = "ABC", email = "xx@gg.xom", 
                    firstName = "test", lastName = "test"}
                };
        // code to retrieve data from a database
        return View(students);
    }

These are the common methods normally being used.

Now, there is another beautiful thing to mark here. The customization which can be done to the pdf files. The use of Custom Switches.

JavaScript
var pdfResult = new ViewAsPdf("TestView")
            {
                FileName = "ExamReport.pdf",
                CustomSwitches =
                    "--footer-center \"Name: " + "XYZ" + "  DOS: " +
                    DateTime.Now.Date.ToString("MM/dd/yyyy") + "  Page: [page]/[toPage]\"" +
                    " --footer-line --footer-font-size \"9\" 
                    --footer-spacing 6 --footer-font-name \"calibri light\""
            };

The FileName property is used to set the file name for the pdf being downloaded. The Custom Switches is the best property. As we can mark the structure is bit messy, but is not cumbersome. Based on the wkhtmltopdf, there are a list of options which can be used to customize the PDF file. Here in the above code snippet, we have a footer customized.

  • –footer-center: This aligns the footer at the center foot of the page.
  • Page:[page]/[toPage]: The [page] to [toPage] marks the current page and the total number of pages in the file.
  • –footer-line: Displays line above the footer
  • –footer-font-size: Sets the font size of the footer elements
  • –footer-spacing: Sets the spacing between the footer-line and the text
  • –footer-font-name: Sets the font family/style of text

For more options and details, please visit the url –wkhtmltopdf.

Conclusion

Thus, we saw how easy it is to implement the Rotativa in MVC applications and generate a pdf in minutes. Implement and enjoy.

References

  • wkhtmltopdf
  • Nuget Rotativa
  • Github Rotativa
This article was originally posted at http://surajpassion.in/using-rotativa-in-mvc-application

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThe namespace Rotativa could not be found Pin
Gaurav Virmani4-Jun-18 18:06
Gaurav Virmani4-Jun-18 18:06 
GeneralMy vote of 5 Pin
Suvendu Shekhar Giri5-Aug-15 23:50
professionalSuvendu Shekhar Giri5-Aug-15 23:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.