Sử dụng iTextSharp để Export dữ liệu Datalist sang PDF trong ASP.Net
(Export selected Datalist Rows to PDF using itextsharp in ASP.Net) – Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng itextsharp để xuất dữ liệu ra file PDF. Dữ liệu được xuất file PDF được lấy bằng cách tích chọn các dòng từ người sử dụng. Số cột, tên cột, độ rộng trên file PDF được lấy tự động tương ứng trên Datalist.
- 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
C# Code
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportDatalistUsingItextsharp
Public Class SqlDataProvider
#Region "Membres
Prives"
Shared _IsError As Boolean = False
Private _connectionString As
String
#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() As
String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function
FillTable(ByVal sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class Constants
Public Const
DEFAULT_COLOR_COMPANYNAME As String = "#007dc2"
Public Const
DEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
Public Const
DEFAULT_BORDERCOLOR_TABLE As String = "#808080"
Public Const
DEFAULT_BACKGROUNDCOLOR_ROW As String = "#edf5ff"
Public Const
DEFAULT_COLOR_HEADERROW As String = "#ffffff"
End Class
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportDatalistUsingItextsharp
Public Class SqlDataProvider
#Region "Membres
Prives"
Shared _IsError As Boolean = False
Private _connectionString As
String
#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() As
String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function
FillTable(ByVal sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class Constants
Public Const
DEFAULT_COLOR_COMPANYNAME As String = "#007dc2"
Public Const
DEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
Public Const
DEFAULT_BORDERCOLOR_TABLE As String = "#808080"
Public Const
DEFAULT_BACKGROUNDCOLOR_ROW As String = "#edf5ff"
Public Const
DEFAULT_COLOR_HEADERROW As String = "#ffffff"
End Class
- B4: References itextsharp.dll trong thư mục vừa giải nén vào Project.
- B5: 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
- B6: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page
Title="Export Datalist
Using itextsharp in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportDatalistUsingItextsharp._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
Export Datalist Using itextsharp in ASP.Net
</h3>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr>
<td>
<asp:LinkButton id="cmdExport" runat="server" CssClass="btn btn-small" OnClick="cmdExport_Click" Causesvalidation="false">
<i class="icon-exportpdf"></i> <asp:label id="lblExport" runat="server" Text="Export PDF"></asp:label>
</asp:LinkButton>
</td>
</tr>
<tr
id="trMessage"
runat="server"
visible="false">
<td>
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<ItemStyle CssClass="GridStyle_RowStyle"
/>
<HeaderTemplate>
<table cellpadding="0"
cellspacing="0"
width="100%">
<tr>
<th colspan="5">
<table id="tblProduct"
runat="server"
cellpadding="0"
cellspacing="0"
width="100%">
<tr>
<th
align="center"
width="220">ProductName</th>
<th
align="center"
width="170">CategoryName</th>
<th
align="center"
width="120">QuantityPerUnit</th>
<th
align="center"
width="80">UnitPrice</th>
<th
align="center"
width="80">UnitsInStock</th>
<th
align="center"
width="80">UnitsOnOrder</th>
</tr>
</table>
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td colspan="6">
<table id="tblInfo"
runat="server"
cellpadding="0"
cellspacing="0"
width="100%">
<tr>
<td
align="left"
width="220"><%# Eval("ProductName")
%></td>
<td
align="left"
width="170"><%# Eval("CategoryName")
%></td>
<td
align="left"
width="120"><%# Eval("QuantityPerUnit")
%></td>
<td
align="right"
width="80"><%# Eval("UnitPrice")
%></td>
<td
align="right"
width="80"><%# Eval("UnitsInStock")
%></td>
<td
align="right"
width="80"><%# Eval("UnitsOnOrder")
%></td>
</tr>
</table>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="cmdExport"
/>
</Triggers>
</asp:UpdatePanel>
</asp:Content>- B7: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace ExportDatalistUsingItextsharp
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Export PDF"
private void
ExportToPDF(string FileName, bool ExportAll)
{
Document document = new
Document(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 = new
Font(bf, 10, Font.BOLD,
new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
Font fontHeader = new
Font(bf, 9, Font.BOLD,
Color.BLUE);
Font fontSubHeader = new
Font(bf, 8);
Font fontTableHeader = new
Font(bf, 8, Font.BOLD,
new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)));
Font fontContent = new
Font(bf, 8, 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 = new
Phrase(beginning);
Paragraph pCompanyName = new Paragraph();
pCompanyName.IndentationLeft = 30;
pCompanyName.Add(p1);
document.Add(pCompanyName);
//Website
string sWebsite = "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 = "LIST PRODUCT" + 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);
}
int iColumn = 0;
int i = 0;
HtmlTable tblProduct =
dlObject.Controls[0].Controls[0].FindControl("tblProduct")
as HtmlTable;
if (tblProduct != null)
{
for (i = 0; i <=
tblProduct.Rows[0].Cells.Count - 1; i++)
{
iColumn += 1;
}
}
if (iColumn > 0)
{
iTextSharp.text.Table datatable = new iTextSharp.text.Table(iColumn);
float[] headerwidths = new float[iColumn];
datatable.Padding = 2;
datatable.Spacing = 1;
datatable.WidthPercentage = 98;
for (i = 0; i <=
tblProduct.Rows[0].Cells.Count - 1; i++)
{
headerwidths[i] = Convert.ToInt32(tblProduct.Rows[0].Cells[i].Width);
datatable.Widths =
headerwidths;
Cell cellText = new Cell(new Phrase(tblProduct.Rows[0].Cells[i].InnerHtml,
fontTableHeader));
cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_HEADERROW));
cellText.HorizontalAlignment = 1;
cellText.VerticalAlignment = 1;
datatable.AddCell(cellText);
}
datatable.BorderWidth = 1;
datatable.DefaultCellBorderWidth = 1;
datatable.DefaultHorizontalAlignment = 1;
datatable.DefaultVerticalAlignment = 1;
datatable.DefaultCellBorderColor = new
iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));
datatable.BorderColor = new
iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));
int iRow = dlObject.Items.Count;
int iAlign = 0;
string
cellValue = "";
for (i = 0; i <= iRow - 1; i++)
{
HtmlTable tblInfo;
DataListItem mySelectedRow = dlObject.Items[i];
tblInfo =
mySelectedRow.FindControl("tblInfo")
as HtmlTable;
if (tblInfo != null)
{
for (int j = 0; j
<= iColumn-1; j++)
{
switch (tblInfo.Rows[0].Cells[j].Align)
{
case "":
case "left":
iAlign
= 0;
break;
case "right":
iAlign
= 2;
break;
case "center":
iAlign =
1;
break;
}
cellValue =
tblInfo.Rows[0].Cells[j].InnerHtml;
iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellValue);
if (i % 2 != 0)
{
cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_ROW));
}
datatable.DefaultHorizontalAlignment = iAlign;
datatable.AddCell(cell);
}
}
}
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 void
BindProduct()
{
DataTable objBind = new
DataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
dlObject.DataSource = objBind;
dlObject.DataBind();
trMessage.Visible = false;
dlObject.Visible = true;
}
else
{
trMessage.Visible = true;
dlObject.Visible = false;
}
updatePanel.Update();
}
}
private DataTable
BindData()
{
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("SELECT Products.ProductID, Products.ProductName,
Products.SupplierID, Products.CategoryID, Categories.CategoryName,
Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock,
Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued From
Products INNER JOIN Categories ON Products.CategoryID =
Categories.CategoryID");
return objBind;
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindProduct();
}
}
catch
{
}
}
protected void
cmdExport_Click(object sender, System.EventArgs e)
{
ExportToPDF("List-Product.pdf",
false);
}
#endregion
}
}
'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 ExportDatalistUsingItextsharp
Public Class _Default
Inherits System.Web.UI.Page
#Region "Export PDF"
Private Sub
ExportToPDF(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, 12, Font.BOLD, New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)))
Dim fontHeader As New Font(bf, 11, Font.BOLD, Color.BLUE)
Dim fontSubHeader As New Font(bf, 10)
Dim fontContent As New Font(bf, 10, Font.NORMAL, Color.BLACK)
Dim fontTableHeader As
New Font(bf,
10, Font.BOLD, New
Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)))
Try
Dim writer As
PdfWriter = PdfWriter.GetInstance(document,
msReport)
document.AddAuthor("Thu thuat lap
trinh")
document.AddSubject("Export to
PDF")
document.Open()
Dim cBreak As
New Chunk(Environment.NewLine)
Dim pBreak As
New Phrase()
Dim
paBreak As New Paragraph()
'=================Start Header
=====================
'CompnayName
Dim sText As
String = "THỦ
THUẬT LẬP TRÌNH" & vbCrLf
Dim beginning As
New Chunk(sText,
fontCompany)
Dim p1 As
New Phrase(beginning)
Dim pCompanyName As New Paragraph()
pCompanyName.IndentationLeft = 30
pCompanyName.Add(p1)
document.Add(pCompanyName)
'Website
Dim sWebsite As
String = "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 As New
Paragraph()
pAddresse.IndentationLeft = 30
pAddresse.Add(p1)
document.Add(pAddresse)
End If
Dim sEmail As
String = "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 As
New Paragraph()
pAddresse.IndentationLeft = 30
pAddresse.Add(p1)
document.Add(pAddresse)
End If
'=================End Header
=====================
'Title
sText = "LIST PRODUCT"
& Environment.NewLine & vbCrLf
If sText <> "" Then
beginning = New Chunk(sText,
fontHeader)
p1 = New Phrase(beginning)
Dim pAddresse As
New Paragraph()
pAddresse.IndentationLeft = 10
pAddresse.Alignment = 1
pAddresse.Add(p1)
document.Add(pAddresse)
End If
Dim iColumn As
Integer = 0
Dim i As Integer = 0
Dim tblProduct As
HtmlControls.HtmlTable =
dlObject.Controls(0).Controls(0).FindControl("tblProduct")
If Not
tblProduct Is Nothing
Then
For i = 0 To
tblProduct.Rows(0).Cells.Count - 1
iColumn += 1
Next
End If
If iColumn > 0 Then
Dim datatable As
New iTextSharp.text.Table(iColumn)
Dim headerwidths As Single() = New Single(iColumn -
1) {}
datatable.Padding = 2
datatable.Spacing = 1
datatable.WidthPercentage = 98
For i = 0 To
tblProduct.Rows(0).Cells.Count - 1
headerwidths(i) = CInt(tblProduct.Rows(0).Cells(i).Width)
datatable.Widths =
headerwidths
Dim cellText As New Cell(New Phrase(tblProduct.Rows(0).Cells(i).InnerHtml,
fontTableHeader))
cellText.BackgroundColor
= New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_HEADERROW))
cellText.HorizontalAlignment = 1
cellText.VerticalAlignment = 1
datatable.AddCell(cellText)
Next
datatable.BorderWidth = 1
datatable.DefaultCellBorderWidth = 1
datatable.DefaultHorizontalAlignment = 1
datatable.DefaultVerticalAlignment = 1
datatable.DefaultCellBorderColor = New
iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE))
datatable.BorderColor = New
iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE))
Dim iRow As
Integer = dlObject.Items.Count
Dim iAlign As
Integer = 0
Dim cellValue As
String = ""
For i = 0 To
iRow - 1
Dim mySelectedRow As DataListItem = dlObject.Items(i)
Dim tblInfo As HtmlControls.HtmlTable = TryCast(mySelectedRow.FindControl("tblInfo"), HtmlTable)
If Not tblInfo Is Nothing Then
For j As Integer = 0 To
iColumn - 1
Select Case
tblInfo.Rows(0).Cells(j).Align
Case "",
"left"
iAlign
= 0
Case "right"
iAlign
= 2
Case "center"
iAlign
= 1
End Select
cellValue =
tblInfo.Rows(0).Cells(j).InnerHtml
Dim cell As New iTextSharp.text.Cell(cellValue)
If i Mod 2 <> 0
Then
cell.BackgroundColor
= New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_ROW))
End If
datatable.DefaultHorizontalAlignment = iAlign
datatable.AddCell(cell)
Next
End If
Next
document.Add(datatable)
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 Sub
BindProduct()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
dlObject.DataSource = objBind
dlObject.DataBind()
trMessage.Visible = False
dlObject.Visible = True
Else
trMessage.Visible = True
dlObject.Visible = False
End If
updatePanel.Update()
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("SELECT Products.ProductID, Products.ProductName,
Products.SupplierID, Products.CategoryID, Categories.CategoryName, "
& _
"Products.QuantityPerUnit, Products.UnitPrice,
Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, "
& _
"Products.Discontinued From Products
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID")
Return objBind
End Function
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
BindProduct()
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdExport.Click
ExportToPDF("List-Product.pdf")
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
No Comment to " Sử dụng iTextSharp để Export dữ liệu Datalist sang PDF trong ASP.Net "