PDF force download as opposed to open in browser

2.1k Views Asked by At

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();
}
2

There are 2 best solutions below

2
On BEST ANSWER

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();
}
0
On

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";