15

The following returns a PDF which the browser tries to directly display inline. This works correctly. However, if I try to download the file, the download name is not "myPDF.pdf", but instead the ID in the route (myapp/controller/PDFGenerator/ID). Is it possible to set the file download name to be "myPDF.pdf"?

public FileStreamResult PDFGenerator(int id)
{
    MemoryStream ms = GeneratePDF(id);

    byte[] file = ms.ToArray();
    MemoryStream output = new MemoryStream();
    output.Write(file, 0, file.Length);
    output.Position = 0;
    HttpContext.Response.AddHeader("content-disposition", 
    "inline; filename=myPDF.pdf");

    return File(output, "application/pdf", fileDownloadName="myPDF.pdf");
}
user1620141
  • 315
  • 1
  • 2
  • 16

3 Answers3

19

No, this is not possible with a PDF displayed inline. You could achieve this if you send the Content-Disposition header with as an attachment:

public ActionResult PDFGenerator(int id)
{
    Stream stream = GeneratePDF(id);
    return File(stream, "application/pdf", "myPDF.pdf");
}

Also notice how I removed the unnecessary MemoryStream you were using and loading the PDF in memory where you could have directly streamed it to the client which would have been far more efficient.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Yes, that was the whole point of my answer. If you want the file to be displayed inline you **cannot** specify a filename. If you display the PDF file inline, it is opened with the plugin associated on the client machine to open PDF files. Behavior will vary between the various plugins. – Darin Dimitrov Apr 07 '13 at 13:09
  • @Nalan M answer could force it to download, in most cases. So, it shouldn't be said as not possible. – Syakur Rahman Feb 26 '16 at 09:05
  • One question, who takes care of disposing the stream here? – Legends Apr 09 '16 at 22:03
  • @Legends the FileStreamResponse will dispose it - see http://stackoverflow.com/a/3086291 – Jono Job Jul 26 '16 at 05:11
6

If you are using FileStreamResult to download the file, try using this in controller

Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Nalan Madheswaran
  • 10,136
  • 1
  • 57
  • 42
  • On of my exporting to PDF actions returns data as **plain text** replacing **iframe** instead of attachment type. I had to add these two lines to force it to popup the save dialog. – OldTrain Apr 09 '15 at 06:33
0

It is possible by making the id a string which represents the file name without the extension.

public ActionResult PDFGenerator(string id, int? docid)
{
    Stream stream = GeneratePDF(docid);
    return new FileStreamResult(stream , "application/pdf");
}

The url then then end like this

  ..PDFGenerator/Document2?docid=15
Community
  • 1
  • 1
F Snyman
  • 499
  • 1
  • 5
  • 6