在C#中打开文件

时间:2012-04-16 09:16:22

标签: c# asp.net

在我的Aspx页面中,我有两个按钮,btnGenerateReceipt用于生成收据,btnAddNew用于添加新的receord。 btnGenerateReceipt的OnClick事件我正在生成并打开收据,如下所示。

 protected void onGenerateReceipt(object sender, EventArgs e)
    {
          try
            {
                    byte[] document = receiptByte;
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.Buffer = true;
                    Response.ContentType = "application/vnd.ms-word";
                    Response.AddHeader("content-disposition", "inline;filename=" + "Receipt" + ".doc");
                    Response.Charset = "";
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(document);
                    //Response.Flush();
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                //Response.End();
            }
        }
    }

这将打开打开/保存/取消对话框,以下是我的问题,

  1. 我需要word文档在没有对话框的情况下自动打开。
  2. 点击btnGenerateReceipt按钮后,我的第二个按钮的点击功能没有激活。
  3. 如何生成& Open PDF文件而非Word Doc?
  4. 有什么想法吗?

2 个答案:

答案 0 :(得分:4)

服务器发送的内容由Web浏览器处理。您无法从服务器端代码控制浏览器是否打开,默认情况下保存或询问用户,因为这是浏览器设置。

修改
关于生成PDF的第二个问题:有很多库可以生成PDF。但是,如果您已经准备好Word文件,一种解决方案是将Word文档打印到PDF打印机并发送生成的PDF。

使用ShellExecuteProcess类和动词print打印文档,然后您可以使用PDF-Creator或Bullzip等PDF打印机生成PDF文件

这是我尝试而不是“手动”生成PDF文件。

答案 1 :(得分:1)

  

我需要在没有对话框的情况下自动打开word文档。

对于@Thorsten Dittmar回答的答案。

  

点击btnGenerateReceipt按钮后,我的第二个按钮的点击功能没有激活。

Asp.net使用无状态连接,因此您认为您的书面内容将保留在内存中。我认为它不应该按照我的理解工作。创建响应内容,然后将其写入响应并刷新它。

  

如何生成& Open PDF文件而非Word Doc?

生成pdf参考this。使用iTextSharp like library生成pdf,然后将它们导出/保存为pdf。

参考: ASP.NET 4: HttpResponse open in NEW Browser?

Response.AppendHeader("Content-Disposition", "inline; filename=foo.pdf");

您需要设置Response对象的Content Type,并在标题中添加pdf的二进制形式。有关详情,请参阅此帖子: 参考:Opening a PDF File from Asp.net page

private void ReadPdfFile()
    {
        string path = @"C:\Swift3D.pdf";
        WebClient client = new WebClient();
        Byte[] buffer =  client.DownloadData(path);

        if (buffer != null)
        {
            Response.ContentType = "application/pdf"; 
            Response.AddHeader("content-length",buffer.Length.ToString()); 
            Response.BinaryWrite(buffer); 
        }

    }

参考链接:
ASP.NET 4: HttpResponse open in NEW Browser?
Generate pdf file after retrieving the information
ASP.NET MVC: How can I get the browser to open and display a PDF instead of displaying a download prompt?