ASP.NET MVC AJAX 使用参数打开 PDF
ASP.NET MVC AJAX Open PDF with parameters
我正在使用 ASP.NET MVC,并且我构建了一个返回 PDF 文件的控制器。
我用 PDFsharp 构建 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 文件。除此之外,我想将一个参数传递给控制器。
据我所知,直接通过ajax打开文件并不容易。
所以我会建议另一条路线。
当 jquery 发送 ajax 生成 pdf,而不是 returning 文件时,return a link 到文件,您可以在其中打开 link
在新标签页中点赞 url。
所以首先将您的操作更改为 return a link:
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 url
$.getJSON( "your GenerateReport url", function( data ) {
window.open(data.url,'_blank');
}
我正在使用 ASP.NET MVC,并且我构建了一个返回 PDF 文件的控制器。
我用 PDFsharp 构建 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 文件。除此之外,我想将一个参数传递给控制器。
据我所知,直接通过ajax打开文件并不容易。
所以我会建议另一条路线。
当 jquery 发送 ajax 生成 pdf,而不是 returning 文件时,return a link 到文件,您可以在其中打开 link 在新标签页中点赞 url。
所以首先将您的操作更改为 return a link:
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 url
$.getJSON( "your GenerateReport url", function( data ) {
window.open(data.url,'_blank');
}