News Ticker

Menu

Export file PDF các dòng và cột được chọn trên Gridview sử dụng iTextSharp trong ASP.Net

(Export các dòng, cột được chọn trên Gridview trong Asp.net sử dụng thư viện iTextSharp) - 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 dữ liệu ra file PDF cho phép chọn cột hoặc dòng trên Gridview. Chương trình sẽ tự động lấy toàn bộ các cột có trên Gridview để hiển thị trên Popup, người dùng có thể chọn hoặc bỏ chọn những trường hoặc các dòng dữ liệu không cần thiết để Export ra file PDF.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo CSDL SQL Customers

B2: Tạo Bảng Accounts có cấu trúc phía dưới trong CSDL SQL Server

STTTên trườngKiểu trườngGhi chú
1AccountIDIntTrường tự tăng
2AccountCodenvarchar(25)
3AccNamenvarchar(250)
4AccAddressnvarchar(250)
5AccPhonenvarchar(50)
6AccFAXnvarchar(50)
7AccEmailnvarchar(50)
8AccWebsitenvarchar(150)
9AccDescnvarchar(1500)
10CreatedDatedatetime
11ModifiedDatedatetime


B3: Nhập dữ liệu cho bảng Accounts


B4: Tạo các stored procedure trong SQL Server

USE [Customers]
GO

CREATE PROCEDURE [dbo].[Pro_Accounts_Get]
      @AccountID int
AS

SELECT * FROM Accounts
WHERE
      AccountID = @AccountID
Go

CREATE PROCEDURE [dbo].[Pro_Accounts_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 Accounts'
set @strWhere =' Where 1=1 '

if @Keyword<>''
      set @strWhere= @strWhere  +' And (AccountCode like N''%' +@Keyword+'%''
            Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
            Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
            Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'

if @SortField='CreatedDate'
      Begin
            set @strOrder =' Order by CreatedDate'
      End
Else
      Begin
            set @strOrder =' Order by AccName'
      End

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây
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 ExportSelectedGridviewColumnsUsingItextsharp

    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

        Public Function FillTable(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If Not Para Is Nothing Then
                    For Each p As ObjectPara In 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 Function RunSQL(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As Object
            Try
                Dim _cnn As New SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd As New SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Each p As ObjectPara In 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 Function GetRow(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataRow
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                For Each p As ObjectPara In 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 Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public Property Value() 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 Property SelectedName() 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 Const DEFAULT_COLOR_COMPANYNAME As String = "#007dc2"
        Public Const DEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
        Public Const DEFAULT_COLOR_HEADERROW As String = "#ffffff"
        Public Const DEFAULT_BORDERCOLOR_TABLE As String = "#808080"
        Public Const DEFAULT_BACKGROUNDCOLOR_ROW As String = "#edf5ff"
    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  thư viện AjaxControlToolkit tại đây

- B10: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

B11: 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 vào thư mục Images
+ no.png, yes.png, sprite.png, lt.gif,  icon_pdf.gif vào thư mục  Styles\Images

B12: Tạo thư mục UserControls, thêm file Popup_SelectedColumns.ascx và nhập mã HTML

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="Popup_SelectedColumns.ascx.vb" Inherits="ExportSelectedGridviewColumnsUsingItextsharp.UserControls.Popup_SelectedColumns" %>
<%@ Register TagPrefix="cc1" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" %>

<script language="javascript" type="text/javascript">
    function CheckBoxListSelect(cbControl, state) {
        var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount = chkBoxList.getElementsByTagName("input");
        for (var i = 0; i < chkBoxCount.length; i++) {
            chkBoxCount[i].checked = state;
        }
        return false;
    }
</script>

<asp:Panel ID="pnlpopup" runat="server" style="display:none">
    <asp:UpdatePanel ID="updatePanelPopup" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button id="cmdShowPopup" runat="server" style="display:none" />
            <cc1:ModalPopupExtender ID="ModalPopupExtender_Popup" runat="server" TargetControlID="cmdShowPopup" X="750" Y="150"
                PopupControlID="pnlpopup" CancelControlID="cmdCancel" BackgroundCssClass="ModalPopupBG" Drag="True" />
                <div class="modal" style="width:450px;">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" id="cmdClose" runat="server" causesvalidation="false" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                                <h4 class="modal-title">
                                    <asp:label id="lblHeader" runat="server" Text="Export only selected columns to PDF"></asp:label>
                                </h4>
                              </div>
                              <div class="modal-body">
                                   <table width="100%" cellpadding="0" cellspacing="0">
                                       <tr>
                                           <td>
                                               <asp:Label ID="lblItemID" Visible="false" runat="server"/>
                                           </td>
                                       </tr>
                                       <tr>
                                            <td style="padding-left:10px;padding-bottom:5px;">
                                                 <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',true)">
                                                       <asp:label id="plCheckAll" runat="server" CssClass="NormalBold" text="CheckAll"></asp:label>
                                                  </a>|
                                                  <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',false)">
                                                       <asp:label id="plUnCheckAll" runat="server" CssClass="NormalBold" text="UnCheckAll"></asp:label>
                                                  </a>
                                            </td>
                                       </tr>
                                       <tr>
                                           <td>
                                               <asp:CheckBoxList ID="chkExport" CellPadding="5" CellSpacing="10" RepeatColumns="2" runat="server">
                                               </asp:CheckBoxList>
                                           </td>
                                       </tr>
                                   </table>
                              </div>
                              <div class="modal-footer">
                                   <div class="btn-group">
                                        <asp:LinkButton id="cmdOK" runat="server" CssClass="btn btn-small" CausesValidation="false">
                                            <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="Export"></asp:label>
                                        </asp:LinkButton>&nbsp;
                                         <asp:LinkButton id="cmdCancel" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                                            <i class="icon-close"></i>&nbsp;&nbsp;<asp:label id="lblClose" runat="server" Text="Close"></asp:label>
                                        </asp:LinkButton>
                                   </div>
                              </div>
                        </div>
                    </div>
                </div>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdOK" />
        </Triggers>
    </asp:UpdatePanel>   
</asp:Panel>


B13: Nhập Code phía dưới cho file Popup_SelectedColumns.ascx

Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf

Namespace ExportSelectedGridviewColumnsUsingItextsharp.UserControls
    Partial Class Popup_SelectedColumns
        Inherits System.Web.UI.UserControl

#Region "Private Members"

        Private _ItemID As Integer
        Private _ItemName As String

#End Region

#Region "Event Click"

        Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As MyEventArgs)
        Public Event OnSelectedRow As MyEventHandler

#End Region

#Region "GetColumnNames"

        Private Sub BindColumn()
            Dim ColumnNames As String = lblItemID.Text
            Dim i As Integer = 0
            chkExport.Items.Clear()

            For Each sValue As String In ColumnNames.Split(",")
                If sValue <> "" Then
                    chkExport.Items.Add(New System.Web.UI.WebControls.ListItem(sValue, sValue))
                    chkExport.Items(i).Selected = True
                    i = i + 1
                End If
            Next
        End Sub

#End Region

#Region "Pulbic Methods"

        Public Sub ShowPopup(ByVal ListItemID As String)
            If ListItemID <> "" Then
                lblItemID.Text = ListItemID
            End If
            BindColumn()
            updatePanelPopup.Update()
            ModalPopupExtender_Popup.Show()
        End Sub

        Public Sub HidePopup()
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

#Region "Properties"

        Public Property ItemID() As Integer
            Get
                Return _ItemID
            End Get
            Set(ByVal Value As Integer)
                _ItemID = Value
            End Set
        End Property

        Public Property ItemName() As String
            Get
                Return _ItemName
            End Get
            Set(ByVal Value As String)
                _ItemName = Value
            End Set
        End Property

#End Region

#Region "Event Handles"

        Private Sub cmdOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOK.Click
            Dim MyArgs As New MyEventArgs()
            Dim sListExport As String = ""
            Dim i As Integer = 0
            Dim iCount As Integer = 0

            For i = 0 To chkExport.Items.Count - 1
                If chkExport.Items(i).Selected Then
                    sListExport &= chkExport.Items(i).Value & ","
                    iCount = iCount + 1
                End If
            Next

            If sListExport.Length > 0 And sListExport.EndsWith(",") Then
                sListExport = sListExport.Remove(sListExport.Length - 1, 1)
            End If

            ModalPopupExtender_Popup.Hide()

            MyArgs.Id = sListExport
            MyArgs.SelectedName = iCount
            RaiseEvent OnSelectedRow(Me, MyArgs)
        End Sub

        Private Sub cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
            ModalPopupExtender_Popup.Hide()
        End Sub

        Private Sub cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdClose.ServerClick
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

    End Class

End Namespace


B14: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ Page Title="Export Selected Gridview Columns and Rows Using itextsharp in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportSelectedGridviewColumnsUsingItextsharp._Default" %>
<%@ Register TagPrefix="ModalPopup" TagName="Delete" Src="~/UserControls/Popup_ConfirmDelete.ascx"%>
<%@ Register TagPrefix="ModalPopup" TagName="Export" Src="~/UserControls/Popup_SelectedColumns.ascx"%>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h1>
        Export Selected Gridview Columns and Rows Using itextsharp in ASP.Net
    </h1>
    <br />
    <ModalPopup:Export ID="ucSelectedColumns" 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>
                        <asp:LinkButton id="cmdExport" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                            <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="ExportToPDF"></asp:label>
                        </asp:LinkButton>
                        <asp:LinkButton id="cmdExportAll" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                            <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExportAll" runat="server" Text="ExportAllToPDF"></asp:label>
                        </asp:LinkButton>
                    </td>
                    <td align="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>
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="AccountID" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:TemplateField>
                                    <ItemStyle HorizontalAlign="Center" width="1%" />
                                    <HeaderTemplate>
                                        <asp:CheckBox ID="chkAll" runat="server" />
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField ItemStyle-Width="10%" DataField="AccountCode" HeaderText="AccountCode" />
                                <asp:BoundField ItemStyle-Width="15%" DataField="AccName" HeaderText="AccountName" />
                                <asp:BoundField ItemStyle-Width="10%" DataField="AccPhone" HeaderText="Phone" />
                                <asp:BoundField ItemStyle-Width="10%" DataField="AccFAX" HeaderText="FAX" />
                                <asp:BoundField ItemStyle-Width="15%" DataField="AccEmail" HeaderText="Email" />       
                                <asp:BoundField ItemStyle-Width="15%" DataField="AccWebsite" HeaderText="Website" />     
                                      <asp:TemplateField HeaderText="Function">
                                          <ItemStyle HorizontalAlign="Center" width="5%" /> 
                                             <ItemTemplate>
                                        <asp:ImageButton ID="cmdDelete" CommandName="Delete" CommandArgument='<%# Eval("AccountID")%>' runat="server" ImageUrl="~/images/delete.gif" CausesValidation="False"></asp:ImageButton>
                                             </ItemTemplate>
                                      </asp:TemplateField>                                
                            </Columns>                                                  
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdExport" />
            <asp:PostBackTrigger ControlID="cmdExportAll" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Content>


B15: Viết Code cho file Default.aspx

Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf

Namespace ExportSelectedGridviewColumnsUsingItextsharp

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Export PDF"

        Private Sub MySelExport_OnSelectedRow(ByVal sender As Object, ByVal e As ExportSelectedGridviewColumnsUsingItextsharp.MyEventArgs)
            Dim sExportList As String = ""
            Dim iCount As Integer = 0
            With e
                If e.Id <> "" Then
                    sExportList = e.Id
                    iCount = e.SelectedName
                    If sExportList <> "" Then
                        ExportToPDF("List-Account.pdf", False, sExportList, iCount)
                    End If
                End If
            End With
        End Sub

        Private Sub ExportToPDF(ByVal FileName As String, ByVal ExportAll As Boolean, ByVal ExportList As String, ByVal iCount As Integer)
            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
            Dim bf 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)
            Dim fontTableHeader As New Font(bf, 10, Font.BOLD, New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_HEADERROW)))

            Try
                ' creation of the different writers
                Dim writer As PdfWriter = 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 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://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 = 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 ACCOUNT" & 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 datatable As New iTextSharp.text.Table(iCount)
                datatable.Padding = 2
                datatable.Spacing = 1
                datatable.WidthPercentage = 98

                Dim headerwidths As Single() = New Single(iCount - 1) {}
                Dim x As Integer = 0
                Dim ItemStyleWidth As Integer = 10
                ItemStyleWidth = 100 / iCount

                For Each sValue As String In ExportList.Split(",")
                    'Header Table
                    headerwidths(x) = CInt(ItemStyleWidth)
                    Dim cellText As New Cell(New Phrase(sValue, fontTableHeader))
                    cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                    cellText.HorizontalAlignment = 1
                    cellText.VerticalAlignment = 1
                    datatable.AddCell(cellText)
                    x = x + 1
                Next
                datatable.Widths = headerwidths

                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 iColumn As Integer = grvObject.Columns.Count - 2
                Dim iRow As Integer = grvObject.Rows.Count - 1
                Dim b_SelectedRow As Boolean = False

                For i As Integer = 0 To iRow
                    If grvObject.Rows(i).RowType = DataControlRowType.DataRow Then
                        For j As Integer = 1 To iColumn
                            Dim mySelectedRow As GridViewRow = grvObject.Rows(i)
                            Dim chkSelect As CheckBox = TryCast(mySelectedRow.Cells(0).FindControl("chkSelect"), CheckBox)

                            If Not chkSelect Is Nothing Then
                                If ExportAll Then
                                    b_SelectedRow = True
                                Else
                                    b_SelectedRow = chkSelect.Checked
                                End If

                                If b_SelectedRow Then
                                    For Each sValue As String In ExportList.Split(",")
                                        If sValue = grvObject.Columns(j).HeaderText Then
                                            Dim mySelectedCell As TableCell
                                            Dim cellText As String = ""
                                            Dim cell As New iTextSharp.text.Cell

                                            mySelectedCell = mySelectedRow.Cells(j)
                                            cellText = mySelectedCell.Text

                                            If cellText <> "" And cellText <> "&nbsp;" Then
                                                cell = New iTextSharp.text.Cell(cellText)
                                            Else
                                                cell = New iTextSharp.text.Cell("")
                                            End If

                                            'Set Color of Alternating row
                                            If i Mod 2 <> 0 Then
                                                cell.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_BACKGROUNDCOLOR_ROW))
                                            End If
                                            datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT
                                            datatable.AddCell(cell)
                                        End If
                                    Next
                                End If
                            End If
                        Next
                    End If
                Next
                document.Add(datatable)
            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 BindAccount()
            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 Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_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 Sub grvObject_RowDeleting(ByVal sender As Object, ByVal e As System.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
                With CType(ucDeleteItem, ExportSelectedGridviewColumnsUsingItextsharp.UserControls.Popup_ConfirmDelete)
                    .ItemID = ItemID
                    .ShowPopup(ItemID, "")
                End With
            End If
        End Sub

        Private Sub grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles grvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                'Delete
                Dim cmdDelete As ImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
                If Not cmdDelete Is Nothing Then
                    cmdDelete.ToolTip = "Delete Account"
                End If
            End If
        End Sub

        Private Sub grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindAccount()
        End Sub

#End Region

#Region "Popup"

        Private Sub MySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e As ExportSelectedGridviewColumnsUsingItextsharp.MyEventArgs)
            Dim ItemName As String = ""
            With e
                If e.Id <> "" Then
                    BindAccount()
                End If
            End With
        End Sub

#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                AddHandler CType(ucDeleteItem, ExportSelectedGridviewColumnsUsingItextsharp.UserControls.Popup_ConfirmDelete).OnSelectedRow, AddressOf MySelDelete_OnSelectedRow
                AddHandler CType(ucSelectedColumns, ExportSelectedGridviewColumnsUsingItextsharp.UserControls.Popup_SelectedColumns).OnSelectedRow, AddressOf MySelExport_OnSelectedRow

                If Page.IsPostBack = False Then
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindAccount()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdQuickSearch.Click
            BindAccount()
        End Sub

        Private Sub cmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdExport.Click
            Dim ColumnNames As String = ""
            For x As Integer = 0 To grvObject.Columns.Count - 2
                ColumnNames &= grvObject.HeaderRow.Cells(x).Text & ","
            Next
            If ColumnNames.Length > 0 And ColumnNames.EndsWith(",") Then
                ColumnNames = ColumnNames.Remove(ColumnNames.Length - 1, 1)
            End If
            With CType(ucSelectedColumns, ExportSelectedGridviewColumnsUsingItextsharp.UserControls.Popup_SelectedColumns)
                .ShowPopup(ColumnNames)
            End With
        End Sub

#End Region

    End Class

End Namespace

B16: Mở file Site.Master dưới dạng HTML và  gắn thêm mã Javascript. Đoạn mã này có chức năng chọn toàn bộ các dòng khi tích chọn.

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/GridStyle.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/Button.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("[id*=chkAll]").live("click"function () {
            var chkAll = $(this);
            var grid = $(this).closest("table");
            $("input[type=checkbox]", grid).each(function () {
                if (chkAll.is(":checked")) {
                    $(this).attr("checked""checked");
                    $("td", $(this).closest("tr")).addClass("selected");
                } else {
                    $(this).removeAttr("checked");
                    $("td", $(this).closest("tr")).removeClass("selected");
                }
            });
        });
        $("[id*=chkSelect]").live("click"function () {
            var grid = $(this).closest("table");
            var chkAll = $("[id*=chkAll]", grid);
            if (!$(this).is(":checked")) {
                $("td", $(this).closest("tr")).removeClass("selected");
                chkAll.removeAttr("checked");
            } else {
                $("td", $(this).closest("tr")).addClass("selected");
                if ($("[id*=chkSelect]", grid).length == $("[id*=chkSelect]:checked", grid).length) {
                    chkAll.attr("checked""checked");
                }
            }
        });
    </script>

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Export file PDF các dòng và cột được chọn trên Gridview sử dụng iTextSharp trong ASP.Net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM