21

I have a link on my page on click of which I am trying to generate a PDF document and then show the "Open - Save" prompt on the browser.

My HTML (reactjs component) has the below code where onclick calls the _getMyDocument function which then calls a Webapi method.

 <div className="row">
     <a href="#" onClick={this._getMyDocument.bind(this)}>Test Link</a>
 </div>  

_getMyDocument(e) {
            GetMyDocument(this.props.mydata).then(()=> {
   }).catch(error=> {

  });

My Controller has the below code

[HttpPost]
[Route("Generate/Report")]
public IHttpActionResult GetMyReport(MyData myData)
 {  
    byte[] myDoc = MyBusinessObject.GenerateMyReport(myData);
    var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(myDoc)
        };
        result.Content.Headers.ContentDisposition =
            new ContentDispositionHeaderValue("attachment")
            {
                FileName = "MyDocument.pdf"
            };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");

        var response = ResponseMessage(result);

        return response;
  }

Currently all the code executes but I don't get the file PDF download prompt. What am I doing wrong here?

Response object on success from the ajax call lokks like below

enter image description here

4
  • Did you try my solution. Please give your feedback.
    – ScrapCode
    Nov 25, 2016 at 10:08
  • I tried assigning the download URL following @Ermir Beqiraj's answer. var file = new Blob([response], { type: 'application/pdf' }); var fileURL = URL.createObjectURL(file); window.location = fileURL; This is downloading a PDF but an invalid one.
    – San
    Nov 25, 2016 at 21:36
  • what is MyBusinessObject.GenerateMyReport(myData); doing?.. is it making a request to another application? Nov 27, 2016 at 15:29
  • It makes a call to another library (inhouse) which uses Microsoft Report viewer to generate the report data (btye array).
    – San
    Nov 27, 2016 at 18:52

5 Answers 5

9

Your response from the server looks good. The missing part is that you are not handling this response from the client side in the correct way.

Lets assume that your resource url object looks like below in js. (i.e. you already know the resource url, if you don't know it yet, then you will need a separate call to the server to know the download url)

response.downloadUrl = app/media/fileId/document.pdf

All you need to do is set,

window.location = item.downloadUrl;

This will cause the browser to request a resource from the server, the response from the server must include Content-Disposition:attachment;. It will cause the browser to show the download dialog.

P.S. I have recently worked on a similar functionality. If you have questions please ask.

When you want to force the browser to show the download prompt for some files (or resources), you must include Content-Disposition:attachment; in the response header (which you already did).

3
  • I am using Microsoft report viewer to generate the pdf. There is no actual file present to set the download url. I have updated my question to include the response object.
    – San
    Nov 25, 2016 at 18:14
  • @San, by download url I mean any web service address (server request) which will return you pdf in response. So if call to Microsoft report viewer returns you the pdf, you need to assign the same call request to variable window.location
    – ScrapCode
    Nov 28, 2016 at 11:45
  • I have assigned the URL by doing - >var file = new Blob([response], { type: 'application/pdf' }); var fileURL = URL.createObjectURL(file)
    – San
    Nov 28, 2016 at 15:03
2

A simple way to do this is on your server to use GET method, and receive your data by query parameters.

Then in your client app you just have to create a classic link:

<a href="http://your-server.com/your-resource?param1=123&param2=456">Test Link</a>

Or use that simple js script if your want to manage it from your script logic:

window.open("http://your-server.com/your-resource?param1=123&param2=456");
2
+50

In our app(angular) we had to create an object url for that with a code like:

WebApi:

result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(data);
result.Content.Headers.Add("Content-Type", "application/pdf");
result.Content.Headers.ContentDisposition =
                        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "FileNameHere"
                        };

return result;

javascript:

// HttpCall in here
// On SuccessResponse
    var file = new Blob([data], {
                    type: 'application/pdf'
                    });
    var fileURL = URL.createObjectURL(file);
// create an anchor and click on it.
    var anchorTag = document.createElement('a');
    anchorTag.href = fileURL;
    anchorTag.target = '_blank';
    anchorTag.download = 'CouponOrder.pdf';
    document.body.appendChild(anchorTag);
    anchorTag.click();
    document.body.removeChild(anchorTag);
3
  • 1
    This downloads the file. But shows as damaged file when tried to open.
    – San
    Nov 25, 2016 at 19:42
  • @San, open the resulting file in notepad and see if your getting content that is not a pdf document.. namely a 500 error or some exception message from your call to MyBusinessObject.GenerateMyReport Nov 27, 2016 at 15:27
  • There is no exception. I have verfied the size of data returned by MyBusinessObject.GenerateMyReport and have also written it to a pdf file directly.
    – San
    Nov 27, 2016 at 19:05
1

Create Content Disposition and add it to your response header

var cd = new System.Net.Mime.ContentDisposition
{
    // for example foo.bak
    FileName = System.IO.Path.GetFileName(fileName),
    // always prompt the user for downloading, set to true if you want 
    // the browser to try to show the file inline
    Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
0

Your issue is that the GetMyDocument function will receive the PDF file as a server response, and currently you are doing nothing with that response. You need to handle the response in the then callback. Saving files from javascript is not entirely simple, so I would recommend using an external library such as filesaver.js to help you.

It will end up looking something like...

_getMyDocument(e) {
    GetMyDocument(this.props.mydata)
    .then((response)=> {
        const returnedFile = new Blob([response], { type: 'application/pdf'});
        saveAs(returnedFile);
    }).catch(error=> {

    });
8
  • Trying to use Filesaver.js how do I read the data fromt he response?. new File() expects two arguments and expects data be array.
    – San
    Nov 17, 2016 at 22:22
  • Looked into this a bit more and I think we will need to use blob rather than file - I have edited.
    – Alex Young
    Nov 17, 2016 at 22:26
  • var file = new Blob([response], { type: 'application/pdf' }); FileSaver.saveAs(file); This generates blank document. Does this require any conversion before passing to Blob?
    – San
    Nov 17, 2016 at 22:53
  • What about if you use new Blob([response.data]) ?
    – Alex Young
    Nov 17, 2016 at 22:55
  • It also downloads. but instead of blank page it gives invalid pdf data error on file open.
    – San
    Nov 17, 2016 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.