2

I am using below code which used to download SSRS report in pdf format:

 string URL = "http://ssrs-test.com/ReportS/?/UAT_FOLDER";
 URL = URL + "&SRNo=122&rs:Command=Render&rs:Format=pdf";

 System.Net.HttpWebRequest Req = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(URL);

 Req.Method = "GET";
 string path = @ "E:\New folder\Test.pdf";
 System.Net.WebResponse objResponse = Req.GetResponse();
 System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
 System.IO.Stream stream = objResponse.GetResponseStream();
 byte[] buf = new byte[1024];
 int len = stream.Read(buf, 0, 1024);

 while (len > 0) {
  fs.Write(buf, 0, len);
  len = stream.Read(buf, 0, 1024);
 }
 stream.Close();
 fs.Close();

Which perfectly creates a pdf file in the specified path E:\New folder\, what I am trying to do is:

I need download it on browser as we were doing in the asp.net with Response.Write() and Response.End() etc.

Can I do the same in the ASP.Net Core?

What I tried:

return new PhysicalFileResult(@"with_samplepdf_file", "application/pdf");  -- Not worked

var stream = new FileStream(@"with_samplepdf_file", FileMode.Open);
return new FileStreamResult(stream, "application/pdf");   -- Not worked - Nothing happening on the browser

var file = @"with_samplepdf_file/pdf";

// Response...
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
   FileName = file,
   Inline = displayInline  // false = prompt the user for downloading;  true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");

return File(System.IO.File.ReadAllBytes(file), "application/pdf"); 
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • If you want to display the PDF in the browser (as opposed to prompt to save it on disk) then the server-side code needs to specify a `Content-Disposition: Inline` header. See, for example, [ASP.Net Core Content-Disposition attachment/inline](https://stackoverflow.com/questions/38897764/asp-net-core-content-disposition-attachment-inline). – AlwaysLearning Oct 10 '19 at 06:57
  • @AlwaysLearning Tried this:https://stackoverflow.com/a/38909848/7124761 but not happing anything on chrome – Prashant Pimpale Oct 10 '19 at 07:03
  • What kind of asp.net core project are you using? razor pages? mvc? – Harry Oct 10 '19 at 07:10
  • @Harry Its MVC.. – Prashant Pimpale Oct 10 '19 at 07:12

3 Answers3

8

First,you need to be sure that you have uploaded the file in your project.

Here is a simple demo about how to download pdf on the browser in Asp.Net Core:

1.View:

<a asp-action="GetPdf" asp-controller="Users">Download</a>

2.Controller(be sure that the file have been exsit in wwwroot/file folder):

 [HttpGet]
 public ActionResult GetPdf()
 {
     string filePath = "~/file/test.pdf";
     Response.Headers.Add("Content-Disposition", "inline; filename=test.pdf");
     return File(filePath, "application/pdf");           
 }

3.Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //...
   app.UseStaticFiles();
   //...
}

4.Result: enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72
3

I copied my pdf into the solution and changed the copy to output directory property to copy.

index.cshtml which opens the pdf in a browser tab:

@{
    ViewData["Title"] = "Home Page";
}

<a href="/home/get">Open PDF</a>

index.cshtml which downloads the pdf to file system (include the download attribute on the html anchor tag):

@{
    ViewData["Title"] = "Home Page";
}

<a href="/home/get" download>Download PDF</a>

home controller:

public class HomeController : Controller
{
    public IActionResult Get()
    {
        var stream = new FileStream(@"example.pdf", FileMode.Open);
        return new FileStreamResult(stream, "application/pdf");
    }
}
Harry
  • 3,930
  • 2
  • 14
  • 31
  • I m using AspNet Core, let me try this" – Prashant Pimpale Oct 10 '19 at 07:24
  • this is aspnet core – Harry Oct 10 '19 at 07:24
  • I don't why but not working am calling that get method as Ajax will that makes the difference? – Prashant Pimpale Oct 10 '19 at 07:29
  • with ajax the response is returned in your http response in javascript. You will need to use javascript to parse the response and cause the download manually. something like this https://ourcodeworld.com/articles/read/545/how-to-trigger-the-direct-download-of-a-pdf-with-javascript – Harry Oct 10 '19 at 07:31
  • actually maybe that links not good. i just searched for it quickly. maybe look at this https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax – Harry Oct 10 '19 at 07:33
  • instead of using ajax why not create a hidden anchor tag in javascript and programmatically click it? ajax is normally for json/html text responses not file binary – Harry Oct 10 '19 at 07:38
  • Yes, using Ajax and Blob its downloing the file but the data is not in a proper format, will try with anchor tag – Prashant Pimpale Oct 10 '19 at 07:42
  • tried with anchor tag : It shows : `Failed to execute 'open' on 'Window': Unable to open a window with invalid URL 'http://localhost:57325/%PDF-` – Prashant Pimpale Oct 10 '19 at 07:53
  • don't use window.open, create a anchor tag programmatically and click it. something like this `var anchor = document.createElement('a'); anchor.href = 'http://www.google.com'; anchor.click(); document.body.removeChild(anchor);` – Harry Oct 10 '19 at 08:33
  • Yes try this but its downloading the file but its show's: `Failed - no file` after download\ – Prashant Pimpale Oct 10 '19 at 08:52
  • I think I am thinking in a wrong direction - I am calling an SSRS report as shown in the question, i need to download that file – Prashant Pimpale Oct 10 '19 at 09:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/200646/discussion-between-prashant-pimpale-and-harry). – Prashant Pimpale Oct 10 '19 at 10:15
2

You can download a three-way file.

public async Task<IActionResult> Get()
{
    var path = Path.Combine(
    Directory.GetCurrentDirectory(), "wwwroot\\images\\4.pdf");

    var memory = new MemoryStream();
    using (var stream = new FileStream(path, FileMode.Open))
    {
       await stream.CopyToAsync(memory);
    }
    memory.Position = 0;
    return File(memory, "application/pdf", "Demo.pdf");
}

HTML;

<form asp-controller="pdf" asp-action="Get" method="get">
  <button type="submit">Download</button>
</form>

enter image description here

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84