Convert MVC View And Layout File Into HTML Content

Introduction

Let’s discuss how to get the MVC view and layout HTML content through Razor View String. For instance, if you want to generate PDF through HTML content you need to get the MVC View and Layout DOM content.

Here you go with the step by step process to get the DOM content.

_Layout.cshtml file

This is the _Layout.cshtml file, which is available in Shared directory. Find the below screenshot for reference.

MVC

 

This is like the master page. Once you call this Layout in View, you can access header part in the web page. We can update the header information on this file.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10. </head>  
  11. <body>  
  12.     <div class="navbar navbar-inverse navbar-fixed-top" style="background-color:lightgray; color:black !important;">  
  13.         <div class="container">  
  14.             <div class="navbar-header">  
  15.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  16.                     <span class="icon-bar"></span>  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                 </button>  
  20.                 <a href="https://storefront.crowehorwath.com/Citrix/CroweWeb/"> Logo</a>  
  21.             </div>  
  22.             <div class="navbar-collapse collapse">  
  23.   
  24.                 @Html.Partial("_LoginPartial")  
  25.             </div>  
  26.         </div>  
  27.     </div>  
  28.     <div class="container body-content">  
  29.         @RenderBody()  
  30.         <hr />  
  31.         <footer>  
  32.             <p>© @DateTime.Now.Year - Local Development</p>  
  33.         </footer>  
  34.     </div>  
  35.   
  36.     @Scripts.Render("~/bundles/jquery")  
  37.     @Scripts.Render("~/bundles/bootstrap")  
  38.     @RenderSection("scripts", required: false)  
  39. </body>  
  40. </html>  

ProjectContent.cshtml

This is the page that contains webpage contents. You can design your requirement on the view. Find the below screenshot.

MVC

We have implemented the sample webpage that displays on web page. Find the code.

  1. @model iTexhSharpHTMLtoPDF.Models.ProjectModel  
  2. @{  
  3.     ViewBag.Title = "ProjectContent";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5.     var auditProgram = ViewData.Model;  
  6. }  
  7.   
  8. <h2>Audit Program</h2>  
  9.   
  10. <table border="0" cellpadding="12" cellspacing="10">  
  11.     <tr>  
  12.         <td>  
  13.             Project Number:  
  14.         </td>  
  15.         <td>  
  16.             @auditProgram.ProjectNumber  
  17.         </td>  
  18.     </tr>  
  19.     <tr>  
  20.         <td>  
  21.             Project Name:  
  22.         </td>  
  23.         <td>  
  24.             @auditProgram.ProjectName  
  25.         </td>  
  26.     </tr>  
  27.     <tr>  
  28.         <td>  
  29.             Element Number:  
  30.         </td>  
  31.   
  32.         <td>  
  33.             @auditProgram.ElementNumber  
  34.         </td>  
  35.     </tr>  
  36.     <tr>  
  37.         <td>  
  38.             Element Name:  
  39.         </td>  
  40.   
  41.         <td>  
  42.             @auditProgram.ElementName  
  43.         </td>  
  44.     </tr>  
  45.   
  46. </table>  

Class File

This is the Class file, which is used to generate the DOM content by the combination of Controller, View Name, and Model Data. Here, Model data is an optional one.

In the method, ViewContext method will give the result of the current request.

  1. public class RazorViewToStringFormat  
  2.     {  
  3.         /// <summary>  
  4.         /// Render razorview to string   
  5.         /// </summary>  
  6.         /// <param name="controller"></param>  
  7.         /// <param name="viewName"></param>  
  8.         /// <param name="model"></param>  
  9.         /// <returns></returns>  
  10.         public static string RenderRazorViewToString(Controller controller, string viewName, object model)  
  11.         {  
  12.             controller.ViewData.Model = model;  
  13.             var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);  
  14.             // checking the view inside the controller  
  15.             if (viewResult.View != null)  
  16.             {  
  17.                 using (var sw = new StringWriter())  
  18.                 {  
  19.                     var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);  
  20.                     viewResult.View.Render(viewContext, sw);  
  21.                     viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);  
  22.                     return sw.GetStringBuilder().ToString();  
  23.                 }  
  24.             }  
  25.             else  
  26.                 return "View cannot be found.";  
  27.         }  
  28.     }  

Method

This method generates combination of View and Layout content as HTML DOM.

Here, RazorViewToStringFormat is the Class name and the method “RenderRazorViewToString” is used to retrieve the DOM content.

  1. public void GenerateAspose()  
  2. {  
  3.   try  
  4.   {  
  5.      string HtmlContent = RazorViewToStringFormat.RenderRazorViewToString(this, ViewName,      projectModel.TempData());  
  6.      if (!HtmlContent.Equals("View cannot be found."))  
  7.           pdfAspose.GeneratePDF(HtmlContent);  
  8.   }  
  9.   catch (Exception ex)  
  10.   {  
  11.   
  12.   }  
  13. }  

Generate PDF

Eventually, you can pass output string to the method. In this function, we have used the ASPOSE PDF DLL for HTML content conversion but you can use your preferred DLL.

  1. public void GeneratePDF(string HtmlContent)  
  2. {  
  3.   Aspose.Pdf.License Objpdflicense = new Aspose.Pdf.License();  
  4.   //Objpdflicense.SetLicense(@"E:\Aspose\Aspose.Pdf.lic");  
  5.   Objpdflicense.Embedded = true;  
  6.   //Check if licensed applied  
  7.   //if (Document.IsLicensed)  
  8.   //{  
  9.   //Set the properties for PDF file page format           
  10.   HtmlLoadOptions objLoadOptions = new    HtmlLoadOptions(HttpContext.Current.Server.MapPath("~/Content/"));  
  11.   objLoadOptions.PageInfo.Margin.Bottom = 10;  
  12.   objLoadOptions.PageInfo.Margin.Top = 10;  
  13.   objLoadOptions.PageInfo.Margin.Left = 20;  
  14.   objLoadOptions.PageInfo.Margin.Right = 20;  
  15.               
  16.  //Load HTML string into MemoryStream using Aspose document class  
  17.  Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(HtmlContent)),   objLoadOptions);  
  18.  string FileName = "ProjectAudit_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf";  
  19.  //Save PDF file on local hard drive or database or as you wish            
  20.  doc.Save(HttpContext.Current.Server.MapPath("~/" + FileName));  
  21.  System.Diagnostics.Process.Start(HttpContext.Current.Server.MapPath("~/" + FileName));  
  22.  //}  
  23. }  

Runtime Example

For instance, we have attached the run-time example screenshot for your reference to understand DOM conversion.

Here, you can see that the combination of Layout.cshtml and View.cshtml DOM content has been loaded into the string.

MVC

OUTPUT

The Output will look like this,

MVC

Thank you.


Similar Articles