0

ASP.NET MVC 4 controller returs pdf:

    public ActionResult Pdf()  {

        byte[] result = CreatePDF();
        var ms = new MemoryStream(result);
        return new FileStreamResult(ms, "application/pdf");
    }

Results appears in Chrome browser window. If user right-clicks in pdf and selects Save as Chrome offers Pdf.pdf as file name to save.

How to specify other default file name like Order 123.pdf ?

Chrome Developer Tool show that file nime is not speficied in response:

Cache-Control:private, s-maxage=0
Content-Length:30814
Content-Type:application/pdf
Date:Fri, 14 Oct 2016 19:18:09 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
Andrus
  • 26,339
  • 60
  • 204
  • 378

2 Answers2

1

Try using File method.

public FileResult Pdf()  
{
    byte[] result = CreatePDF();
    string fileName = "Order 123.pdf";
    return File(result, "application/pdf", fileName);
}

There is no need to wrap result in MemoryStream

Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59
  • In this case pdf is not shown in Chrome. Only downloaded file icon appears. How to force browser to show pdf immediately, without extra click in downloaded file in this case ? – Andrus Oct 14 '16 at 19:43
  • 1
    @Andrus, according to [answer on SO](http://stackoverflow.com/a/19412687/1380428) you need to set `Content-Disposition: inline` – Adil Mammadov Oct 14 '16 at 19:48
0

FileStreamResult has a FileDownloadName property which you can set

public ActionResult Pdf()
{
    byte[] result = CreatePDF();
    var ms = new MemoryStream(result);
    var fs = new FileStreamResult(ms, "application/pdf") {FileDownloadName = "Hello.pdf"};
    return fs;
}

This is exactly what happens when you call the ControllerBase.File method's overload which takes the file name.

public ActionResult Pdf()
{
    byte[] result = CreatePDF();      
    return File(result ,"application/pdf","Hello.pdf");
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • If `FileDownloadName` is specified or `File` result is returned pdf is not shown in Chrome. Only downloaded file icon appears and extra click is required to show pdf. How to force browser to show pdf immediately, without extra click in downloaded file ? – Andrus Oct 14 '16 at 19:49
  • If you are trying to download. this depends on the user browser (download) settings. Based on the settings it will either download the file to your download folder or open to the user. If you absolutely want to show the file to use. You should use FileStringResult. In that case, there is no reason to specify a file name(user is not going to download it). See [this](http://stackoverflow.com/questions/34498184/difference-between-filecontentresult-and-filestreamresult/34498356#34498356) – Shyju Oct 14 '16 at 19:52
  • User may want to save order and expect that offered file name contains order number – Andrus Oct 14 '16 at 20:09