0

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()
JosephStyons
  • 57,317
  • 63
  • 160
  • 234
  • 1
    This preference is on the client side. There are several ways to improve this behavior here in S.O. plenty of this kind of answer, but in the end, you can not force the user option. You can only play with the default behavior in every browser. – Leandro Bardelli Mar 16 '23 at 20:57
  • Or use an iframe, of course, but I think is not what you are looking for. – Leandro Bardelli Mar 16 '23 at 20:58
  • 1
    Does this answer your question? [Opening a PDF in browser instead of downloading it](https://stackoverflow.com/questions/12086321/opening-a-pdf-in-browser-instead-of-downloading-it) – Leandro Bardelli Mar 16 '23 at 20:59

2 Answers2

1

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.

JosephStyons
  • 57,317
  • 63
  • 160
  • 234
0

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