.net - 将剃刀视图转换为 pdf 文件
问题描述
我有一个应用程序,管理员可以在电子邮件中完成后在电子邮件中订购详细信息,并将副本保存在服务器中。我有一个视图“~/order/MyOrder.cshtml?id=Q5/KCbPNhXKx7EWffTprWg==”,用户在登录后可以查看其状态。但是,当订单完成时,管理员会向用户发送一封电子邮件,其中包含订单状态和包含所有信息的 pdf 文件。我正在尝试从上面提到的视图创建一个 pdf 文件,并计划将该文件附加到电子邮件中。最好的方法是什么。我在这里看到的解决方案很少,但我无法弄清楚处理这个问题的方法。我为此使用 ITEXSharp。
string html = RenderViewToString(ControllerContext,
"/order/MyOrder.cshtml?Auth=Q5/KCbPNhXKx7EWffTprWg==",
model, true);
using (MemoryStream stream = new System.IO.MemoryStream())
{
StringReader sr = new StringReader(html);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
var Filename = File(stream.ToArray(), "application/pdf", "Grid.pdf");
zip.AddFile(Filename.FileDownloadName, "Pdf");
}
和 RanderViewToString 函数:
static string RenderViewToString(ControllerContext context,
string viewPath,
object model = null,
bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
我收到“值不能为空。参数名称:视图”错误。我不确定如何使用参数传递视图以将其转换为字符串。
解决方案
我建议你试试 Rotativa
https://github.com/webgio/Rotativa
public ActionResult PrintIndex()
{
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}
推荐阅读
- java - 为什么基于数组的队列在java中不能正常工作
- c# - 如何根据屏幕大小更改 kendo mvc grid PageSize?
- php - 我正在尝试为我正在开发的应用程序创建安全等级,但我是新手并且迷路了
- sql - mysql select查询中出现意外的查询结果
- python - 如何在 Dataframe 的行级别应用计算?
- amazon-web-services - 将 Namecheap 域与 amazon S3 存储桶连接
- r - 无法将 .rmd 文件编入 PDF、HTML 或 Word
- java - javax.mail.NoSuchProviderException:本地没有提供程序
- java - 如何防止用作地图值的列表被修改?
- mysql - MySQL 按日期排序并按名称分组