问题
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?
回答1:
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/
回答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.
来源:https://stackoverflow.com/questions/62584735/how-to-render-full-razorpage-to-string