2

I have a POST request for a PDF document in an APIController, here's the code:

Generator pdfGenerator = new Generator();         
MemoryStream ms = pdfGenerator.Generate();

var response = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new StreamContent(ms)
};

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "Tag.pdf"
};
 response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;

when I send my file to angular with a GET request everything works fine and I can download the pdf using:

 $window.open('my_url');

A well formed 28K pdf file is created in the download folder.

But when I changed my request to a POST the file is malformed.

var pdfGetter = $resource('my_url', {}, {            
    sendPDFTag: { method: 'POST', url: 'my_url', responseType: 'arraybuffer' }
});

pdfGetter.sendPDFTag(info, function(data) {
    var file = new Blob([data], { type: 'application/pdf' });
    var fileURL = URL.createObjectURL(file);
    $window.open(fileURL);;
});

I tried using the FileSaver.js and I get a bad 1K pdf file in my download folder.

pdfGetter.sendPDFTag(info, function(data) {
    var file = new Blob([data], { type: 'application/pdf' });
    saveAs(file, 'Tag.pdf');
});

What could the problem be?

Thanks

Ana Franco
  • 1,611
  • 3
  • 24
  • 43

1 Answers1

1

I found the solution to my problem in this question: pdf-js-render-pdf-using-an-arraybuffer-or-blob-instead-of-url

The problem was with the ng-resource that returns a promise instead of the arraybuffer, so you need to transform the data before you process the promise.

Here is the corrected code:

var pdfGetter = $resource(myUrl, {}, {
    sendPDFTag: { method: 'POST', url: myUrl + "/getPdfWithPost", responseType: 'arraybuffer', 
        transformResponse: function(data, headersGetter) {
            // Stores the ArrayBuffer object in a property called "data"
            return { data : data };
        }
    }
});

var pdfGetter = pdfGetter.sendPDFTag(info);
pdfGetter.$promise.then(function () {
    var data = pdfGetter.data;
    var file = new Blob([data], { type: 'application/pdf' });
    var fileURL = URL.createObjectURL(file);
    $window.open(fileURL);
});

Thank you

Community
  • 1
  • 1
Ana Franco
  • 1,611
  • 3
  • 24
  • 43