ITextSharp - 谷歌浏览器保存按钮将PDF保存为.ASPX页面

时间:2015-05-08 19:31:28

标签: c# asp.net google-chrome .net-3.5 itextsharp

我目前正在使用ITextSharp使用.Net 3.5 ASPX页面创建PDF。一切运作良好..唯一的问题是在chrome(版本42.0.2311.135)中单击保存按钮或右键单击并说保存,因为它尝试保存为.aspx页面。使用Firefox或Internet Explorer时,我不会遇到这些问题。我尝试禁用chrome PDF查看器,它只是自动将文件保存为aspx文件。我已经将下面的代码包含在按钮点击中。我假设这是我处理响应的方式?有任何想法吗?

enter image description here

iTextSharp.text.Document d = new iTextSharp.text.Document(PageSize.A4, 20, 20, 20, 20);

using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{

 w = PdfWriter.GetInstance(d, stream);

 //add stuff to itext document

 d.Close();

 byte[] b = stream.ToArray();
 stream.Close();


 Response.Clear();
 Response.ContentType = "application/pdf";
 Response.BinaryWrite(b);
 HttpContext.Current.ApplicationInstance.CompleteRequest();

}

更新 想要分享我的发现,以免它让人头疼。添加Response.AddHeader(" Content-Disposition"," inline; filename = myfilename.pdf");修复了大部分问题,但我仍然遇到谷歌浏览器查看器中的保存按钮问题(打印工作正常,但保存提示用户保存页面而不是pdf)。通过单击按钮在.aspx页面上生成PDF。生成后,我清除响应并将PDF转储到页面。页面上的表单元素没有方法集,所以它是作为post发送的(通过fiddler发现)。此页面是通过iframe共享的。我在页面上将方法更改为GET,现在所有内容都按预期工作。

1 个答案:

答案 0 :(得分:2)

尝试:

Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.pdf");