如何将文件附加到页面上的响应渲染?

时间:2011-07-25 13:55:51

标签: asp.net pdf popup export render

我在渲染页面时收到页面加载的HTML结果,然后将pdf文件附加到浏览器:

 protected override void Render(HtmlTextWriter writer)
    {
        if (isPdfExport)
        {
            var stringWriter = new StringWriter();
            var htmlWriter = new HtmlTextWriter(stringWriter);
            base.Render(htmlWriter);
            var pageHtml = stringWriter.ToString();
            Write(GetBytes(pageHtml));
        }
        else
        {
            base.Render(writer);
        }
    }

    private void Write(byte[] bytes)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=MyFile.pdf; size=" + bytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(bytes);
        response.Flush();
        response.End();
    }

单击导出按钮时,它会将isPdfExport字段设置为true,以便Render方法知道它应该导出。

问题是在页面上呈现了一些二进制数据,而我希望看到一个包含pdf文件的弹出对话框。

如果导出发生在Render之前的事件处理程序上,它可以正常工作并带来一个弹出窗口,但是,我无法在Render事件处理程序之前随时访问页面的html数据。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

为什么不设置.pdf处理程序,所以你要做的就是提供一个到.pdf文件的标准超链接,然后提示弹出窗口保存文件?

e.g。

<a href="/Correspondence/12345.pdf">Download the PDF</a>

为此,首先需要在“Correspondence”子目录中的web.config中定义一个处理程序,以便处理.pdf个文件:

<configuration>
    <system.web>
        <httpHandlers>
            <add verb="*" path="*.pdf" type="PdfHandler"/>
        </httpHandlers>
    </system.web>
</configuration>

然后你编写处理程序本身,就像这样应该这样做:

Public Class PdfHandler
    Implements IHttpHandler

    Public ReadOnly Property IsReusable As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
            If FileInvalid Then // Maybe want to check the path is valid, or they are authorised to see it, etc.
                context.Response.StatusCode = 404
                context.Response.StatusDescription = "404 Not Found"
                context.Response.Flush()
            Else
                context.Response.ContentType = "application/pdf"
                context.Response.AddHeader("Content-Disposition", "attachment; filename=MyPDF.pdf")

                context.Response.BinaryWrite(PDFBinaryContent) // E.g. Loaded from a database, disk, etc                
            End If
    End Sub
End Class

最后,只需将IIS配置为将.pdf请求传递给.NET引擎(如果合适,请不要忘记关闭“验证文件存在”。应该这样做。