(Sử dụng iTextSharp để xuất thông tin bản ghi ra PDF) – Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng Datalist để hiển thị danh sách dữ liệu và tương ứng với mỗi bản ghi sẽ có chức năng Export. Khi kích nút Export chương trình sẽ tự động lấy toàn bộ thông tin bản ghi để xuất ra file PDF. Dưới đây là các bước thực hiện.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- B2: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;
namespace ExportRecordUsingItextsharpInDatalist
{
public class SqlDataProvider
{
#region"Membres Prives"
private string_connectionString;
#endregion
#region"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region"Proprietes"
public stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(string sql)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
public DataRowGetRow(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
adap.Fill(tb);
if (tb.Rows != null)
{
return tb.Rows[0];
}
}
catch
{
return null;
}
return null;
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(stringPname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
public class Constants
{
public const string DEFAULT_COLOR_COMPANYNAME = "#007dc2";
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportRecordUsingItextsharpInDatalist
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString AsString
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionGetRow(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
adap.Fill(tb)
If tb.Rows.Count Then
Return tb.Rows(0)
End If
Catch ex As Exception
Return Nothing
End Try
Return Nothing
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public PropertyName() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public PropertyValue() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
Public Class Constants
Public ConstDEFAULT_COLOR_COMPANYNAME As String = "#007dc2"
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B4: Download thư viện iTextSharp tại đây
- B5: References itextsharp.dll trong thư mục vừa giải nén vào Project.
- B6: Tạo thư mục Fonts, Download Font ARIALUNI.TTF tại đây và copy file này vào thư mục vừa tạo
- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ PageTitle="Export Records Using Itextsharp in Datalist ASP.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="ExportRecordUsingItextsharpInDatalist._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Export Records Using Itextsharp in Datalist
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<tdcolspan="2">
<asp:DataList ID="lstEmployees" runat="server" CellPadding="0" CellSpacing="0" Width="100%"
OnItemCommand="lstEmployees_ItemCommand"
OnItemDataBound="lstEmployees_ItemDataBound"
RepeatDirection="Horizontal"RepeatColumns="3">
<ItemTemplate>
<table align="left"cellpadding="2"cellspacing="3"style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;"width="300px"height="160px">
<tr>
<td colspan="2" class="info">
<asp:Label ID="lblFullName"Text='<%# Eval("LastName") + " "+ Eval("FirstName") %>' runat="server" />
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plTitle"runat="server"Text="Title"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblTitle"text='<%# Eval("Title")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plAddress"runat="server"Text="Address"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblAddress"text='<%# Eval("Address")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plCity" runat="server"Text="City"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblCity"text='<%# Eval("City")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="pRegion"runat="server"Text="Region"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblRegion"text='<%# Eval("Region")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plPostalCode"runat="server"Text="PostalCode"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblPostalCode"text='<%# Eval("PostalCode")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:ImageButton ID="cmdExport"CommandName="ExportPDF"CommandArgument='<%# Eval("EmployeeID")%>' runat="server"ImageUrl="~/images/icon_pdf.gif"CausesValidation="False"></asp:ImageButton>
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle VerticalAlign="Top"/>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
VB.Net Code
<%@ PageTitle="Export Records Using Itextsharp in Datalist" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportRecordUsingItextsharpInDatalist._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Export Records Using Itextsharp in Datalist
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td colspan="2">
<asp:DataList ID="lstEmployees" runat="server" CellPadding="0" CellSpacing="0" Width="100%" RepeatDirection="Horizontal" RepeatColumns="3">
<ItemTemplate>
<table align="left"cellpadding="2"cellspacing="3"style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;"width="300px"height="160px">
<tr>
<td colspan="2" class="info">
<asp:Label ID="lblFullName"Text='<%# Eval("LastName") & " " & Eval("FirstName") %>' runat="server" />
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plTitle"runat="server"Text="Title"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblTitle"text='<%# Eval("Title")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plAddress"runat="server"Text="Address"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblAddress"text='<%# Eval("Address")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plCity" runat="server"Text="City"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblCity"text='<%# Eval("City")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="pRegion" runat="server" Text="Region"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblRegion"text='<%# Eval("Region")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
<b><asp:Label ID="plPostalCode"runat="server"Text="PostalCode"></asp:Label></b>:
</td>
<td>
<asp:Label ID="lblPostalCode"text='<%# Eval("PostalCode")%>' runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:ImageButton ID="cmdExport"CommandName="ExportPDF"CommandArgument='<%# Eval("EmployeeID")%>' runat="server"ImageUrl="~/images/icon_pdf.gif"CausesValidation="False"></asp:ImageButton>
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle VerticalAlign="Top"/>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B8: Viết Code cho file Default.aspx
C#
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace ExportRecordUsingItextsharpInDatalist
{
public partial class _Default : System.Web.UI.Page
{
#region"Export PDF"
private voidExportToPDF(int ItemID, string FileName)
{
Document document = newDocument(PageSize.A4, 10f, 10f, 5f, 0f);
System.IO.MemoryStream msReport = new System.IO.MemoryStream();
string FilePath = "";
FilePath = Server.MapPath("Fonts\\ARIALUNI.TTF");
string fontpath = FilePath;
BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontCompany = newFont(bf, 13, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
Font fontHeader = newFont(bf, 12, Font.BOLD, Color.BLUE);
Font fontSubHeader = newFont(bf, 10);
Font fontTitle = newFont(bf, 11, Font.BOLD, Color.BLACK);
Font fontContent = newFont(bf, 11, Font.NORMAL, Color.BLACK);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.AddAuthor("Thu thuat lap trinh");
document.AddSubject("Export to PDF");
document.Open();
Chunk cBreak = new Chunk(Environment.NewLine);
Phrase pBreak = new Phrase();
Paragraph paBreak = new Paragraph();
//=================Start Header =====================
//CompnayName
string sText = "THỦ THUẬT LẬP TRÌNH";
Chunk beginning = new Chunk(sText, fontCompany);
Phrase p1 = newPhrase(beginning);
Paragraph pCompanyName = new Paragraph();
pCompanyName.IndentationLeft = 30;
pCompanyName.Add(p1);
document.Add(pCompanyName);
//Website
stringsWebsite = "Website: http://www.laptrinhdotnet.com";
sText = "";
if (!string.IsNullOrEmpty(sWebsite))
{
sText = sWebsite;
}
if (!string.IsNullOrEmpty(sText))
{
sText = sText.Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty);
beginning = new Chunk(sText, fontSubHeader);
p1 = new Phrase(beginning);
Paragraph pAddresse = new Paragraph();
pAddresse.IndentationLeft = 30;
pAddresse.Add(p1);
document.Add(pAddresse);
}
string sEmail = "Email: kenhphanmemviet@gmail.com";
if (!string.IsNullOrEmpty(sEmail))
{
sText = sEmail;
}
if (!string.IsNullOrEmpty(sText))
{
sText = sText.Replace(Environment.NewLine, string.Empty).Replace(" ", string.Empty);
beginning = new Chunk(sText, fontSubHeader);
p1 = new Phrase(beginning);
Paragraph pAddresse = new Paragraph();
pAddresse.IndentationLeft = 30;
pAddresse.Add(p1);
document.Add(pAddresse);
}
//=================End Header =====================
//Title
sText = "EMPLOYEE INFO" + Environment.NewLine;
if (!string.IsNullOrEmpty(sText))
{
beginning = new Chunk(sText, fontHeader);
p1 = new Phrase(beginning);
Paragraph pAddresse = new Paragraph();
pAddresse.IndentationLeft = 10;
pAddresse.Alignment = 1;
pAddresse.Add(p1);
document.Add(pAddresse);
}
iTextSharp.text.Table datatable = new iTextSharp.text.Table(4);
datatable.Padding = 1;
datatable.Spacing = 0;
datatable.WidthPercentage = 98;
float[] headerwidths = {12,38,14,35};
datatable.Widths = headerwidths;
datatable.DefaultCellBorderWidth = 0;
datatable.BorderWidth = 0;
datatable.DefaultHorizontalAlignment = 3;
datatable.DefaultVerticalAlignment = 1;
SqlDataProvider objSQL = new SqlDataProvider();
DataRow objInfo = objSQL.GetRow("Pro_Employees_Get", new ObjectPara("@EmployeeID", ItemID));
if (objInfo != null)
{
//LastName
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("LastName", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["LastName"].ToString(), fontContent));
//FirstName
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("FirstName", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["FirstName"].ToString(), fontContent));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("Title", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["Title"].ToString(), fontContent));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("TitleOfCourtesy", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["TitleOfCourtesy"].ToString(), fontContent));
//Address
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("Address", fontTitle));
datatable.DefaultColspan = 3;
if (objInfo["Address"] != null)
{
datatable.AddCell(new Phrase(objInfo["Address"].ToString(), fontContent));
}
else
{
datatable.AddCell(new Phrase("", fontContent));
}
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("City", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["City"].ToString(), fontContent));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase("Region", fontTitle));
datatable.DefaultColspan = 1;
datatable.AddCell(new Phrase(objInfo["Region"].ToString(), fontContent));
document.Add(datatable);
}
}
catch
{
}
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();
}
#endregion
#region"Bind Data"
private voidBindEmployees()
{
DataTable objBind = newDataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
lstEmployees.DataSource = objBind;
lstEmployees.DataBind();
lstEmployees.Visible = true;
}
else
{
lstEmployees.Visible = false;
}
updatePanel.Update();
}
}
private DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Employees.* From Employees");
return objBind;
}
#endregion
#region"Datalist Methods"
protected voidlstEmployees_ItemCommand(object sender, DataListCommandEventArgs e)
{
if (e.CommandName.ToLower() != "sort" & e.CommandName.ToLower() != "page")
{
string[] CommandArgument = e.CommandArgument.ToString().Split(',');
int EmployeeID = -1;
if (CommandArgument.Length > 0)
{
EmployeeID =Convert.ToInt32(CommandArgument[0]);
}
switch (e.CommandName.ToLower())
{
case "exportpdf":
if (EmployeeID>0)
{
ExportToPDF(EmployeeID, "EmployeeInfo");
}
break;
}
}
}
protected voidlstEmployees_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
ImageButton cmdExport = (ImageButton)e.Item.FindControl("cmdExport");
if (cmdExport != null)
{
cmdExport.ToolTip = "Click to Export";
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
}
}
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindEmployees();
}
}
catch
{
}
}
#endregion
}
}VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Namespace ExportRecordUsingItextsharpInDatalist
Public Class _Default
Inherits System.Web.UI.Page
#Region "Export PDF"
Private SubExportToPDF(ByVal ItemID As Integer, ByVal FileName As String)
Dim document As New Document(PageSize.A4.Rotate, 20, 20, 30, 20)
Dim msReport As New System.IO.MemoryStream()
Dim FilePath As String = ""
FilePath = Server.MapPath("Fonts\ARIALUNI.TTF")
Dim fontpath As String = FilePath
Dim bf As BaseFont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
Dim fontCompany As New Font(bf, 13, Font.BOLD, New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)))
Dim fontHeader As New Font(bf, 12, Font.BOLD, Color.BLUE)
Dim fontSubHeader As New Font(bf, 10)
Dim fontTitle As New Font(bf, 11, Font.BOLD, Color.BLACK)
Dim fontContent As New Font(bf, 11, Font.NORMAL, Color.BLACK)
Try
Dim writer AsPdfWriter = PdfWriter.GetInstance(document, msReport)
document.AddAuthor("Thu thuat lap trinh")
document.AddSubject("Export to PDF")
document.Open()
Dim cBreak AsNew Chunk(Environment.NewLine)
Dim pBreak AsNew Phrase()
Dim paBreak AsNew Paragraph()
'=================Start Header =====================
'CompnayName
Dim sText AsString = "THỦ THUẬT LẬP TRÌNH" & vbCrLf
Dim beginning AsNew Chunk(sText, fontCompany)
Dim p1 AsNew Phrase(beginning)
Dim pCompanyName As New Paragraph()
pCompanyName.IndentationLeft = 30
pCompanyName.Add(p1)
document.Add(pCompanyName)
'Website
Dim sWebsite AsString = "Website: http://www.laptrinhdotnet.com"
sText = ""
If sWebsite <> "" Then
sText = sWebsite & vbCrLf
End If
If sText <> "" Then
sText = sText.Replace(Environment.NewLine, String.Empty).Replace(" ", String.Empty)
beginning = New Chunk(sText, fontSubHeader)
p1 = New Phrase(beginning)
Dim pAddresse AsNew Paragraph()
pAddresse.IndentationLeft = 30
pAddresse.Add(p1)
document.Add(pAddresse)
End If
Dim sEmail AsString = "Email: kenhphanmemviet@gmail.com"
If sEmail <> "" Then
sText = sEmail & vbCrLf
End If
If sText <> "" Then
sText = sText.Replace(Environment.NewLine, String.Empty).Replace(" ", String.Empty)
beginning = New Chunk(sText, fontSubHeader)
p1 = New Phrase(beginning)
Dim pAddresse AsNew Paragraph()
pAddresse.IndentationLeft = 30
pAddresse.Add(p1)
document.Add(pAddresse)
End If
'=================End Header =====================
'Title
sText = "EMPLOYEE INFO"& Environment.NewLine & vbCrLf
If sText <> "" Then
beginning = New Chunk(sText, fontHeader)
p1 = New Phrase(beginning)
Dim pAddresse AsNew Paragraph()
pAddresse.IndentationLeft = 10
pAddresse.Alignment = 1
pAddresse.Add(p1)
document.Add(pAddresse)
End If
Dim datatable AsNew iTextSharp.text.Table(4)
datatable.Padding = 1
datatable.Spacing = 0
datatable.WidthPercentage = 98
Dim headerwidths As Single() = {12, 38, 12, 38}
datatable.Widths = headerwidths
datatable.DefaultCellBorderWidth = 0
datatable.BorderWidth = 0
datatable.DefaultHorizontalAlignment = 3
datatable.DefaultVerticalAlignment = 1
Dim objSQL AsNew SqlDataProvider
Dim objInfo AsDataRow = objSQL.GetRow("Pro_Employees_Get", New ObjectPara("@EmployeeID", ItemID))
If NotobjInfo Is NothingThen
With objInfo
'LastName
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("LastName", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("LastName"), fontContent))
'FirstName
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("FirstName", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("FirstName"), fontContent))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Title", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("Title"), fontContent))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("TitleOfCourtesy", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("TitleOfCourtesy"), fontContent))
'Address
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Address", fontTitle))
datatable.DefaultColspan = 3
IfNot IsDBNull(objInfo("Address")) Then
datatable.AddCell(New Phrase(objInfo("Address"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("City", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("City"), fontContent))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Region", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("Region"), fontContent))
document.Add(datatable)
End With
End If
Catch e As Exception
Console.Error.WriteLine(e.Message)
End Try
document.Close()
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & FileName & ".pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(msReport.ToArray())
Response.End()
End Sub
#End Region
#Region "Bind Data"
Private SubBindEmployees()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
lstEmployees.DataSource = objBind
lstEmployees.DataBind()
lstEmployees.Visible = True
Else
lstEmployees.Visible = False
End If
updatePanel.Update()
End If
End Sub
Private FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Employees.* From Employees")
Return objBind
End Function
#End Region
#Region "Datalist Methods"
Private SublstEmployees_ItemCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs) HandleslstEmployees.ItemCommand
If (e.CommandName.ToLower <> "sort" Ande.CommandName.ToLower <> "page") Then
Dim CommandArgument() As String = e.CommandArgument.ToString.Split(",")
Dim EmployeeID AsInteger = -1
If CommandArgument.Length > 0 Then
EmployeeID = CommandArgument(0)
End If
Select Casee.CommandName.ToLower
Case "exportpdf"
IfEmployeeID > 0 Then
ExportToPDF(EmployeeID, "EmployeeInfo")
End If
End Select
End If
End Sub
Private SublstEmployees_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs) HandleslstEmployees.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim cmdExport AsImageButton = DirectCast(e.Item.FindControl("cmdExport"), ImageButton)
If cmdExport IsNotNothing Then
cmdExport.ToolTip = "Click to Export"
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport)
End If
End If
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
BindEmployees()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment