【问题标题】:ASP.NET show PDF file to user instead of "save as" dialogASP.NET 向用户显示 PDF 文件而不是“另存为”对话框
【发布时间】:2010-10-05 06:50:28
【问题描述】:

我的 ASP.NET 应用程序使用下面的代码将 PDF 文件返回给用户

Context.Response.Clear();
Context.Response.ContentType = "application/pdf";
Context.Response.TransmitFile(optionEntityCmd.PathToSave);
Context.Response.End();

此代码显示另存为浏览器对话框,是否可以直接在浏览器中加载 PDF 文件而不是另存为对话框?

【问题讨论】:

    标签: asp.net pdf


    【解决方案1】:

    您可以附加 Content-Disposition 标头:

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

    【讨论】:

    • 是的,已经添加了,只是错过了在这里发帖 Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    • 糟糕,抱歉。你想要它内联,而不是附件。我误读了你的问题。请查看我的更新。
    • 我试图在浏览器中显示 PDF 文件而不保存文件。我正在使用 ASP.NET MVC。你能告诉我你是怎么解决你的问题的吗? stackoverflow.com/questions/32260041/…
    【解决方案2】:

    它是动态创建的文件吗?如果没有,您可以只使用超链接或响应。我相信重定向到它。

    【讨论】:

    • 文件存储在 HDD 上,但我不想在 IIS 上托管文件 URL 存储,我想隐藏实际文件位置,所以我使用 Context.Response.TransmitFile。我不确定您的建议如何解决问题。
    【解决方案3】:

    我不确定经典的 asp.net,但使用 mvc,将其流式传输给用户可以满足您的需求:

    MemoryStream stream = PDF.GeneratePDFByStream();
    stream.Flush(); //Always catches me out
    stream.Position = 0; //Not sure if this is required
    return stream;
    

    public static MemoryStream GeneratePDFByStream() {
        var doc1 = new Document();
        //use a variable to let my code fit across the page...
        string path = AppDomain.CurrentDomain.BaseDirectory + "PDFs";
        MemoryStream stream = new MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(doc1, stream);
        writer.CloseStream = false;
    
        // Actual Writing
        doc1.Open();
        // writing comes here, you will probably just load the PDF in a stream?
        doc1.Close();
    
        return stream;
    }
    

    你的 MVC 控制器会返回类似的东西

    return File(GetPDFStream(id), "application/pdf");
    

    所以,我知道这不是您正在寻找的确切答案,但也许您应该尝试将您的 PDF 流式传输给用户,因为它会在新标签页中打开它曾经测试过。

    从我的脑海中,你应该得到类似的东西:

    Response.Clear(); 
    Response.ContentType = "application/pdf"; 
    Response.OutputStream.Write( objMemoryStream.ToArray(), 0,        
    Convert.ToInt32(objMemoryStream.Length)); 
    Response.Flush(); 
    try { Response.End(); } catch{}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2021-10-25
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      相关资源
      最近更新 更多