How to download a PDF?

Dondon510 221 Reputation points
2022-09-27T14:10:39.993+00:00

Hi,

I'm trying to create a pdf on-the-fly and to download it, it was created but it can't be downloaded.. what I missed here?

        [HttpGet]  
        [Route("/Invoice/Download/{id}")]  
        public async Task<IActionResult> Download()  
        {  
               string currentPageUrl = Request.GetDisplayUrl();  
  
                HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);  
                PdfDocument document = htmlConverter.ConvertPartialHtml(currentPageUrl, "invoice");  
  
                using (MemoryStream ms = new MemoryStream())  
                {  
                    string fileName = Helper.Generate_NewGuid() + ".pdf";  
                    string fileExt = fileName.Substring(fileName.IndexOf("."));  
  
                    document.Save(ms);  
                    document.Close(true);  
                    byte[] pdf = ms.ToArray();  
  
                    return File(pdf, new Helper().GetMimeTypes()[fileExt], Path.GetFileName(fileName));  
                  
            }  
  
            return View("~/Views/Errs/e400.cshtml");  
        }'  
  
  
Helper.cs  
  
internal Dictionary<string, string> GetMimeTypes()  
        {  
            return new Dictionary<string, string>  
            {  
                {".txt", "text/plain"},  
                {".pdf", "application/pdf"},  
                {".doc", "application/vnd.ms-word"},  
                {".docx", "application/vnd.ms-word"},  
                {".xls", "application/vnd.ms-excel"},  
                {".xlsx", "application/vnd.ms-excel"},  
                {".png", "image/png"},  
                {".jpg", "image/jpeg"}  
            };  
        }  
  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,237 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,886 Reputation points
    2022-09-27T16:46:05.437+00:00

    use the browsers debug tools to check the response headers and content

    0 comments No comments

  2. Laxmikant 216 Reputation points
    2022-09-27T20:00:44.617+00:00

    replace your return statement with

    return new FileContentResult(pdf, "application/pdf");  
    

    for more details see - https://geeksarray.com/blog/aspnet-core-mvc-returning-file-using-fileresult

    0 comments No comments

  3. Dondon510 221 Reputation points
    2022-09-27T23:00:48.543+00:00

    thanks to all,
    this has been resolved, we can't use ajax to download, it's simple just use location.href

    cheers

    0 comments No comments