public void CreateUserAccount(string login, string password, string fullName, bool isAdmin)
{
try
{
DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntries entries = dirEntry.Children;
DirectoryEntry newUser = entries.Add(login, "user");
newUser.Properties["FullName"].Add(fullName);
newUser.Invoke("SetPassword", password);
newUser.CommitChanges();
// Remove the if condition along with the else to create user account in "user" group.
DirectoryEntry grp;
if (isAdmin)
{
grp = dirEntry.Children.Find("Administrators", "group");
if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); }
}
else
{
grp = dirEntry.Children.Find("Guests", "group");
if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); }
}
}
catch (Exception ex)
{
}
}
To Check for the User exists please refer the Prev posts on [checking Logon User Exists]
For Further Scripts on Logon User/Group management
Click Here
Click Here
Friday, February 12, 2010
Check dynamically if the Logon User already exists
public bool UserExists(string UserName)
{
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
if (child.Name == UserName)
return false;
}
}
return true;
}
{
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
if (child.Name == UserName)
return false;
}
}
return true;
}
Thursday, February 11, 2010
Accessing a Network Shared file from IIS/Local in C#
Steps To Be Followed To Open/Copy the Network Shared File
---------------------------------------------------------
1. Create a New User in Local Users and Groups by Right-clicking on MyComputer-->Manage
Create a User as Mentioned above in the System which hosts the Application and the System which shares the Files on a network.
The Username and password should be the same in both the systems.
2. Then use the below code and access the required File. The option of saving the network shared file is also available, If not you can just show the file in the same web page that requests for the File.
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.IO;
public partial class PDFTest : System.Web.UI.Page
{
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
private void undoImpersonation()
{
impersonationContext.Undo();
}
protected void Page_Load(object sender, EventArgs e)
{
doDownload();
}
private bool doDownload()
{
try
{
string strPath = @"\\REMOTEMACHINE\SHAREDFOLDER";
bool bFileExists = false;
if (strPath.Substring(strPath.Length) != "\\")
{
strPath = strPath + "\\";
}
string strFileLocation = strPath + "FILENAME";
if (impersonateValidUser("TestAcc", Environment.MachineName, "TESTAccPASSWORD"))
{
bFileExists = System.IO.File.Exists(strFileLocation);
}
if (!bFileExists)
{
//File does not exist!
undoImpersonation();
Response.Redirect("error.aspx?m=There was an error while attempting to access the file you selected. Please re-try your download.");
return;
}
//Writing to the Same Web Page
long lCurrentPosition = 0;
int intBytesRead = 0;
FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] arrBuffer = new byte[objFileStream.Length+20];
objFileStream.Position = lCurrentPosition;
intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
lCurrentPosition = objFileStream.Position;
objFileStream.Close();
if (arrBuffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", arrBuffer.Length.ToString());
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(arrBuffer);
//Response.End();
}
//Saving/Opening the Network PDF
//Response.ClearContent();
//Response.ClearHeaders();
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment;filename=" + "sss.pdf");
//Response.AddHeader("Content-Length", new FileInfo(strFileLocation).Length.ToString());
//long lCurrentPosition = 0;
//byte[] arrBuffer = new byte[524288];
//int intBytesRead = 0;
//FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
//objFileStream.Position = lCurrentPosition;
//intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
//lCurrentPosition = objFileStream.Position;
//objFileStream.Close();
//while (intBytesRead > 0 && Response.IsClientConnected)
//{
// Response.OutputStream.Write(arrBuffer, 0, intBytesRead);
// Response.Flush();
// try
// {
// objFileStream = System.IO.File.OpenRead(strFileLocation);
// objFileStream.Position = lCurrentPosition;
// intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
// lCurrentPosition = objFileStream.Position;
// }
// catch (Exception ex)
// {
// //catch puke here
// }
// finally
// {
// objFileStream.Close();
// }
//}
undoImpersonation();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
If you find any difficulties in this code let me know..
---------------------------------------------------------
1. Create a New User in Local Users and Groups by Right-clicking on MyComputer-->Manage
Create a User as Mentioned above in the System which hosts the Application and the System which shares the Files on a network.
The Username and password should be the same in both the systems.
2. Then use the below code and access the required File. The option of saving the network shared file is also available, If not you can just show the file in the same web page that requests for the File.
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.IO;
public partial class PDFTest : System.Web.UI.Page
{
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
private void undoImpersonation()
{
impersonationContext.Undo();
}
protected void Page_Load(object sender, EventArgs e)
{
doDownload();
}
private bool doDownload()
{
try
{
string strPath = @"\\REMOTEMACHINE\SHAREDFOLDER";
bool bFileExists = false;
if (strPath.Substring(strPath.Length) != "\\")
{
strPath = strPath + "\\";
}
string strFileLocation = strPath + "FILENAME";
if (impersonateValidUser("TestAcc", Environment.MachineName, "TESTAccPASSWORD"))
{
bFileExists = System.IO.File.Exists(strFileLocation);
}
if (!bFileExists)
{
//File does not exist!
undoImpersonation();
Response.Redirect("error.aspx?m=There was an error while attempting to access the file you selected. Please re-try your download.");
return;
}
//Writing to the Same Web Page
long lCurrentPosition = 0;
int intBytesRead = 0;
FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] arrBuffer = new byte[objFileStream.Length+20];
objFileStream.Position = lCurrentPosition;
intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
lCurrentPosition = objFileStream.Position;
objFileStream.Close();
if (arrBuffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", arrBuffer.Length.ToString());
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(arrBuffer);
//Response.End();
}
//Saving/Opening the Network PDF
//Response.ClearContent();
//Response.ClearHeaders();
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment;filename=" + "sss.pdf");
//Response.AddHeader("Content-Length", new FileInfo(strFileLocation).Length.ToString());
//long lCurrentPosition = 0;
//byte[] arrBuffer = new byte[524288];
//int intBytesRead = 0;
//FileStream objFileStream = System.IO.File.Open(strFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);
//objFileStream.Position = lCurrentPosition;
//intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
//lCurrentPosition = objFileStream.Position;
//objFileStream.Close();
//while (intBytesRead > 0 && Response.IsClientConnected)
//{
// Response.OutputStream.Write(arrBuffer, 0, intBytesRead);
// Response.Flush();
// try
// {
// objFileStream = System.IO.File.OpenRead(strFileLocation);
// objFileStream.Position = lCurrentPosition;
// intBytesRead = objFileStream.Read(arrBuffer, 0, arrBuffer.Length);
// lCurrentPosition = objFileStream.Position;
// }
// catch (Exception ex)
// {
// //catch puke here
// }
// finally
// {
// objFileStream.Close();
// }
//}
undoImpersonation();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
If you find any difficulties in this code let me know..
Tuesday, February 9, 2010
Creating a CSV Text from Table Columns
Select Name from Users
Name
----
Ramu
Saju
Nattu
SELECT SUBSTRING((SELECT ',' + s.Name FROM Users s ORDER BY s.Name FOR XML PATH('')),2,200000) AS CSV
Name
----
Ramu
Saju
Nattu
SELECT SUBSTRING((SELECT ',' + s.Name FROM Users s ORDER BY s.Name FOR XML PATH('')),2,200000) AS CSV
Splitting Text with Extra Characters to a Table
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
create function fn_ParseText2Table
(
@p_SourceText varchar(8000)
,@p_Delimeter varchar(100) = ',' --default to comma delimited.
)
RETURNS @retTable TABLE
(
Position int identity(1,1)
,Int_Value int
,Num_value Numeric(18,3)
,txt_value varchar(2000)
)
AS
BEGIN
DECLARE @w_Continue int
,@w_StartPos int
,@w_Length int
,@w_Delimeter_pos int
,@w_tmp_int int
,@w_tmp_num numeric(18,3)
,@w_tmp_txt varchar(2000)
,@w_Delimeter_Len tinyint
if len(@p_SourceText) = 0
begin
SET @w_Continue = 0 -- force early exit
end
else
begin
-- parse the original @p_SourceText array into a temp table
SET @w_Continue = 1
SET @w_StartPos = 1
SET @p_SourceText = RTRIM( LTRIM( @p_SourceText))
SET @w_Length = DATALENGTH( RTRIM( LTRIM( @p_SourceText)))
SET @w_Delimeter_Len = len(@p_Delimeter)
end
WHILE @w_Continue = 1
BEGIN
SET @w_Delimeter_pos = CHARINDEX( @p_Delimeter
,(SUBSTRING( @p_SourceText, @w_StartPos
,((@w_Length - @w_StartPos) + @w_Delimeter_Len)))
)
IF @w_Delimeter_pos > 0 -- delimeter(s) found, get the value
BEGIN
SET @w_tmp_txt = LTRIM(RTRIM( SUBSTRING( @p_SourceText, @w_StartPos
,(@w_Delimeter_pos - 1)) ))
if isnumeric(@w_tmp_txt) = 1
begin
set @w_tmp_int = cast( cast(@w_tmp_txt as numeric) as int)
set @w_tmp_num = cast( @w_tmp_txt as numeric(18,3))
end
else
begin
set @w_tmp_int = null
set @w_tmp_num = null
end
SET @w_StartPos = @w_Delimeter_pos + @w_StartPos + (@w_Delimeter_Len- 1)
END
ELSE -- No more delimeters, get last value
BEGIN
SET @w_tmp_txt = LTRIM(RTRIM( SUBSTRING( @p_SourceText, @w_StartPos
,((@w_Length - @w_StartPos) + @w_Delimeter_Len)) ))
if isnumeric(@w_tmp_txt) = 1
begin
set @w_tmp_int = cast( cast(@w_tmp_txt as numeric) as int)
set @w_tmp_num = cast( @w_tmp_txt as numeric(18,3))
end
else
begin
set @w_tmp_int = null
set @w_tmp_num = null
end
SELECT @w_Continue = 0
END
INSERT INTO @retTable VALUES( @w_tmp_int, @w_tmp_num, @w_tmp_txt )
END
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
select * from dbo.fn_ParseText2Table('101, 201, 223, 443', ',')
Position Int_Value Num_value txt_value
----------- ----------- -------------------- ----------
1 NULL NULL 101
2 NULL NULL 201
3 NULL NULL 223
4 NULL NULL 443
GO
SET ANSI_NULLS OFF
GO
create function fn_ParseText2Table
(
@p_SourceText varchar(8000)
,@p_Delimeter varchar(100) = ',' --default to comma delimited.
)
RETURNS @retTable TABLE
(
Position int identity(1,1)
,Int_Value int
,Num_value Numeric(18,3)
,txt_value varchar(2000)
)
AS
BEGIN
DECLARE @w_Continue int
,@w_StartPos int
,@w_Length int
,@w_Delimeter_pos int
,@w_tmp_int int
,@w_tmp_num numeric(18,3)
,@w_tmp_txt varchar(2000)
,@w_Delimeter_Len tinyint
if len(@p_SourceText) = 0
begin
SET @w_Continue = 0 -- force early exit
end
else
begin
-- parse the original @p_SourceText array into a temp table
SET @w_Continue = 1
SET @w_StartPos = 1
SET @p_SourceText = RTRIM( LTRIM( @p_SourceText))
SET @w_Length = DATALENGTH( RTRIM( LTRIM( @p_SourceText)))
SET @w_Delimeter_Len = len(@p_Delimeter)
end
WHILE @w_Continue = 1
BEGIN
SET @w_Delimeter_pos = CHARINDEX( @p_Delimeter
,(SUBSTRING( @p_SourceText, @w_StartPos
,((@w_Length - @w_StartPos) + @w_Delimeter_Len)))
)
IF @w_Delimeter_pos > 0 -- delimeter(s) found, get the value
BEGIN
SET @w_tmp_txt = LTRIM(RTRIM( SUBSTRING( @p_SourceText, @w_StartPos
,(@w_Delimeter_pos - 1)) ))
if isnumeric(@w_tmp_txt) = 1
begin
set @w_tmp_int = cast( cast(@w_tmp_txt as numeric) as int)
set @w_tmp_num = cast( @w_tmp_txt as numeric(18,3))
end
else
begin
set @w_tmp_int = null
set @w_tmp_num = null
end
SET @w_StartPos = @w_Delimeter_pos + @w_StartPos + (@w_Delimeter_Len- 1)
END
ELSE -- No more delimeters, get last value
BEGIN
SET @w_tmp_txt = LTRIM(RTRIM( SUBSTRING( @p_SourceText, @w_StartPos
,((@w_Length - @w_StartPos) + @w_Delimeter_Len)) ))
if isnumeric(@w_tmp_txt) = 1
begin
set @w_tmp_int = cast( cast(@w_tmp_txt as numeric) as int)
set @w_tmp_num = cast( @w_tmp_txt as numeric(18,3))
end
else
begin
set @w_tmp_int = null
set @w_tmp_num = null
end
SELECT @w_Continue = 0
END
INSERT INTO @retTable VALUES( @w_tmp_int, @w_tmp_num, @w_tmp_txt )
END
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
select * from dbo.fn_ParseText2Table('101, 201, 223, 443', ',')
Position Int_Value Num_value txt_value
----------- ----------- -------------------- ----------
1 NULL NULL 101
2 NULL NULL 201
3 NULL NULL 223
4 NULL NULL 443
Wednesday, February 3, 2010
Date Formats Available in SQL Server
ID | Date Formats |
0 or 100 | mon dd yyyy hh:miAM (or PM) |
101 | mm/dd/yy |
102 | yy.mm.dd |
103 | dd/mm/yy |
104 | dd.mm.yy |
105 | dd-mm-yy |
106 | dd mon yy |
107 | Mon dd, yy |
108 | hh:mm:ss |
9 or 109 | mon dd yyyy hh:mi:ss:mmmAM (or PM) |
110 | mm-dd-yy |
111 | yy/mm/dd |
112 | yymmdd |
13 or 113 | dd mon yyyy hh:mm:ss:mmm(24h) |
114 | hh:mi:ss:mmm(24h) |
20 or 120 | yyyy-mm-dd hh:mi:ss(24h) |
21 or 121 | yyyy-mm-dd hh:mi:ss.mmm(24h) |
126 | yyyy-mm-dd Thh:mm:ss.mmm(no spaces) |
130 | dd mon yyyy hh:mi:ss:mmmAM |
131 | dd/mm/yy hh:mi:ss:mmmAM |
Encoding and Decoding Using UnicodeEncoding in C#
//Include this line in Declaration
UnicodeEncoding Unicode = new UnicodeEncoding();
To Encode a String
-------------------
string inputString = "This string contains the unicode character";
byte[] FilterBytes = Unicode.GetBytes(inputString);
string FilterASCII = System.Text.ASCIIEncoding.ASCII.GetString(FilterBytes);
byte[] AsciiBytes = Unicode.GetBytes(FilterASCII);
string sEncodedText = Convert.ToBase64String(AsciiBytes);
To Decode the Above Encoded String
----------------------------------
byte[] FileTextBytes = Convert.FromBase64String(sEncodedText);
string ASCIItext = Unicode.GetString(FileTextBytes);
byte[] ASCIIBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(ASCIItext);
string sDecodedText = Unicode.GetString(ASCIIBytes);
UnicodeEncoding Unicode = new UnicodeEncoding();
To Encode a String
-------------------
string inputString = "This string contains the unicode character";
byte[] FilterBytes = Unicode.GetBytes(inputString);
string FilterASCII = System.Text.ASCIIEncoding.ASCII.GetString(FilterBytes);
byte[] AsciiBytes = Unicode.GetBytes(FilterASCII);
string sEncodedText = Convert.ToBase64String(AsciiBytes);
To Decode the Above Encoded String
----------------------------------
byte[] FileTextBytes = Convert.FromBase64String(sEncodedText);
string ASCIItext = Unicode.GetString(FileTextBytes);
byte[] ASCIIBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(ASCIItext);
string sDecodedText = Unicode.GetString(ASCIIBytes);
Export Gridview to PDF using C#.Net for Both AutoGenerate Column and Template Columns
public void ExportToPDF(string ReportName, GridView grdPDF, bool isLandscape,string Filename)
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null;
if (grdPDF.AutoGenerateColumns)
{
tbl = grdPDF.DataSource as DataTable; // Gets the DataSource of the GridView Control.
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = grdPDF.Columns.Count;
noOfRows = grdPDF.Rows.Count;
}
float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;
// Creates a PDF document
Document document = null;
if (isLandscape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}
PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
// Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;
// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("../Images/medtech_logo.jpg"));
imgLogo.ScaleToFit(100, 25);
PdfPCell clApplicationName = new PdfPCell(imgLogo);
clApplicationName.Border = PdfPCell.NO_BORDER;
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd-MMM-yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;
headerTable.AddCell(clApplicationName);
headerTable.AddCell(clDate);
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
// Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);
// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase(sApplicationnName, FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);
// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);
// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;
if (grdPDF.AutoGenerateColumns)
ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
else
ph = new Phrase(grdPDF.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
mainTable.AddCell(ph);
}
// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (grdPDF.AutoGenerateColumns)
{
string s = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = "";
if (grdPDF.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = grdPDF.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
if (lc != null)
{
s = lc.Text.Trim();
}
else
{
for (int i = 0; i < grdPDF.Rows[rowNo].Cells[columnNo].Controls.Count; i++)
{
if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(TextBox))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as TextBox).Text;
}
else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(Label))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as Label).Text;
}
else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(System.Web.UI.WebControls.Image))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as System.Web.UI.WebControls.Image).ToolTip;
}
}
}
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
s = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}
mainTable.CompleteRow();
}
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;
document.Footer = pdfFooter;
document.Open();
document.Add(mainTable);
document.Close();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= "+ Filename +"_"+ DateTime.Now.ToString("dd_MMM_yyyy") +".pdf");
HttpContext.Current.Response.End();
}
ITextSharp Dll Download link
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null;
if (grdPDF.AutoGenerateColumns)
{
tbl = grdPDF.DataSource as DataTable; // Gets the DataSource of the GridView Control.
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = grdPDF.Columns.Count;
noOfRows = grdPDF.Rows.Count;
}
float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;
// Creates a PDF document
Document document = null;
if (isLandscape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}
PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
// Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;
// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("../Images/medtech_logo.jpg"));
imgLogo.ScaleToFit(100, 25);
PdfPCell clApplicationName = new PdfPCell(imgLogo);
clApplicationName.Border = PdfPCell.NO_BORDER;
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd-MMM-yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;
headerTable.AddCell(clApplicationName);
headerTable.AddCell(clDate);
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
// Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);
// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase(sApplicationnName, FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);
// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);
// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;
if (grdPDF.AutoGenerateColumns)
ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
else
ph = new Phrase(grdPDF.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
mainTable.AddCell(ph);
}
// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (grdPDF.AutoGenerateColumns)
{
string s = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = "";
if (grdPDF.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = grdPDF.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
if (lc != null)
{
s = lc.Text.Trim();
}
else
{
for (int i = 0; i < grdPDF.Rows[rowNo].Cells[columnNo].Controls.Count; i++)
{
if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(TextBox))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as TextBox).Text;
}
else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(Label))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as Label).Text;
}
else if (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i].GetType() == typeof(System.Web.UI.WebControls.Image))
{
s = (grdPDF.Rows[rowNo].Cells[columnNo].Controls[i] as System.Web.UI.WebControls.Image).ToolTip;
}
}
}
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
s = grdPDF.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}
mainTable.CompleteRow();
}
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;
document.Footer = pdfFooter;
document.Open();
document.Add(mainTable);
document.Close();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= "+ Filename +"_"+ DateTime.Now.ToString("dd_MMM_yyyy") +".pdf");
HttpContext.Current.Response.End();
}
ITextSharp Dll Download link
Subscribe to:
Posts (Atom)