0

在我的 Aspx 页面中,我有两个按钮,btnGenerateReceipt 用于生成收据,btnAddNew 用于添加新收据。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. 如何生成和打开 PDF 文件而不是 word Doc?

任何想法?

4

2 回答 2

4

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

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

打印文档可以使用ShellExecuteProcess带有动词的类来实现print,然后您可以使用 PDF-Creator 或 Bullzip 等 PDF 打印机生成 PDF 文件。

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

于 2012-04-16T09:21:08.770 回答
1

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

对于@Thorsten Dittmar 的答案。

单击 btnGenerateReceipt 按钮后,我的第二个按钮的单击功能不会触发。

Asp.net 使用无状态连接,所以你认为你写的内容会留在内存中吗?我认为根据我的理解它不应该起作用。创建响应内容,然后将其写入响应并刷新它。

如何生成和打开 PDF 文件而不是 word Doc?

要生成 pdf 参考this。使用 iTextSharp 之类的库生成 pdf,然后将它们导出/保存为 pdf。

参考: ASP.NET 4:在新浏览器中打开 HttpResponse?

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

您需要设置 Response 对象的 Content Type 并在 header 中添加 pdf 的二进制形式。有关详细信息,请参阅此帖子:参考:从 Asp.net 页面打开 PDF 文件

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 在新浏览器中打开?
检索信息后生成 pdf 文件
ASP.NET MVC:如何让浏览器打开并显示 PDF 而不是显示下载提示?

于 2012-04-16T09:42:30.077 回答