Saturday 3 August 2019

Open (Show) PDF File in new Browser Tab (Window) in ASP.Net

In this article I will explain with an example, how to open (show) PDF File in new Browser Tab (Window) in ASP.Net using C# and VB.Net.
 
 
HTML Markup
Page 1
The HTML Markup consists of an ASP.Net HyperLink. The NavigateUrl property is set to the ViewPDFpage and the name of the File is passed as QueryString parameter.
<asp:HyperLink NavigateUrl="~/ViewPDF.aspx?File=Mudassar_Khan.pdf" runat="server" Text="View PDF" Target="_blank" />
 
View PDF
The HTML Markup consists of an ASP.Net Literal control. The Literal control will display the embedded PDF File.
<asp:Literal ID="ltEmbed" runat="server" />
 
 
Opening (Showing) PDF File in new Browser Tab (Window) in ASP.Net
Inside the Page Load event, an HTML OBJECT Tag is generated in String format in order to embed the PDF File in browser. The path of the PDF file is extracted from QueryString and is set in the HTML String.
The HTML String is then set to the Literal Tag.
C#
protected void Page_Load(object sender, EventArgs e)
{
    string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
    embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
    embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
    embed += "</object>";
    ltEmbed.Text = string.Format(embed, ResolveUrl(string.Format("~/Files/{0}", Request.QueryString["File"])));
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load
    Dim embed As String = "<object data=""{0}"" type=""application/pdf"" width=""500px"" height=""300px"">"
    embed += "If you are unable to view file, you can download from <a href = ""{0}"">here</a>"
    embed += " or download <a target = ""_blank"" href = ""http://get.adobe.com/reader/"">Adobe PDF Reader</a> to view the file."
    embed += "</object>"
    ltEmbed.Text = String.Format(embed, ResolveUrl(String.Format("~/Files/{0}", Request.QueryString("File"))))
End Sub
 
 
Screenshots
The PDF File displayed in Browser in New Tab (Window) when Adobe PDF Reader is installed

No comments:

Post a Comment