将剃刀视图转换为pdf文件

问题描述 投票:0回答:1

我有一个应用程序,管理员可以在电子邮件中完成订单并将其副本保存在服务器中后,管理员在其中订购用户的详细信息。我有一个视图“〜/ 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;
}

我收到“值不能为空。参数名称:view'”错误。我不确定如何通过带有参数的视图将其转换为字符串。

.net asp.net-mvc razor itext
1个回答
0
投票

我建议您尝试Rotativa

https://github.com/webgio/Rotativa

  public ActionResult PrintIndex()
  {
          return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
   }
© www.soinside.com 2019 - 2024. All rights reserved.