IHttpHandler returning BinaryWrite resulting in blank pdf file

21 views Asked by At

I have this ajax call that is posting data to this IHttpHandler. This handler is returning a BinaryWrite. In the JS success function I am using the Blob([data] from that pdfByte and wanted to download the file. I can see the file is different when I open the pdf file in notepad but I am not sure why. I have attached some samples of the file and the logic I am using.

IHttpHandler

context.Response.Clear();
context.Response.AddHeader("Pragma", "public");
context.Response.AddHeader("Expires", "0");
context.Response.AddHeader("Content-Type", "application/octet-stream");
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
context.Response.AddHeader("Content-Transfer-Encoding", "binary");
context.Response.AddHeader("Content-Length", pdfByte.Length.ToString());
context.Response.BinaryWrite(pdfByte);
context.Response.End();

JS Code

$.ajax({
    type: 'POST',
    url: 'GenerateSubmissionPDF.ashx',
    data: { "PDFObject": data, "SubmissionId": submissionId },
    datatype: "JSON",
    success: function (data, textStatus, xhr) {
        console.log(data);
        var type = xhr.getResponseHeader("Content-Type");
        var fileName = xhr.getResponseHeader('content-disposition').split('filename=')[1].split(';')[0]
        var blob = new Blob([data], { type: type });

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();

Sample blank file pdfByte

Sample working file

enter image description here

0

There are 0 answers