2017-06-02 66 views
0

我正在使用Asp.Net MVC,並且我構建了一個返回pdf文件的控制器。 我建有PdfSharp的PDF:Asp.net mvc ajax用參數打開pdf

public ActionResult GenerateReport(string Param) 
{ 
    // Create a new PDF document 
    PdfDocument document = new PdfDocument(); 
    document.Info.Title = "Created with PDFsharp"; 

    // Create an empty page 
    PdfPage page = document.AddPage(); 

    // Get an XGraphics object for drawing 
    XGraphics gfx = XGraphics.FromPdfPage(page); 

    // Create a font 
    XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); 

    // Draw the text 
    gfx.DrawString("Hello, World!", font, XBrushes.Black, 
    new XRect(0, 0, page.Width, page.Height), 
    XStringFormats.Center); 

    MemoryStream stream = new MemoryStream(); 
    document.Save(stream, false); 
    byte[] bytes = stream.ToArray(); 

    return File(bytes, "application/pdf"); 
} 

現在我的目標是從jQuery的發送一個AJAX請求,並在新標籤中打開PDF文件。除此之外,我想將參數傳遞給控制器​​。

在此先感謝!

回答

1

據我所知,通過ajax直接打開文件並不容易。

所以我會建議另一條路線。

當獲取生成的jQuery發送AJAX爲PDF格式,而不是返回文件,返回鏈接到文件,在其中您可以在新標籤中打開網址一樣該鏈接 。

所以首先改變你的行動來回報鏈接:

public ActionResult GenerateReport(string Param) 
{ 
    // same as before 
    .... 

    // save your pdf to a file 
    File.WriteAllBytes("result.pdf", memoryStream.ToArray()); 

    // get url to that pdf which can be browsed 
    var pdfUrl = "some location which url can browse"; 

    return Json(new {url: pdfUrl}, JsonBehaviour.AllowGet); 
} 

然後在你的jQuery AJAX解僱的觀點,當得到的結果回來,只是瀏覽到PDF網址

$.getJSON("your GenerateReport url", function(data) { 
    window.open(data.url,'_blank'); 
} 
+0

大解決方法:) – Anokrize