(Export dữ liệu trong Asp.net sử dụng thư viện iTextSharp) – iTextSharp là một thư viện cho phép bạn tạo và thao tác các tài liệu PDF, iTextSharp cung cấp các tính năng cho phép người phát triển như:
- Tạo ra các tài liệu động từ các tập tin XML hoặc cơ sở dữ liệu
- Thêm dấu trang, số trang, hình mờ
- Chia, nối, và thao tác các trang PDF
- Điền các thông tin vào file PDF có sẵn
- Thêm chữ ký số vào một file PDF
Bài viết dưới đây, thủ thuật tin học sẽ giới thiệu với các bạn cách sử dụng thư viện iTextSharp để Export thông tin chi tiết 1 bản ghi ra file PDF.
- Tạo ra các tài liệu động từ các tập tin XML hoặc cơ sở dữ liệu
- Thêm dấu trang, số trang, hình mờ
- Chia, nối, và thao tác các trang PDF
- Điền các thông tin vào file PDF có sẵn
- Thêm chữ ký số vào một file PDF
Bài viết dưới đây, thủ thuật tin học sẽ giới thiệu với các bạn cách sử dụng thư viện iTextSharp để Export thông tin chi tiết 1 bản ghi ra file PDF.
- B1: Tạo CSDL SQL Customers
- B2: Tạo Bảng Contacts có cấu trúc phía dưới trong CSDL SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | ContactID | Int | Trường tự tăng |
2 | ContactCode | nvarchar(25) | |
3 | ContactName | nvarchar(250) | |
4 | Sex | bit | |
5 | Birthdate | datetime | |
6 | ContactAddress | nvarchar(250) | |
7 | Mobille | nvarchar(50) | |
8 | nvarchar(150) | ||
9 | CreatedDate | datetime | |
10 | ModifiedDate | datetime |
- B3: Nhập dữ liệu cho bảng Contacts
- B4: Tạo các stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Contacts_List]
@Keyword nvarchar(250),
@SortField nvarchar(50),
@SortType nvarchar(10)
AS
declare @strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Contacts'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (ContactCode like N''%' +@Keyword+'%''
Or ContactName like N''%' +@Keyword+'%'' Or ContactAddress like N''%' +@Keyword+'%''
Or Mobille like N''%' +@Keyword+'%'' Or Email like N''%' +@Keyword+'%'')'
if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by ContactName'
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
- B5: 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.
Imports System.Data.SqlClient
Imports System.Data
Namespace ExportRecordsUsingItextsharp
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 FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If NotPara Is NothingThen
For Eachp As ObjectParaIn Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
End If
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn AsNew SqlConnection(_connectionString)
_cnn.Open()
Dim cmd AsNew SqlCommand(ProcName, _cnn)
cmd.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
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 MyEventArgs
Inherits EventArgs
Private Name As String
Private MyId As String
Public PropertySelectedName() As String
Get
Return Name
End Get
Set(ByVal value As String)
Name = value
End Set
End Property
Public Property Id() As String
Get
Return MyId
End Get
Set(ByVal value As String)
MyId = 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
- B6: Download thư viện iTextSharp tại đây
- B7: References itextsharp.dll trong thư mục vừa giải nén vào Project
- B8: 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.
- B9: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục Images
+ delete.gif, icon_search.gif, icon_pdf.gif vào thư mục Images
+ no.png, yes.png, sprite.png, lt.gif vào thư mục Styles\Images
- B10: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Export Records Using Itextsharp in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportRecordsUsingItextsharp._Default" %>
<%@ RegisterTagPrefix="ModalPopup"TagName="ViewRecord"Src="~/UserControls/Popup_ViewRecord.ascx"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="Delete"Src="~/UserControls/Popup_ConfirmDelete.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h1>
Export Records Using Itextsharp in ASP.Net
</h1>
<br />
<ModalPopup:ViewRecord ID="ucViewRecord"runat="server"/>
<ModalPopup:Delete ID="ucDeleteItem"runat="server"/>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
</td>
<tdalign="right">
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</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:GridView ID="grvObject" runat="server"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="ContactID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<Columns>
<asp:TemplateField HeaderText="ContactCode">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:LinkButton id="cmdContactCode" runat="server" CausesValidation="False" CommandName="View" CommandArgument='<%# Eval("ContactID") %>' text='<%# Eval("ContactCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContactName">
<ItemStyle width="12%" />
<ItemTemplate>
<asp:LinkButton id="cmdContactName"runat="server"CausesValidation="False"CommandName="View"CommandArgument='<%# Eval("ContactID") %>' text='<%# Eval("ContactName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Birthdate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblBirthdate"Text='<%# Eval("Birthdate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobille">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblMobille"Text='<%# Eval("Mobille") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblEmail"Text='<%# Eval("Email") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center"width="5%"/>
<ItemTemplate>
<asp:ImageButton ID="cmdExport"CommandName="ExportPDF"CommandArgument='<%# Eval("ContactID")%>' runat="server"ImageUrl="~/images/icon_pdf.gif"CausesValidation="False"></asp:ImageButton>
<asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("ContactID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B11: Viết Code cho file Default.aspx
Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Namespace ExportRecordsUsingItextsharp
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
'"simsun.ttf" file was downloaded from web and placed in the folder
Dimbf As BaseFont= BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
'create new font based on BaseFont
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
' creation of the different writers
Dim writer AsPdfWriter = PdfWriter.GetInstance(document, msReport)
' we add some meta information to the document
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://thuthuatlaptrinh.blogspot.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 = NewPhrase(beginning)
Dim pAddresse AsNew 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 AsNew Paragraph()
pAddresse.IndentationLeft = 30
pAddresse.Add(p1)
document.Add(pAddresse)
End If
'=================End Header =====================
'Title
sText = "CONTACT 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 = 95
Dim headerwidths As Single() = {16, 34, 16, 34}
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_Contacts_Get", New ObjectPara("@ContactID", ItemID))
If NotobjInfo Is NothingThen
With objInfo
'ContactCode
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Contact Code", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("ContactCode"), fontContent))
'ContactName
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Contact Name", fontTitle))
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase(objInfo("ContactName"), fontContent))
'Address
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Address", fontTitle))
datatable.DefaultColspan = 3
If Not IsDBNull(objInfo("Address")) Then
datatable.AddCell(New Phrase(objInfo("Address"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
'Sex
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Sex", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("Sex")) Then
If objInfo("Sex") Then
datatable.AddCell(New Phrase("Male", fontContent))
Else
datatable.AddCell(New Phrase("Female", fontContent))
End If
Else
datatable.AddCell(New Phrase("Female", fontContent))
End If
'Birthdate
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Birthdate", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("Birthdate")) Then
datatable.AddCell(New Phrase(CType(objInfo("Birthdate"), Date).ToShortDateString, fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
'Email
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Email", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("Email")) Then
datatable.AddCell(New Phrase(objInfo("Email"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
'Mobille
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("Mobille", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("Mobille")) Then
datatable.AddCell(New Phrase(objInfo("Mobille"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
'CreatedDate
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("CreatedDate", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("CreatedDate")) Then
datatable.AddCell(New Phrase(objInfo("CreatedDate"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
'ModifiedDate
datatable.DefaultColspan = 1
datatable.AddCell(New Phrase("ModifiedDate", fontTitle))
datatable.DefaultColspan = 1
If Not IsDBNull(objInfo("ModifiedDate")) Then
datatable.AddCell(New Phrase(objInfo("ModifiedDate"), fontContent))
Else
datatable.AddCell(New Phrase("", fontContent))
End If
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 SubBindContact()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
Else
trMessage.Visible = True
grvObject.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("Pro_Contacts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@SortField", "CreatedDate"), _
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "GridView Methods"
Private SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
Select Casee.CommandName.ToLower
Case "view"
With CType(ucViewRecord, ExportRecordsUsingItextsharp.UserControls.Popup_ViewRecord)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
Case "exportpdf"
ExportToPDF(ItemID, "ContactInfo_"& ItemID & ".pdf")
End Select
End Sub
Private SubgrvObject_RowDeleting(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvObject.RowDeleting
Dim ItemID As Integer = CType(grvObject.DataKeys(e.RowIndex).Value, Integer)
Dim ItemName As String = ""
If ItemID <> -1 Then
WithCType(ucDeleteItem, ExportRecordsUsingItextsharp.UserControls.Popup_ConfirmDelete)
.ItemID = ItemID
.ShowPopup(ItemID, "")
End With
End If
End Sub
Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ContactID AsInteger = DataBinder.Eval(e.Row.DataItem, "ContactID")
'Export
Dim cmdExport AsImageButton = DirectCast(e.Row.FindControl("cmdExport"), ImageButton)
If NotcmdExport Is NothingThen
cmdExport.ToolTip = "Export Contact"
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport)
End If
'Delete
Dim cmdDelete AsImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If NotcmdDelete Is NothingThen
cmdDelete.ToolTip = "Delete Contact"
End If
End If
End Sub
#End Region
#Region "Popup"
Private SubMySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e AsExportRecordsUsingItextsharp.MyEventArgs)
Dim ItemName As String = ""
With e
If e.Id <> "" Then
BindContact()
End If
End With
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
AddHandler CType(ucDeleteItem, ExportRecordsUsingItextsharp.UserControls.Popup_ConfirmDelete).OnSelectedRow, AddressOf MySelDelete_OnSelectedRow
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindContact()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindContact()
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