【问题标题】:Problems with downloading a PDF file to local PC将 PDF 文件下载到本地 PC 的问题
【发布时间】:2020-05-04 20:01:40
【问题描述】:

我正在尝试将使用 PDFsharp 创建的 PDF 文件从网络服务器下载到本地 PC 的下载文件夹。我用谷歌搜索了很多,尝试了很多都没有成功。我可以正确创建 PDF 文件并将其保存到磁盘 - 但我无法将其传输/下载到本地 PC 的下载文件夹。

我已经尝试了以下代码:

string filename = Server.MapPath("~\\Files\\Temp\\file.pdf");
document.Save(filename); //generate the physical file

MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();

那我做错了什么?

【问题讨论】:

  • 代码运行时会发生什么?什么不工作?
  • @NateBarbettini 什么也没发生 - 我在下载文件夹中看不到文件:-(
  • @MichaelEriksen 您是否尝试过在代码中添加日志记录或使用断点来调试程序?如果是,结果如何。
  • 前两行没有意义。当您只需要MemoryStream 时,为什么要写入本地文件?此处显示的 sn-p 周围的代码可能有问题。
  • @IliassNassibane 我已经调试了程序但没有成功。我在资源管理器中关注了它 - 但没有任何反应:-(

标签: c# asp.net pdf pdfsharp


【解决方案1】:

缺少Content-Disposition

Response.AddHeader("Content-Disposition", "attachment;filename=test.pdf"); 
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", binfile.Length.ToString());
Response.BinaryWrite(binfile);

如果你有更新面板,你必须将按钮设置为回发触发器

  <asp:UpdatePanel runat="server">
        <Triggers>
            <asp:PostBackTrigger ControlID="btnID" />
        </Triggers>
        <ContentTemplate></ContentTemplate>
    </asp:UpdatePanel>

【讨论】:

  • 不确定那是缺少的位。官网样本没有这行:pdfsharp.net/wiki/Clock-sample.ashx
  • @DragandDrop 正确链接。这个示例很可能是原始帖子中代码的原型(除了前两行没有意义)。
  • 我已尝试设置 Content-Disposition - 但我仍然无法下载文件 :-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2012-03-06
  • 2021-08-28
  • 1970-01-01
相关资源
最近更新 更多