【问题标题】:Unable to download PDF file with Rotativa in MVC4无法在 MVC4 中使用 Rotativa 下载 PDF 文件
【发布时间】:2014-06-08 00:09:09
【问题描述】:

我正在使用 Rotativa 将 Razor 视图转换为 PDF。

PDF 文件未下载。

我可以在 Fiddler 中看到它,但浏览器没有提示下载 - 我在 IE 和 Chrome 上都试过了。

我还尝试使用this question here. 中的解决方案将文件下载到物理路径,但这也不起作用,因为系统无法访问该文件夹(拒绝访问)。

这是我的代码:

public ActionResult Index()
{
    var model = new CustomerDashboardVM();
    return View("Index", model);
}

public ActionResult print(int voucherID)
{
    var pdf =  new ActionAsPdf("Index", new { voucherID}) { FileName = "testInvoice.pdf", PageSize = Rotativa.Options.Size.A4};

  //  RotativaHelper.SaveHttpResponseAsFile("http://localhost:65425/BlankDashboard",  Server.MapPath("~\\PdfDownloads"));

    return pdf;

}

我想知道为什么会发生这种情况 - 我单击按钮,它调用 print ActionResult 方法 - 没有错误消息(我将其包装在 try 和 catch 块中)。我在同事的电脑上试过了,还是一样的问题!

非常感谢。

【问题讨论】:

  • 您可以使用 ViewAsPdf 代替 ActionAsPdf。所以你的代码看起来像这样 - return new ViewAsPdf("Index.cshtml", new { couponID }) { FileName = "testInvoice.pdf", CustomSwitches = "--print-media-type --header-center \"text\ “”};。很抱歉格式问题。
  • @KrishnrajRana 谢谢队友。这没有用;它要求视图的视图模型(Index.cshtml)。我实际上希望它显示一个动作的结果,所以我想知道为什么这不适用于 ActionAsPdf - 它适用于其他项目!
  • 好的,告诉我你的 CustomerDashboardVM() 返回什么??它是返回通用列表吗???我说的是这一行 - var model = new CustomerDashboardVM(); in Index() 方法
  • @KrishnrajRana 这实际上是页面的视图模型。但问题现在解决了,如下所示。非常感谢。

标签: asp.net asp.net-mvc asp.net-mvc-4 rotativa


【解决方案1】:

问题是我通过 Ajax 帖子在按钮单击事件上调用 ActionResult print() 方法。这显然行不通。

如果您将按钮替换为链接,它应该可以工作,该链接在其 URL 中有 print() 方法;即,只是 mvc 链接的工作方式..

【讨论】:

    【解决方案2】:

    好的,我明白你的错误了。您没有在 Index 方法中传递参数名称 voucherID

    所以现在您的代码如下所示:

    public ActionResult Index(int voucherID)  // Here you have to pass parameter
    {
        var model = new CustomerDashboardVM(voucherID);
        return View("Index", model);
    }
    

    Print() 方法看起来像这样 -

    public ActionResult Print(int voucherID)
    {
      return new ActionAsPdf(
                     "Index", 
                     new { voucherID = voucherID }) 
                     { 
                        FileName = "testInvoice.pdf",
                        PageSize = Rotativa.Options.Size.A4
                     };
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多