Razor View to PDF in .Net
Photo by Glenn Carstens-Peters
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 MVC
Please read the .NET MVC PDF FAQ to lean how to render a MVC view as a binary PDF file.
Information contained on this page is provided by an independent third-party content provider. Frankly and this Site make no warranties or representations in connection therewith. If you are affiliated with this page and would like it removed please contact pressreleases@franklymedia.com