Razor View to PDF in .NET

The following method makes it easy to render a Razor view to a string.

We may then use IronPDF’s HTML to PDF functionality to render that Razor view as a string.

public string RenderRazorViewToString(string viewName, object model)
ViewData.Model = model;
    using (var sw = new StringWriter())
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
        var viewContext = new ViewContext(ControllerContext, viewResult.View,
        ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
Public Function RenderRazorViewToString(ByVal viewName As String, ByVal model As Object) As String
ViewData.Model = model
	Using sw = New StringWriter()
		Dim viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName)
		Dim viewContext = New ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw)
		viewResult.View.Render(viewContext, sw)
		viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View)
		Return sw.GetStringBuilder().ToString()
	End Using
End Function
VB   C#

Don’t forget to set the optional BaseURI parameter of the IronPdf.HtmlToPdf.RenderHtmlAsPdf Method to load relative assets, CSS, JS and images.

Serving Razor Views as PDFs in ASP.NET MVC

Please read the .NET MVC PDF FAQ to lean how to render a MVC view as a binary PDF file.