首页 > 解决方案 > PDF 文件未在 .aspx 页面上下载为 pdf

问题描述

所以我有一个使用此代码预览 PDF 文件的代码:

System.Net.WebClient client = new System.Net.WebClient();
        //text box holds the path to the original pdf file in a folder
        Byte[] Thisbuffer = client.DownloadData(TextBox.Text);

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

当我使用以下选项进行下载时,它可以在 chrome、IE 和 Edge 中查看 PDF 文件,但在 chrome 上查看: 看图片

它将文件下载为 .aspx 而不是 .pdf。这仅在 chrome 中发生,而不在 IE 或 Edge 中发生。

我试过Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf");了,这个自动下载的文件不允许它在下载前查看。任何帮助表示感谢谢谢!

标签: c#asp.netpdfdownload

解决方案


Chrome 的内置 PDF 查看器下载按钮指向 PDF 的原始 URL,因此在您的情况下是 aspx 页面。此问题的一个潜在解决方案是创建一个新的 aspx 页面,该页面在 page_load 上加载 PDF,然后以新页面为目标。

不确定您的原始代码块是如何被调用的,但您应该能够插入带有<a>锚标记的目标页面或使用Response.Redirect().

目标页面加载示例:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["RequestedPath"] != null)
    {
        System.Net.WebClient client = new System.Net.WebClient();
        //text box holds the path to the original pdf file in a folder
        Byte[] Thisbuffer = client.DownloadData(Request.QueryString["RequestedPath"]);

        if (Thisbuffer!= null)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=myPDFfile.pdf");
            HttpContext.Current.Response.AddHeader("content-length", Thisbuffer.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.BinaryWrite(Thisbuffer);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest(); 
        }
    }
}

推荐阅读