gpt4 book ai didi

asp.net-mvc - 如何将生成的 HTML 存储为字符串,而不是使用 Razor View 引擎写入浏览器?

转载 作者:行者123 更新时间:2023-12-02 00:58:27 24 4
gpt4 key购买 nike

我使用 MVC3 和 Razor View 引擎创建了一个网站。我想要做的是获取生成的 HTML 并将其存储在流或字符串中,以便我可以将其写入文件而不是写入浏览器。

我需要做的是将生成的 HTML 转换为 PDF,并将 PDF 作为报告形式提供给用户。我已经解决了这部分问题,只是无法找出将 HTML 放入某种变量的最佳方法。

编辑 - 我最终走向了一点不同的方向,并想分享结果。我创建了一个使用 WKHTMLTOPDF 项目将流转换为 PDF 的属性。现在我所做的就是向操作添加一个属性,而不是将 HTML 渲染到浏览器,而是弹出一个“另存为”对话框。

public class PdfInterceptAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var viewResult = filterContext.Result as ViewResult;
var workingDir = ConfigurationManager.AppSettings["PdfWorkingPath"];
var fileName = workingDir + @"\" + Guid.NewGuid() + ".pdf";

if (viewResult != null)
{
var view = viewResult.View;
var writer = new StringWriter();
var viewContext = new ViewContext(filterContext.Controller.ControllerContext, view,
viewResult.ViewData, viewResult.TempData, writer);
view.Render(viewContext, writer);
HtmlToPdf(new StringBuilder(writer.ToString()), fileName);
filterContext.HttpContext.Response.Clear();
var pdfByte = File.ReadAllBytes(fileName);
filterContext.HttpContext.Response.ContentType = "application/pdf";
filterContext.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
filterContext.HttpContext.Response.BinaryWrite(pdfByte);
filterContext.HttpContext.Response.End();
}

base.OnResultExecuted(filterContext);
}

private static bool HtmlToPdf(StringBuilder file, string fileName)
{
// assemble destination PDF file name

var workingDir = ConfigurationManager.AppSettings["PdfWorkingPath"];
var exePath = ConfigurationManager.AppSettings["PdfExePath"]; //Path to the WKHTMLTOPDF executable.
var p = new Process
{
StartInfo = {FileName = @"""" + exePath + @""""}
};

var switches = "--print-media-type ";
switches += "--margin-top 4mm --margin-bottom 4mm --margin-right 0mm --margin-left 0mm ";
switches += "--page-size A4 ";

p.StartInfo.Arguments = switches + " " + "-" + " " + fileName;

p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
p.StartInfo.RedirectStandardOutput = true;
//p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
p.StartInfo.WorkingDirectory = workingDir;

p.Start();
var sw = p.StandardInput;
sw.Write(file.ToString());
sw.Close();

// read the output here...
string output = p.StandardOutput.ReadToEnd();

// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);

// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();

// if 0 or 2, it worked (not sure about other values, I want a better way to confirm this)
return (returnCode <= 2);
}
}

最佳答案

我使用这个代码:

private string RenderView<TModel>(string viewPath, TModel model, TempDataDictionary tempData = null) {
var view = new RazorView(
ControllerContext,
viewPath: viewPath,
layoutPath: null,
runViewStartPages: false,
viewStartFileExtensions: null
);

var writer = new StringWriter();
var viewContext = new ViewContext(ControllerContext, view, new ViewDataDictionary<TModel>(model), tempData ?? new TempDataDictionary(), writer);
view.Render(viewContext, writer);
return writer.ToString();
}

这使用当前的ControllerContext;如果您不希望这样,则需要模拟 HttpContextBase

如果您想从 View 传回数据,则需要将其传递到 TempData,而不是 ViewBag

关于asp.net-mvc - 如何将生成的 HTML 存储为字符串,而不是使用 Razor View 引擎写入浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5147877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com