2017-06-02 65 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