3

I am using RazorPDF and I would like to force download the PDF as opposed to open in browser tab. How do I do this? Thanks

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Id)
{
    return RedirectToAction("Pdf");
}

public PdfResult Pdf()
{
    // With no Model and default view name.  Pdf is always the default view name
    return new PdfResult();
}
MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200

2 Answers2

8

Try adding the content-disposition header before returning the PDFResult object.

public PdfResult Pdf()
{
  Response.AddHeader("content-disposition", "attachment; filename=YourSanitazedFileName.pdf");

  // With no Model and default view name.  Pdf is always the default view name
  return new PdfResult();
}
IronGeek
  • 4,764
  • 25
  • 27
  • IronGeek, I don't have any .pdf file to return. So I am not sure if your code will work in my case. Thanks – dotnet-practitioner Jan 13 '14 at 01:19
  • @dotnet-practitioner You don't have to, it could be any name. You could even use random name for it. The browser will use that name as the filename to download in the Download File Dialog. – IronGeek Jan 13 '14 at 02:32
0

You should look at the "Content-Disposition" header; for example setting "Content-Disposition" to "attachment; filename=FileName.pdf" will prompt the user (typically) with a "Save as: FileName.pdf" dialog, rather than opening it. This, however, needs to come from the request that is doing the download, so you can't do this during a redirect. However, ASP.NET offers Response.TransmitFile for this purpose. For example (assuming you aren't using MVC, which has other preferred options):

Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Response.TransmitFile(filePath);
Response.End(); 

If You Are try to open then the file in Api Convert Stream to BytesArray and then Fill the content

            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            FileStream stream = File.OpenRead(path);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();           
            result.Content = new ByteArrayContent(fileBytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "FileName.pdf";            
Skull
  • 1,204
  • 16
  • 28