0

I have a href link to a PDF file that when clicked it opens in a new page in browser. I want this to download instead of opening in a new tab.

So how to make a PDF file link downloadable instead of opening them in the browser?

Here's the code:

<asp:FormView ID="FormView2" runat="server">
            <ItemTemplate>
                <asp:LoginView ID="LoginView1" runat="server">
                    <LoggedInTemplate>
                          <asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank"></asp:HyperLink>
                        <br />
                    </LoggedInTemplate>
                    <AnonymousTemplate>
                            <p>You need to log in to view the book.</p>
                    </AnonymousTemplate>
                </asp:LoginView>
            </ItemTemplate>
        </asp:FormView>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    int bookId = Convert.ToInt32(Request.QueryString.Get("BookId"));


    using (LibraryEntities entities = new LibraryEntities())
    {
        var book = (from r in entities.Books
                          where r.Id == bookId
                          select r);
        FormView2.DataSource = book;
        FormView2.DataBind();
    }
}
user123456
  • 17
  • 1
  • 2
  • 5

2 Answers2

2

Just add an attribute download to <asp:HyperLink>.

Final code will be.

<asp:HyperLink ID="HyperLink1" ToolTip="Open" CssClass="button" runat="server" 
               NavigateUrl='<%# Eval("PDFUrl") %>' Text="Open" Target="_blank" download
</asp:HyperLink>

NOTE: This is a HTML5 attribute, so it will work only for HTML5 compatible browsers. Check this link to see download attribute support on different browsers - http://caniuse.com/#feat=download

Michael
  • 2,961
  • 2
  • 28
  • 54
Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48
0
Response.Clear(); //eliminates issues where some response has already been sent
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.sql", filename));
Response.Write(yourSQL);
Response.End();

Similar questions has been asked here.

Community
  • 1
  • 1
sudip
  • 1
  • 1