Show a PDF in the browser in RotativaHQ

date Oct 20, 2017

Controlling how a PDF will be served to the user by the browser can be hard and not 100% effective. But we have a few options that will let us make it work for most of our user base.

When a file is sent as a HTTP response to the browser, the information about how to treat this file is located in the HTTP headers. The browser will decide what to do with the response based on how it is configured and what is installed on the OS.

With Rotativa.io you have a few parameters to help.

  • If you don’t define a FileName property then the PDF should be served by the browser inline inside the browser window. If the user wishes to download it then it will default its name to a unique id assigned by Rotativa.io. As will happen will this code:
public ActionResult MyAction()
{
    return new ViewAsPdf();
}
  • If you define a FileName property, then the browser will, either prompt te user asking if it needs to save or open the file, or just download it (the latter should be the case for Chrome). This code will give achieve this:
public ActionResult MyAction()
{
    return new ViewAsPdf()
    {
        FileName = "MyPdfFile.pdf"  
    };
}
  • If you define both the FileName property and the ShowInline property to true, then the browser should show the file inside the browser window and show the defined file name as default when saving. As this sample code:
public ActionResult Contact()
{
    ViewBag.Message = "Your application description page.";

    return new ViewAsPdf() {
        FileName = "CDtest.pdf",
        ShowInline = true
    };
}

This options should work most of the times. Of course we can’t know if the user has installed any PDF reader or if the browser itself has a embedded reader or the user has installed a browser plugin to read PDF files. But still, with those options we are able to send to the browser the correct HTTP headers.