0
votes

I have created a method that creates and saves a pdf to a directory in the project. I am unable to get this file to download after it is created however. I have tried several options i have seen on stack overflow, and numerous other sites. I can see PDF content in the response in firebug, and i can open the file manually, but no file download. Please help.

Controller

    public class SignatureController : Controller
    {
    // GET: Signature
    public FileContentResult Index(string orderNumber)
    {
        var pdfFile = DocumentGenerator.GenerateSignedDocument(orderNumber);

        byte[] filedata = System.IO.File.ReadAllBytes(pdfFile);
        string contentType = MimeMapping.GetMimeMapping(pdfFile);

        System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
        {
            FileName = pdfFile,
            Inline = true,
        };

        Response.AppendHeader("Content-Disposition", cd.ToString());

        return File(filedata, contentType);
    }
}

PDF Generator

        public static string GenerateSignedDocument(string orderNumber)
        {

      ...............

        string currentDate = DateTime.Now.ToString("MMddyyyy");

        string fileName = HostingEnvironment.MapPath(pdfTempPath) + orderNumber + currentDate + ".pdf";

        pdfDocument.Save(fileName);
        return fileName;
    }

Header is returning

Cache-Control
private Content-Disposition attachment; filename="signed document.pdf" Content-Encoding
gzip Content-Type
application/pdf Date
Thu, 16 Jul 2015 16:58:29 GMT Server
Microsoft-IIS/8.0 Transfer-Encoding
chunked Vary
Accept-Encoding X-AspNet-Version
4.0.30319 X-AspNetMvc-Version 5.2 X-Powered-By
ASP.NET X-SourceFiles
=?UTF-8?B?QzpcVXNlcnNccmphbWVzXFNvdXJjZVxXb3Jrc3BhY2VzXEN1c3RvbWVyUGlja1VwXEN1c3RvbWVyUGlja1VwLldlYlxTaWduYXR1cmVcSW5kZXg =?=

1

1 Answers

0
votes

Set Inline to false or omit it. That way the the header is attachment (instead of inline).

e.g (this sample downloads a file in file system)

public FilePathResult DownloadPdf()
{
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = "foo.pdf"
        //Inline = false //false or omit
    };


    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File("~/files/somefile.pdf", "application/pdf");
}

The header will look like: Content-Disposition:attachment; filename=foo.pdf


File name is what you set - sample is obtaining a pdf from file system only because I don't generate one on the fly (so your code is fine for byte result). The key item is to return the correct header attachment - you can even set that manually

Response.AppendHeader("Content-Disposition", "attachment; filename=" + pdfFile);

and not have to use System.Net.Mime.ContentDisposition. BTW, is your pdfFile variable a string (you're using that as the FileName property)?

Hth...