VSO
VSO

Reputation: 12646

Web API 2 - Return Pdf, Show/Download Received Pdf File on Client (AngularJs)

This is the code in my Web API 2 controller:

//pdfBytes is a valid set of...pdfBytes, how it's generated is irrelevant
Byte[] pdfBytes = pdfConverter.GeneratePdf(myPdfString);

//using HttpResponseMessage instead of IHttpActionResult here because I read
//that the latter can cause problems in this scenario
var response = new HttpResponseMessage();

//Set reponse content to my PDF bytes
response.Content = new ByteArrayContent(pdfBytes);

//Specify content type as PDF - not sure if this is necessary
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

return response;

How do I trigger the browser to automatically download the PDF or open it in a new window once I have received the PDF on the client? (Note - I am not sure if byte array is the format I want to receive here).

callToGetPdfFromDb()
    .success(function (pdfFromWebApi) {
        console.log('Got pdf...'');
        //How do I show the received PDF to the user? 
    });

I am pretty new to working with any sort of file downloads/uploads, so I apologize if I am missing something very basic. I am perfectly happy with pointers in the right direction as a response.

Upvotes: 2

Views: 7056

Answers (2)

VSO
VSO

Reputation: 12646

There is an answer here that works. The complete call/response that works with the C# code in the question. Note, I am leaving the question because I think it's a bit more specific than the existing ones, and I had a hard time finding the answer:

    $scope.getPdf= function(){
        var pdfReportUrl = yourBaseUrl+ '/generatepdf';

        var runDbCallToGetPdf =  function(){
            return $http({
                method: 'GET',
                url: pdfReportUrl,
                responseType:'arraybuffer'
            });
        };

        runDbCallToGetPdf ()
            .success(function (pdfBytes) {
                var pdfFile = new Blob([pdfBytes], {type: 'application/pdf'});
                var pdfFileUrl = URL.createObjectURL(pdfFile );
                window.open(pdfFileUrl);
            });
    };

Upvotes: 3

tebereth
tebereth

Reputation: 189

Instead of calling the Web Api endpoint from angular you can just open it in a new window (or tab).

var getUrl = //path to web api endpoint to get generated pdf
// make sure to inject $window service
$window.open(getUrl, "_blank");

If the MIME type for the response is set correctly the browser should be able to open the pdf.

Upvotes: 1

Related Questions