To open a PDF file through code with ASP.Net , a class named WebClient Class in the System.Net namespace is required. To dynamically specify the path of the PDF file - we will be using the FileUpload Control. Further after selecting the file to open, we will make a check to selected file extension to make sure that the file selected is a PDF file using System.IO.Path.GetExtension() Method.
Just declare an object of the WebClient Class. Create a string variable to store the complete path of the PDF file.
The different Properties and Methods used in the code are explained below :
- The DownloadData Method of the WebClient Class downloads the resource from the specified path or URI as a System.Byte array.
- The ContentType property gets or sets the HTTP MIME type of the Output stream.
- The AppendHeader Method adds an HTTP Header to the Output stream.
- The BinaryWrite Method writes a string of binary characters to the HTTP Output stream.
So here is the code for .apsx.cs file :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Net;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
protected void OpenPDF_Click(object sender, EventArgs e)
{
string _path = string.Empty;
if (FileUpload1.HasFile)
{
//----- get the extension of the file.
System.String _fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
//----- check the extension of the file.
if (_fileExtension.ToUpper() == ".PDF")
{
_path = FileUpload1.PostedFile.FileName;
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(_path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AppendHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
else
{
//---- Selected file is not a PDF file.
Response.Write("The " + FileUpload1.FileName + " file does not appear to be a valid PDF file.");
}
}
else
{
//---- No file selected to open.
Response.Write("Please select a PDF file to open.");
}
}
Add the following controls in .apsx file :
- FileUpload Control with ID FileUpload1
- Button Control with ID OpenPDF.


So thats all.
Wish you Happy Coding.
-- Anki Sharma
No comments:
Post a Comment