Originally Posted On: https://ironpdf.com/docs/questions/razor-view-to-pdf/
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,
- viewName);
- 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();
- }
- }
Copy code to clipboardVB 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 MVCPlease read the .NET MVC PDF FAQ to lean how to render a MVC view as a binary PDF file.