IronPDF Razor Extension
Published: 2022-01-25 07:50:02

---
canonical_url: https://ironpdf.com/docs/questions/razor-view-to-pdf/
---

IronPDF is a pdf library for .NET and .NET Core. It is mostly a free pdf library, as IronPDF is an openly commercial C# PDF library. It is free for development but must be licensed for commercial deployment. This clearer license model does not require developers to learn the ins and outs of GNU / AGPL license models and can instead focus on their projects.

IronPDF enables .NET and .NET Core developers to generate, merge, split, edit, and extract pdf content easily in C#, F#, and VB.Net for .NET Core and .NET Framework as well as create PDFs from HTML, ASPX, CSS, JS, and image files.

IronPDF has comprehensive PDF editing and generation functionality via HTML to PDF. How does it work? Well, most of the document design and layout can use existing HTML and HTML5 assets.

## IronPDF features for .NET & .NET Core applications

Some fantastic IronPDF pdf library features include:

- The .NET pdf library can generate PDF documents from HTML, images and ASPX files
- Reading PDF text in .NET and .NET Core applications
- Extracting data and images from PDFs
- Merging PDF documents
- Splitting PDFs
- Manipulating PDFs

## IronPDF Advantages

- The IronPDF pdf library is easy to install
- The IronPDF .NET library has quick and easy licensing options
- IronPDF outshines most .NET pdf libraries and outperforms most .NET Core pdf libraries

**IronPDF is the pdf solution you've been looking for.**

---

## Installing the IronPDF pdf library

To install the IronPDF library for pdf in .NET or .NET Core is quite easy. You could install it in the following ways:

Use the NuGet package manager and type the following into the command prompt:

`Install-Package IronPdf`

Using the NuGet package manager in Visual Studio by opening the Selecting Manage NuGet Packages from the project menu and searching for IronPDF, as shown below:

![Figure 1 - IronPDF NuGet Package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nn6fngf6orfls7nby8h8.png)

**Figure 1** - _IronPDF NuGet Package_

This installs the PDF extension.

With IronPDF you can use ASP.Net MVC to return a PDF file. A few code examples follow:

An example of a method that could be served by your controller as shown below.

**C#:**
```
public FileResult Generate_PDF_FromHTML_Or_MVC(long id) {
  var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPdf and MVC Example</h1>"); //Create a PDF Document 
  var objLength = objPDF.BinaryData.Length; //return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString());
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" + id + ".pdf");
  return File(objPDF.BinaryData, "application/pdf;");
}
```

**VB:**
```
Public Function Generate_PDF_FromHTML_Or_MVC(ByVal id As Long) As FileResult
  Dim objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPdf and MVC Example</h1>") 'Create a PDF Document
  Dim objLength = objPDF.BinaryData.Length 'return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString())
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" & id & ".pdf")
  Return File(objPDF.BinaryData, "application/pdf;")
End Function
```

An example of serving an existing pdf in ASP.NET follows.

**C#:**
```
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"));
Response.Flush();
Response.End();
```

**VB:**
```
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition","attachment;filename=""FileName.pdf""")
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"))
Response.Flush()
Response.End()
```

Let’s do a quick example in ASP.NET using MVC and .NET Core, open Visual Studio and create a new ASP.NET Core web application.

![Figure 2 - ASP.Net Core Web Application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igmgl2ttzvef00vikie4.png)

**Figure 2** - _ASP.Net Core Web Application_

Click Next.

Select the location that this project should be created inside, and click ‘Create’.

A new window will open, it looks like Figure 3

![Figure 3 - ASP.Net Core Web Application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2k5en6axc2diqu4jjnn.png)

**Figure 3** - _ASP.Net Core Web Application_

Select Web Application (Model-View-Controller). This will create an ASP.NET Core web application.

Now that we have an application set up, we need to create the following:

- Client object model
- Client services
- Add the pages
- Functionality to download the pdf document

---

## Create the MVC Model

To create the model, use the next few steps:

Right click on the Model folders

![Figure 4 - Models Folders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1x4n5fsxyyv0cv82nayl.png)

**Figure 4** - _Models folders_

Select Add, Class. **Figure 5** below shows a model _'ExampleModel added'_

![Figure 5 - Model added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vq1ja7u5p34udk22mjy6.png)


**Figure 5** - _Model added_

You could add content to your Model, for example:

**C#:**
```
namespace ASPCore_Ex.Models
{
    public class ExampleModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}
```

**VB:**
```
Namespace ASPCore_Ex.Models
	Public Class ExampleModel
		Public Property Name() As String
		Public Property Surname() As String
		Public Property Age() As Integer
	End Class
End Namespace
```

---

## Creating the MVC Service

Follow the next few steps to add the service necessary Right-click on the project folder and select '_Add New Folder_'

![Figure 6 - Service Folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9vvx11e8ij07g6oidh47.png)

**Figure 6** - _Service Folder_

Right click on the Services folder, and add a new class

![Figure 7 - Adding the Service Class](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/on7hreil7ytd86gm0owb.png)

**Figure 7** - _Adding the Service Class_

Connect the Model and the Service with code similar to the following:

**C#:**
```
public class ExampleService
{
    private static ExampleModel eModel;
    public static void AddExample(ExampleModel exModel)
    {
         eModel = exModel;
    }
    public static ExampleModel GetExample()
    {
         return eModel;
    }
}
```

**VB:**
```
Public Class ExampleService
	Private Shared eModel As ExampleModel
	Public Shared Sub AddExample(ByVal exModel As ExampleModel)
		 eModel = exModel
	End Sub
	Public Shared Function GetExample() As ExampleModel
		 Return eModel
	End Function
End Class
```

---

## Adding the MVC Controller

To add the controller, follow the next step or two steps Right-click the 'Controllers' folder

![Figure 8 - Add Controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7tbyqk8b29bo7lmgumd.png)

**Figure 8** - _Add Controller_

Select Add Controller

![Figure 9 - Add Controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqo24zfwhbltmuo3rveb.png)

**Figure 9** - _Add Controller_

The next image below shows an example of a controller being added.

![Figure 10 - Example Controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hvn4fwxejdwwn2wdl2u.png)

**Figure 10** - _Example Controller_

After the controller has been added, right-click on the constructor of the Controller class, and select 'Add View'. This opens a dialog where you can choose which Razor view option to add. You don't really have to follow this step as there already exists an Index.cshtml page in the Home folder. You can add a new View if you want to place your Index file inside another folder.

![Figure 11 - Add View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/so6owl6jcyf70ma0ncwj.png)

**Figure 11** - _Add View_

Click Add.

Then, on the next screen, specify a name, and click Add

![Figure 12 - Index.cshtml](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvpm0uajn8ydpzo0ri2k.png)

**Figure 12** - _Index.cshtml_

We can add a simple form to our Home page with the following code

**C#:**
```
@model ASPCore_Ex.Models.ExampleModel
@{
    ViewBag.Title = "Example Index View";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-10 pull-right">
                <button type="submit" value="Save" class="btn btn-sm">
                    <i class="fa fa-plus"></i>
                    <span>
                        Save
                    </span>
                </button>
            </div>
        </div>
    </div>
}
```

**VB:**
```
<HttpPost>
Public Function ExampleView(ByVal model As ExampleModel) As ActionResult
  IronPdf.Installation.TempFolderPath = $"{_host.ContentRootPath}/irontemp/"
  IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = True
  Dim html = Me.RenderViewAsync("_Example", model)
  Dim ironPdfRender = New IronPdf.ChromePdfRenderer()
  Dim pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result)
  Return File(pdfDoc.Stream.ToArray(), "application/pdf")
End Function
```

The RenderViewAsync code looks like the following:

**C#:**
```
public static class ControllerPDF
{
  public static async Task<string> RenderViewAsync<TModel>(this Controller, string viewName, TModel model, bool partial = false)
  {
    if (string.IsNullOrEmpty(viewName))
    {
      viewName = controller.ControllerContext.ActionDescriptor.ActionName;
    }
    controller.ViewData.Model = model;
    using (var writer = new StringWriter())
    {
      IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
      ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
      if (viewResult.Success == false)
      {
        return $"A view with the name {viewName} could not be found";
      }
      ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
      await viewResult.View.RenderAsync(viewContext);
      return writer.GetStringBuilder().ToString();
    }
  }
}
```

**VB:**
```
Public Module ControllerPDF
'INSTANT VB TODO TASK: The following line could not be converted:
  public static async Task(Of String) RenderViewAsync(Of TModel)(Me Controller, String viewName, TModel model, Boolean partial = False)
  If True Then
	If String.IsNullOrEmpty(viewName) Then
	  viewName = controller.ControllerContext.ActionDescriptor.ActionName
	End If
	controller.ViewData.Model = model
	Using writer = New StringWriter()
	  Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
	  Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
	  If viewResult.Success = False Then
		Return $"A view with the name {viewName} could not be found"
	  End If
	  Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
	  Await viewResult.View.RenderAsync(viewContext)
	  Return writer.GetStringBuilder().ToString()
	End Using
  End If
End Module
```