0

I'm trying to add a feature to download a pdf file. I'm using ironpdf to generate the pdf file and I want the user to click and download it.

Here is my handler.

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();
        }

Here is my ajax request

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

I can see the output stream response in the browser but no download dialog. What am I doing wrong?

Thanks in advance.

  • did you check https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post ? – Falco Alexander Nov 07 '19 at 15:22
  • @FalcoAlexander I just did, it helped a lot, thanks. Now I can get the download but the pdf file is empty, the number of pages is right, but empty. I tried to change the dataType of my ajax call to arraybuffer, blob and same result. I also checked if the ironpdf api was returning the right values and it was working. Any idea what it could be? – Victor Costa Nov 07 '19 at 17:23
  • generating the PDF outside ASP.NET context is working fine? – Falco Alexander Nov 07 '19 at 23:23
  • @FalcoAlexander Sorry for the late response. Yes, it is working fine. – Victor Costa Nov 12 '19 at 14:24

1 Answers1

1

I had the same issue, and was able to get it to work with FileDownload on the frontend:

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

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

And my controller returns:

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

Here is js-file-download: https://www.npmjs.com/package/js-file-download

Lastly, and maybe most importantly, you need to set the response type in your api request on the frontend:

 responseType: 'arraybuffer'
KingV
  • 112
  • 7