DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironpdf.com

IronPDF Razor Extension

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

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;");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

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

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

Figure 4 - Models folders

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

Figure 5 - Model added

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; }
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Figure 6 - Service Folder

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

Figure 7 - Adding the Service Class

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Adding the MVC Controller

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

Figure 8 - Add Controller

Figure 8 - Add Controller

Select Add Controller

Figure 9 - Add Controller

Figure 9 - Add Controller

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

Figure 10 - Example Controller

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

Figure 11 - Add View

Click Add.

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

Figure 12 - Index.cshtml

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>
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)