【问题标题】:Client download pdf file using Response.BinaryWrite ASP.NET c#客户端使用 Response.BinaryWrite ASP.NET c# 下载 pdf 文件
【发布时间】:2019-11-07 15:07:42
【问题描述】:

我正在尝试添加一项功能来下载 pdf 文件。我正在使用 ironpdf 生成 pdf 文件,我希望用户点击并下载它。

这是我的处理程序。

try
        {
            // Render any HTML fragment or document to HTML
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
            var data = PDF.MetaData;
            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.Buffer = true;
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", "attachment;filename=Cotacao.pdf");
            context.Response.BinaryWrite(PDF.BinaryData);
            context.Response.Flush();
        }
        catch (Exception e)
        {

        }
        finally
        {
            context.ApplicationInstance.CompleteRequest();
        }

这是我的 ajax 请求

function GeneratePDF() {
return $.ajax({
    type: "POST",
    url: "../Handlers/GeneratePDF.ashx",
    success: PDFSuccess,
    error: PDFError
});

我可以在浏览器中看到输出流响应,但没有下载对话框。我做错了什么?

提前致谢。

【问题讨论】:

  • @FalcoAlexander 我刚刚做了,它帮助很大,谢谢。现在我可以下载但pdf文件是空的,页数是正确的,但是是空的。我试图将我的 ajax 调用的 dataType 更改为 arraybuffer、blob 和相同的结果。我还检查了 ironpdf api 是否返回了正确的值并且它正在工作。知道它可能是什么吗?
  • 在 ASP.NET 上下文之外生成 PDF 工作正常吗?
  • @FalcoAlexander 抱歉回复晚了。是的,它工作正常。

标签: c# download ironpdf


【解决方案1】:

我遇到了同样的问题,并且能够让它与前端的 FileDownload 一起工作:

const FileDownload = require('js-file-download');

postHtmlString(data).then(response => {
   console.log(response)
   commit('pdfDownloading', false)
   FileDownload(response.data, 'example.pdf');
})...

我的控制器返回:

return File(pdf.BinaryData, "application/pdf");

这里是js文件下载:https://www.npmjs.com/package/js-file-download

最后,也许最重要的是,您需要在前端的 api 请求中设置响应类型:

 responseType: 'arraybuffer'

【讨论】:

  • 响应类型:'arraybuffer'。太棒了-谢谢KingV
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
相关资源
最近更新 更多