2013-01-07 21 views
5

私はRotativaツールを使用してpdfを表示しています。これは、次のコードで正常に動作します:Rotativa SaveAsダイアログでダウンロード

public ActionResult PreviewDocument() 
{ 

    var htmlContent = Session["html"].ToString(); 
    var model = new PdfInfo { Content = htmlContent, Name = "PDF Doc" }; 
    return new ViewAsPdf(model); 
} 

私はボタンをクリックする上でブラウザの「保存として」ダイアログを経由してPDFファイルをダウンロードする方法を知りたいと思ったし、いくつかのiframe内に表示しません。 「新しいViewAsPdf(モデル)」は、pdfデータを返します。

ありがとうございます。

答えて

5

あなたはこのようRotativa呼び出しに属性を追加することができます

return new PartialViewAsPdf("PreviewDocument", pdfModel) 
        { 
         PageSize = Size.A4, 
         FileName = "PDF Doc.pdf" 
        }; 

そして、それはあなたのためのファイルを作成します。 :)

+0

これはなぜ受け入れられた答えではありませんか?シンプルで、余分なコードをほとんど必要とせず、うまく動作します。 – Simon

3

私はついにこれを行う方法を得ました。

実際、rotativaのメソッド "return new ViewAsPdf(model)"はHttpResponseStreamを返します。私たちはほとんど何もできません。しかし、アクションがカスタム属性を使用して実行されると、レスポンスを変更/変更できます。アクションフィルタのOnResultExecuted()メソッドをオーバーライドできます。

コントローラのアクション

[HttpGet] 
[ActionDownload] //here a custom action filter added 
public ActionResult DownloadDocument() 
{ 
    var htmlContent = "<h1>sachin Kumar</hi>"; 

    var model = new PdfInfo {FtContent = htmlContent, FtName = "Populate Form"}; 
    return new ViewAsPdf(model); 
} 

カスタムアクションフィルタ:

public class ActionDownloadAttribute : ActionFilterAttribute 
{ 
    public override void OnResultExecuted(ResultExecutedContext filterContext) 
    { 
      //Add content-disposition header to response so that browser understand to download as an attachment. 
     filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf"); 

      base.OnResultExecuted(filterContext); 
    } 
} 
+1

なぜこの回答が「回答」と記載されていないのですか?これは、ライブラリにかかわらず、MVC ActionResultsを使用してPDFファイルを返すすべての人に便利です。私はMvcRazorToPdfを使用しています。iTextSharpに依存していますが、このコードはまだ動作しています。 –

+0

これは不必要に複雑なので、@ derekadkの答えを見てください。 FileName属性を追加するだけです。 return new ViewAsPdf(model){FileName = "file.pdf"}; –

3

あなたは新しいActionAsPdfを返すことができます。カスタム属性やその他必要なものはありません。 例:https://github.com/webgio/Rotativa/

public ActionResult PrintPreviewDocument() 
{ 
    return new ActionAsPdf("PreviewDocument") { FileName = "PDF Doc.pdf" }; 
} 

public ActionResult PreviewDocument() 
{ 

    var htmlContent = Session["html"].ToString(); 
    var model = new PdfInfo { Content = htmlContent, Name = "PDF Doc" }; 
    return View(model); 
} 
関連する問題