您可以尝试将剃刀代码呈现为字符串,然后将其保存为文件,最后将文件导出为 PDF。
有时像这样:
剃刀到字符串
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();
}
}
导出为 PDF
public void MyPDFExport()
{
string url = @"d:\Foo.html";
string html = RenderRazorViewToString("File", "myName");
System.IO.File.WriteAllBytes(url, System.Text.Encoding.ASCII.GetBytes(html));
var document = new HtmlToPdfDocument
{
GlobalSettings = new GlobalSettings(),
Objects =
{
new ObjectSettings
{
HtmlText = "<p>Some Html</p>",
FooterSettings = new FooterSettings { HtmlUrl = url }
}
}
};
IConverter converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win32EmbeddedDeployment(
new TempFolderDeployment())));
byte[] result = converter.Convert(document);
}
查看文件.cshtml
@model string
<html>
<p>Name: @Model</p>
</html>