skip to Main Content

I have ASP.NET code that retrieves a PDF file from a database and gives it to the user to download in their browser. I want to make the PDF render inside the browser, without them having to manually open the downloaded file. What’s the best approach to do that? My current code is below for reference.

Response.Clear()
Response.AddHeader("Content-Length", fileContents.Length.ToString())
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename)
Response.OutputStream.Write(fileContents, 0, fileContents.Length)
Response.Flush()
Response.End()

2

Answers


  1. Chosen as BEST ANSWER

    I ended up solving this by using a server-side tag. In my code, I save the PDF to the web server, then change the src attribute to point to that saved location.


  2. With this code, the PDF file will be rendered inside the browser when the user clicks the download link, instead of prompting them to download it. Note that this approach requires that the user has a PDF viewer plugin installed in their browser. If they don’t, they may still be prompted to download the file.

    public ActionResult DownloadPDF(int id)
    {
        byte[] fileContent;
        string fileName;
    
        // Retrieve the PDF file from the database
        using (var db = new MyDbContext())
        {
            var pdfFile = db.PDFFiles.Find(id);
            fileContent = pdfFile.Content;
            fileName = pdfFile.FileName;
        }
    
        // Render the PDF file inside the browser
        Response.ContentType = "application/pdf";
        Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName);
        Response.BinaryWrite(fileContent);
        Response.End();
    
        return new EmptyResult();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search