![](/img/trans.png)
[英]How to open PDF file in a new tab or window instead of downloading it (using asp.net)?
[英]How to open PDF file in a new tab or window instead of downloading it using C# and ASP.NET MVC?
我有发票屏幕,在此屏幕上有很多订单可用,所以当我们创建发票时,我们需要填写一张表格,所以我想解决的方法是当我提交此发票表格或单击此提交按钮时,pdf应该在新窗口中打开标签。 我想向您澄清,我们不会在任何地方保存该pdf文件。
<div class="modal-footer custom-no-top-border">
<input type="submit" class="btn btn-primary" id="createdata" value="@T("Admin.Common.Create")" />
</div>
当我单击此按钮时,应该在新选项卡中打开pdf。
这是PDF代码
[HttpPost]
public virtual ActionResult PdfInvoice(int customerOrderselectedId)
{
var customerOrder = _customerOrderService.GetCustomerOrderById(customerOrderselectedId);
var customerOrders = new List<DD_CustomerOrder>();
customerOrders.Add(customerOrder);
byte[] bytes;
using (var stream = new MemoryStream())
{
_customerOrderPdfService.PrintInvoicePdf(stream, customerOrders);
bytes = stream.ToArray();
}
return File(bytes, MimeTypes.ApplicationPdf, string.Format("order_{0}.pdf", customerOrder.Id));
}
当我单击按钮时,此代码下载pdf。
谢谢 !!
最重要的是Controller.File()
与[HttpGet]
,因此您应该执行以下步骤:
1)将HTTP方法类型从[HttpPost]
更改为[HttpGet]
并设置return File()
而不指定fileDownloadName
参数(使用接受2个参数的Controller.File()
重载)。
[HttpGet]
public virtual ActionResult PdfInvoice(int customerOrderselectedId)
{
var customerOrder = _customerOrderService.GetCustomerOrderById(customerOrderselectedId);
var customerOrders = new List<DD_CustomerOrder>();
customerOrders.Add(customerOrder);
byte[] bytes;
using (var stream = new MemoryStream())
{
_customerOrderPdfService.PrintInvoicePdf(stream, customerOrders);
bytes = stream.ToArray();
}
// use 2 parameters
return File(bytes, MimeTypes.ApplicationPdf);
}
2)处理该按钮的click
事件(优选使用<input type="button" .../>
)并使用_blank
选项,或者使用具有target='_blank'
属性的锚标记( <a>
):
$('#createdata').click(function (e) {
// if using type="submit", this is mandatory
e.preventDefault();
window.open('@Url.Action("PdfInvoice", "ControllerName", new { customerOrderselectedId = selectedId })', '_blank');
});
之所以不使用fileDownloadName
参数,是因为该参数在提供文件名时设置了Content-Disposition: attachment
,否则,如果您省略它或使用null
值,则将自动设置Content-Disposition: inline
。
请注意,由于使用的是FileResult
,因此不应在return File()
之前使用Response.AddHeader
设置Content-Disposition
,因为这样做会发送多个Content-Disposition
标头,从而导致浏览器无法显示文件:
// this is wrong way, should not be used
Response.AddHeader("Content-Disposition", "inline; filename=order_XXX.pdf");
return File(bytes, MimeTypes.ApplicationPdf);
相关问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.