(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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.Web;
namespace ExportSelectedDatalistRowToPDF
{
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;
}
}
#endregion
}
public class Constants
{
public const string DEFAULT_COLOR_COMPANYNAME = "#007dc2";
public const string DEFAULT_BACKGROUNDCOLOR_HEADERROW = "#99cd00";
public const string DEFAULT_COLOR_HEADERROW = "#ffffff";
public const string DEFAULT_BORDERCOLOR_TABLE = "#808080";
public const string DEFAULT_BACKGROUNDCOLOR_ROW = "#edf5ff";
}
}Imports System.Data.SqlClient
Imports System.Data
Namespace ExportSelectedDatalistRowUsingItextsharp
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
#End Region
End Class
Public Class Constants
Public ConstDEFAULT_COLOR_COMPANYNAME As String = "#007dc2"
Public ConstDEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
Public ConstDEFAULT_BORDERCOLOR_TABLE As String = "#808080"
Public ConstDEFAULT_BACKGROUNDCOLOR_ROW As String = "#edf5ff"
Public ConstDEFAULT_COLOR_HEADERROW As String = "#ffffff"
End Class
End Namespace
- 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
<%@ PageTitle="Export Selected Datalist Row Using itextsharp in ASP.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="ExportSelectedDatalistRowToPDF._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Export Selected Datalist Row Using itextsharp in ASP.Net
</h3>
<asp:Literal ID="ltScript"runat="server"></asp:Literal>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
<div class="btn-group">
<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="ExportToPDF"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdExportAll"runat="server"CssClass="btn btn-small" OnClick="cmdExportAll_Click" Causesvalidation="false">
<i class="icon-exportpdf"></i> <asp:label id="lblExportAll" runat="server" Text="ExportAllToPDF"></asp:label>
</asp:LinkButton>
</div>
</td>
</tr>
<trid="trMessage"runat="server"visible="false">
<tdcolspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<tdcolspan="2">
<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 align="center"width="20px">
<asp:CheckBox ID="chkAll" runat="server"/>
</th>
<th colspan="5">
<table id="tblProduct"runat="server"cellpadding="0"cellspacing="0"width="100%">
<tr>
<thalign="center"width="200">ProductName</th>
<thalign="center"width="100">QuantityPerUnit</th>
<thalign="center"width="80">UnitPrice</th>
<th align="center" width="80">UnitsInStock</th>
<thalign="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>
<tdalign="center"width="20px">
<asp:CheckBox ID="chkSelect"runat="server"/>
</td>
<tdalign="left"width="200"><%# Eval("ProductName") %></td>
<tdalign="left"width="100"><%# Eval("QuantityPerUnit") %></td>
<tdalign="right"width="80"><%# Eval("UnitPrice") %></td>
<tdalign="right"width="80"><%# Eval("UnitsInStock") %></td>
<tdalign="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"/>
<asp:PostBackTrigger ControlID="cmdExportAll"/>
</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 ExportSelectedDatalistRowToPDF
{
public partial class _Default : System.Web.UI.Page
{
#region"Export PDF"
private voidExportToPDF(string FileName, bool ExportAll)
{
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, 12, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
Font fontHeader = newFont(bf, 11, Font.BOLD, Color.BLUE);
Font fontSubHeader = newFont(bf, 10);
Font fontContent = newFont(bf, 10, Font.NORMAL, Color.BLACK);
Font fontTableHeader = newFont(bf, 10, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)));
try
{
PdfWriterwriter = 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
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 = newPhrase(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 = newiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));
datatable.BorderColor = newiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE));
int iRow = dlObject.Items.Count;
bool b_SelectedRow = false;
int iAlign = 0;
string cellValue = "";
for (i = 0; i <= iRow - 1; i++)
{
HtmlTable tblInfo;
DataListItem mySelectedRow = dlObject.Items[i];
CheckBox chkSelect = mySelectedRow.FindControl("chkSelect") asCheckBox;
tblInfo = mySelectedRow.FindControl("tblInfo") as HtmlTable;
if (chkSelect != null & tblInfo != null)
{
if (ExportAll)
{
b_SelectedRow = true;
}
else
{
b_SelectedRow = chkSelect.Checked;
}
if(b_SelectedRow)
{
for (int j = 1; j <= iColumn; 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 voidBindProduct()
{
DataTable objBind = newDataTable();
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 DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Products.* From Products");
return objBind;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindProduct();
}
}
catch
{
}
}
protected voidcmdExport_Click(object sender, System.EventArgs e)
{
ExportToPDF("List-Product.pdf", false);
}
protected voidcmdExportAll_Click(object sender, System.EventArgs e)
{
ExportToPDF("List-Product.pdf", true);
}
#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 ExportSelectedDatalistRowUsingItextsharp
Public Class _Default
Inherits System.Web.UI.Page
#Region "Export PDF"
Private SubExportToPDF(ByVal FileName As String, ByVal ExportAll As Boolean)
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 AsNew Font(bf, 10, Font.BOLD, NewColor(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)))
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 = "LIST PRODUCT" & 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 iColumn AsInteger = 0
Dim i AsInteger = 0
Dim tblProduct AsHtmlControls.HtmlTable = dlObject.Controls(0).Controls(0).FindControl("tblProduct")
If NottblProduct Is NothingThen
For i = 0 TotblProduct.Rows(0).Cells.Count - 1
iColumn += 1
Next
End If
If iColumn > 0 Then
Dim datatable AsNew iTextSharp.text.Table(iColumn)
Dim headerwidths As Single() = New Single(iColumn - 1) {}
datatable.Padding = 2
datatable.Spacing = 1
datatable.WidthPercentage = 98
For i = 0 TotblProduct.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 = NewiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE))
datatable.BorderColor = NewiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BORDERCOLOR_TABLE))
Dim iRow AsInteger = dlObject.Items.Count
Dim b_SelectedRow As Boolean = False
Dim iAlign AsInteger = 0
Dim cellValue AsString = ""
For i = 0 ToiRow - 1
Dim mySelectedRow As DataListItem = dlObject.Items(i)
DimchkSelect As CheckBox= TryCast(mySelectedRow.FindControl("chkSelect"), CheckBox)
Dim tblInfo As HtmlControls.HtmlTable = TryCast(mySelectedRow.FindControl("tblInfo"), HtmlTable)
If Not chkSelect Is Nothing And Not tblInfo Is Nothing Then
If ExportAll Then
b_SelectedRow = True
Else
b_SelectedRow = chkSelect.Checked
End If
If b_SelectedRow Then
For j As Integer = 1 ToiColumn
Select CasetblInfo.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
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 SubBindProduct()
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 FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Products.* From Products")
Return objBind
End Function
#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
BindProduct()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdExport.Click
ExportToPDF("List-Product.pdf", False)
End Sub
Private SubcmdExportAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdExportAll.Click
ExportToPDF("List-Product.pdf", True)
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment