(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 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
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportDatalistUsingItextsharp
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
- 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 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>
<trid="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>
<thalign="center"width="220">ProductName</th>
<thalign="center"width="170">CategoryName</th>
<thalign="center"width="120">QuantityPerUnit</th>
<thalign="center"width="80">UnitPrice</th>
<thalign="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="left"width="220"><%# Eval("ProductName") %></td>
<tdalign="left"width="170"><%# Eval("CategoryName") %></td>
<tdalign="left"width="120"><%# 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"/>
</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 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, 10, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
Font fontHeader = newFont(bf, 9, Font.BOLD, Color.BLUE);
Font fontSubHeader = newFont(bf, 8);
Font fontTableHeader = newFont(bf, 8, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)));
Font fontContent = newFont(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 = 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 = 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 = 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;
int iAlign = 0;
stringcellValue = "";
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 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.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 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);
}
#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 SubExportToPDF(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 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()
DimpaBreak As New 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)
DimpAddresse As NewParagraph()
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 As Integer = 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 iAlign AsInteger = 0
Dim cellValue AsString = ""
For i = 0 ToiRow - 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 ToiColumn - 1
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
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.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 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")
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