c# - 如何在新选项卡中打开来自 Response MemoryStream 的 PDF
问题描述
我不确定是否是这样做的好方法。我想在新的浏览器选项卡中显示 PDF。
我有一个生成 MemoryStream 并返回到我的 ajax 调用的方法。这样做的好方法是什么?
我的 Ajax 调用:
$("#selector").click(function () {
urlToFunction = "/Controller/Function";
$.ajax({
url: urlToFunction,
data: ({ id: 12345 }),
type: 'GET',
success: function (response) {
???? here
},
error:
function (response) {
}
});
});
[HttpGet]
public async Task Print(int? id)
{
var ms = GETMemoryStreamPDF();
Response.ContentType = "application/pdf; charset=utf-8";
Response.Headers.Add("content-disposition", "attachment;filename=" + randomName + ".pdf;charset=utf-8'");
await Response.Body.WriteAsync(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
我的问题在这里:
success: function (response) {
???? here
},
在新选项卡中显示我的 PDF 的最佳做法是什么?
解决方案
您可以尝试以下代码:
Javascript
$("#selector").click(function (e) {
e.preventDefault();
window.open('@Url.Action("ActionName", "ControllerName", new { id=12345})', '_blank');
});
控制器
[HttpGet]
public IActionResult Pdf(int? id)
{
MemoryStream memoryStream = new MemoryStream();
PdfWriter pdfWriter = new PdfWriter(memoryStream);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
Document document = new Document(pdfDocument);
document.Add(new Paragraph("Welcome"));
document.Close();
byte[] file = memoryStream.ToArray();
MemoryStream ms = new MemoryStream();
ms.Write(file, 0, file.Length);
ms.Position = 0;
return File(fileStream: ms, contentType: "application/pdf", fileDownloadName: "test_file_name" + ".pdf");
}
推荐阅读
- java - 使用 Java 调用 REST API 和解析 JSON 数据的最简单方法
- java - GUI循环更新
- python - 储能优化 pyomo 约束
- python - 从附加模块到主模块的导入类问题
- python - 向数据集添加一列,其值按组填充
- javascript - 使用AppleScript将击键发送到osx上的后台应用程序?
- django - 为什么 my_task.delay() 仅适用于任务模块,而不适用于模型或视图模块?
- magit - 如何在 Magit 中查找文件何时被删除
- python - 我无法让 Python 日志记录模块从不同的模块写入日志文件
- mbtiles - 如何让 Kepler GL 将本地 MBTiles 服务器用于基本地图而不是在线地图?