0

Is it possible to save a rendered view as html file?

I need to save a view as an "Testfile.html" after Razor and javascript has rendered. Is it possible?

What i am trying to do, is take the saved view, that includes canvas created using chart.js, and save them as an html file. Afterwards i want to convert the html file to a pdf using iText7

Mags
  • 57
  • 7
  • You need to call that controller action, which returns the view, from C# using HTTPClient, the response will have the HTML content of the view. You can save it as an html file. – Chetan Oct 01 '19 at 08:22
  • https://stackoverflow.com/questions/18442343/get-html-from-mvc-4-view-into-a-string – Chetan Oct 01 '19 at 08:26
  • Possible duplicate of [In MVC3 Razor, how do I get the html of a rendered view inside an action?](https://stackoverflow.com/questions/4692131/in-mvc3-razor-how-do-i-get-the-html-of-a-rendered-view-inside-an-action) – Adersh M Oct 01 '19 at 10:11

2 Answers2

0

Take a look on the below code :

First of all there is no need to save the HTML as a physical file, you can just call the razor engine renderer from within your controller, for example, so as to return the final string response.

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();
        }
    }

Then you can pass this response to your exporter so that it can return to you the pdf file, that you will later on return directly to the client

              string htmlContent = RenderRazorViewToString("SomeViewDefinedAsPartial", ReportModel);

////    fetch view's pdf styles
                string CSSContent = "";

            var byteRslt = PDFExporter.ConvertToPDF(htmlContent, CSSContent);

Important: HTML to PDF renderers usually dont play well enough with dynamic pages that require javascript to do initializations, but i hope this answer will help you move forwards in your requirement/implementation.

MKougiouris
  • 2,821
  • 1
  • 16
  • 19
0

You can directly convert the View to pdf file using wkhtmltopdf

wkhtmltopdf need to be installed on the server and its path is used in the web.config from here the c# code will use this path and convert it to pdf file.

Dileep Sreepathi
  • 302
  • 3
  • 10