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. </head>
  10. <body>
  11. <div class="navbar navbar-inverse navbar-fixed-top" style="background-color:lightgray; color:black !important;">
  12. <div class="container">
  13. <div class="navbar-header">
  14. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  15. <span class="icon-bar"></span>
  16. <span class="icon-bar"></span>
  17. <span class="icon-bar"></span>
  18. </button>
  19. <a href="https://storefront.crowehorwath.com/Citrix/CroweWeb/"> Logo</a>
  20. </div>
  21. <div class="navbar-collapse collapse">
  22. @Html.Partial("_LoginPartial")
  23. </div>
  24. </div>
  25. </div>
  26. <div class="container body-content">
  27. @RenderBody()
  28. <hr />
  29. <footer>
  30. <p>© @DateTime.Now.Year - Local Development</p>
  31. </footer>
  32. </div>
  33. @Scripts.Render("~/bundles/jquery")
  34. @Scripts.Render("~/bundles/bootstrap")
  35. @RenderSection("scripts", required: false)
  36. </body>
  37. </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. <h2>Audit Program</h2>
  8. <table border="0" cellpadding="12" cellspacing="10">
  9. <tr>
  10. <td>
  11. Project Number:
  12. </td>
  13. <td>
  14. @auditProgram.ProjectNumber
  15. </td>
  16. </tr>
  17. <tr>
  18. <td>
  19. Project Name:
  20. </td>
  21. <td>
  22. @auditProgram.ProjectName
  23. </td>
  24. </tr>
  25. <tr>
  26. <td>
  27. Element Number:
  28. </td>
  29. <td>
  30. @auditProgram.ElementNumber
  31. </td>
  32. </tr>
  33. <tr>
  34. <td>
  35. Element Name:
  36. </td>
  37. <td>
  38. @auditProgram.ElementName
  39. </td>
  40. </tr>
  41. </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. }

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. //Load HTML string into MemoryStream using Aspose document class
  16. Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(HtmlContent)), objLoadOptions);
  17. string FileName = "ProjectAudit_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf";
  18. //Save PDF file on local hard drive or database or as you wish
  19. doc.Save(HttpContext.Current.Server.MapPath("~/" + FileName));
  20. System.Diagnostics.Process.Start(HttpContext.Current.Server.MapPath("~/" + FileName));
  21. //}
  22. }

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.