1

I tried to use the solution from https://stackoverflow.com/a/54043063/234954, to render a page as a string (so I can turn it into a PDF), but that only gets me the main view, it doesn't get the layout associated with the page (and so it is missing the style sheets and some header/footers).

How can I render the full page as a string, and not just the partial view?

jmoreno
  • 12,752
  • 4
  • 60
  • 91

2 Answers2

2

I used this article code in a recent project to render html to feed into PDF generation.

I used templates in the Views folder so not razor pages.

It works with Layouts and partials in templates.

https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/

Rosco
  • 2,108
  • 17
  • 17
  • the main difference between this and what I was doing is that the it finds and uses the view instead of the page. That turned out to be exactly the thing I needed to change. – jmoreno Jun 26 '20 at 04:53
2

I found that I could get what I wanted (the whole page) by making two changes to the answer I was looking at:

var view = new RazorView(_razorViewEngine,
                _activator,
                new List<IRazorPage>(),
                page,
                HtmlEncoder.Default,
                new DiagnosticListener("ViewRenderService"));

changed to :

 var view = new RazorView(_razorViewEngine,
                _activator,
                pageModel.PageContext.ViewStartFactories.Select(v => v()).ToList(),
                page,
                HtmlEncoder.Default,
                new DiagnosticListener("ViewRenderService"));

and

await page.ExecuteAsync();

to

await view.RenderAsync(viewContext);

Note that if the viewstart pages aren't included in the view, then rendering the view produces the same as executing the page.

jmoreno
  • 12,752
  • 4
  • 60
  • 91