News Ticker

Menu

Sử dụng iTextSharp để Export thông tin bản ghi trong Datalist

(Sử dụng iTextSharp để xuất thông tin bản ghi ra PDF) – Bài viết dưới đây sẽ hướng dẫn các  bạn cách sử dụng Datalist để hiển thị danh sách dữ liệu và tương ứng với mỗi bản ghi sẽ có chức năng Export. Khi kích nút Export chương trình sẽ tự động lấy toàn bộ thông tin bản ghi để xuất ra file PDF. Dưới đây là các bước thực hiện.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube




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



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

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.

C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using System.Text;
using System.Web;

namespace ExportRecordUsingItextsharpInDatalist
{
    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 string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string sql)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        public DataRow GetRow(string ProcName, params ObjectPara[] Para)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
                adap.SelectCommand.CommandType = CommandType.StoredProcedure;
                foreach (ObjectPara p in Para)
                {
                    adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
                }
                adap.Fill(tb);
                if (tb.Rows != null)
                {
                    return tb.Rows[0];
                }
            }
            catch
            {
                return null;
            }
            return null;
        }

        #endregion
    }

    public class ObjectPara
    {
        string _name;

        object _Value;
        public ObjectPara(string Pname, object PValue)
        {
            _name = Pname;
            _Value = PValue;
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public object Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
    }

    public class Constants
    {
        public const string DEFAULT_COLOR_COMPANYNAME = "#007dc2";
    }
}

VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace ExportRecordUsingItextsharpInDatalist

    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 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 Constants

        Public Const DEFAULT_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

- B4: Download  thư viện iTextSharp tại đây

- B5: References  itextsharp.dll trong thư mục vừa giải nén vào Project.

- B6: 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

B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page Title="Export Records Using Itextsharp in Datalist ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportRecordUsingItextsharpInDatalist._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Export Records Using Itextsharp in Datalist
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td colspan="2">
                        <asp:DataList ID="lstEmployees" runat="server" CellPadding="0" CellSpacing="0" Width="100%"
                        OnItemCommand="lstEmployees_ItemCommand"
                        OnItemDataBound="lstEmployees_ItemDataBound"
                        RepeatDirection="Horizontal" RepeatColumns="3">
                            <ItemTemplate>
                                <table align="left" cellpadding="2" cellspacing="3" style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;" width="300px" height="160px">
                                    <tr>
                                        <td colspan="2" class="info">
                                            <asp:Label ID="lblFullName" Text='<%# Eval("LastName") + "&nbsp;&nbsp;"+ Eval("FirstName") %>' runat="server" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plTitle" runat="server" Text="Title"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblTitle" text='<%#  Eval("Title")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plAddress" runat="server" Text="Address"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblAddress" text='<%#  Eval("Address")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plCity" runat="server" Text="City"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblCity" text='<%#  Eval("City")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="pRegion" runat="server" Text="Region"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblRegion" text='<%#  Eval("Region")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plPostalCode" runat="server" Text="PostalCode"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblPostalCode" text='<%#  Eval("PostalCode")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" align="right">
                                             <asp:ImageButton ID="cmdExport" CommandName="ExportPDF" CommandArgument='<%# Eval("EmployeeID")%>' runat="server" ImageUrl="~/images/icon_pdf.gif" CausesValidation="False"></asp:ImageButton>
                                        </td>
                                    </tr>
                                </table>
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Top" />
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

VB.Net Code
<%@ Page Title="Export Records Using Itextsharp in Datalist" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportRecordUsingItextsharpInDatalist._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Export Records Using Itextsharp in Datalist
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td colspan="2">
                        <asp:DataList ID="lstEmployees" runat="server" CellPadding="0" CellSpacing="0" Width="100%" RepeatDirection="Horizontal" RepeatColumns="3">
                            <ItemTemplate>
                                <table align="left" cellpadding="2" cellspacing="3" style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;" width="300px" height="160px">
                                    <tr>
                                        <td colspan="2" class="info">
                                            <asp:Label ID="lblFullName" Text='<%# Eval("LastName") & "&nbsp;&nbsp;" & Eval("FirstName") %>' runat="server" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plTitle" runat="server" Text="Title"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblTitle" text='<%#  Eval("Title")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plAddress" runat="server" Text="Address"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblAddress" text='<%#  Eval("Address")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plCity" runat="server" Text="City"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblCity" text='<%#  Eval("City")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="pRegion" runat="server" Text="Region"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblRegion" text='<%#  Eval("Region")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <b><asp:Label ID="plPostalCode" runat="server" Text="PostalCode"></asp:Label></b>:
                                        </td>
                                        <td>
                                            <asp:Label ID="lblPostalCode" text='<%#  Eval("PostalCode")%>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" align="right">
                                             <asp:ImageButton ID="cmdExport" CommandName="ExportPDF" CommandArgument='<%# Eval("EmployeeID")%>' runat="server" ImageUrl="~/images/icon_pdf.gif" CausesValidation="False"></asp:ImageButton>
                                        </td>
                                    </tr>
                                </table>
                            </ItemTemplate>
                            <ItemStyle VerticalAlign="Top" />
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B8: Viết Code cho file Default.aspx

C#
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace ExportRecordUsingItextsharpInDatalist
{
    public partial class _Default : System.Web.UI.Page
    {
        #region "Export PDF"

        private void ExportToPDF(int ItemID, string FileName)
        {
            Document document = new Document(PageSize.A4, 10f, 10f, 5f, 0f);
            System.IO.MemoryStream msReport = new System.IO.MemoryStream();
            string FilePath = "";

            FilePath = Server.MapPath("Fonts\\ARIALUNI.TTF");
            string fontpath = FilePath;
            BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font fontCompany = new Font(bf, 13, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml(Constants.DEFAULT_COLOR_COMPANYNAME)));
            Font fontHeader = new Font(bf, 12, Font.BOLD, Color.BLUE);
            Font fontSubHeader = new Font(bf, 10);
            Font fontTitle = new Font(bf, 11, Font.BOLD, Color.BLACK);
            Font fontContent = new Font(bf, 11, Font.NORMAL, Color.BLACK);

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(document, msReport);
                document.AddAuthor("Thu thuat lap trinh");
                document.AddSubject("Export to PDF");
                document.Open();

                Chunk cBreak = new Chunk(Environment.NewLine);
                Phrase pBreak = new Phrase();
                Paragraph paBreak = new Paragraph();

                //=================Start Header =====================
                //CompnayName
                string sText = "THỦ THUẬT LẬP TRÌNH";
                Chunk beginning = new Chunk(sText, fontCompany);
                Phrase p1 = new Phrase(beginning);
                Paragraph pCompanyName = new Paragraph();
                pCompanyName.IndentationLeft = 30;
                pCompanyName.Add(p1);
                document.Add(pCompanyName);

                //Website
                string sWebsite = "Website: http://www.laptrinhdotnet.com";
                sText = "";
                if (!string.IsNullOrEmpty(sWebsite))
                {
                    sText = sWebsite;
                }

                if (!string.IsNullOrEmpty(sText))
                {
                    sText = sText.Replace(Environment.NewLine, string.Empty).Replace("  ", string.Empty);
                    beginning = new Chunk(sText, fontSubHeader);
                    p1 = new Phrase(beginning);
                    Paragraph pAddresse = new Paragraph();
                    pAddresse.IndentationLeft = 30;
                    pAddresse.Add(p1);
                    document.Add(pAddresse);
                }

                string sEmail = "Email: kenhphanmemviet@gmail.com";
                if (!string.IsNullOrEmpty(sEmail))
                {
                    sText = sEmail;
                }

                if (!string.IsNullOrEmpty(sText))
                {
                    sText = sText.Replace(Environment.NewLine, string.Empty).Replace("  ", string.Empty);
                    beginning = new Chunk(sText, fontSubHeader);
                    p1 = new Phrase(beginning);
                    Paragraph pAddresse = new Paragraph();
                    pAddresse.IndentationLeft = 30;
                    pAddresse.Add(p1);
                    document.Add(pAddresse);
                }
                //=================End Header =====================

                //Title
                sText = "EMPLOYEE INFO" + 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);
                }

                iTextSharp.text.Table datatable = new iTextSharp.text.Table(4);

                datatable.Padding = 1;
                datatable.Spacing = 0;
                datatable.WidthPercentage = 98;

                float[] headerwidths = {12,38,14,35};
                datatable.Widths = headerwidths;

                datatable.DefaultCellBorderWidth = 0;
                datatable.BorderWidth = 0;
                datatable.DefaultHorizontalAlignment = 3;
                datatable.DefaultVerticalAlignment = 1;

                SqlDataProvider objSQL = new SqlDataProvider();
                DataRow objInfo = objSQL.GetRow("Pro_Employees_Get", new ObjectPara("@EmployeeID", ItemID));

                if (objInfo != null)
                {
                    //LastName
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("LastName", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["LastName"].ToString(), fontContent));
                    //FirstName
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("FirstName", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["FirstName"].ToString(), fontContent));

                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("Title", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["Title"].ToString(), fontContent));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("TitleOfCourtesy", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["TitleOfCourtesy"].ToString(), fontContent));

                    //Address
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("Address", fontTitle));
                    datatable.DefaultColspan = 3;
                    if (objInfo["Address"] != null)
                    {
                        datatable.AddCell(new Phrase(objInfo["Address"].ToString(), fontContent));
                    }
                    else
                    {
                        datatable.AddCell(new Phrase("", fontContent));
                    }
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("City", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["City"].ToString(), fontContent));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase("Region", fontTitle));
                    datatable.DefaultColspan = 1;
                    datatable.AddCell(new Phrase(objInfo["Region"].ToString(), fontContent));

                    document.Add(datatable);
                }
            }
            catch
            {
            }
            document.Close();
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(msReport.ToArray());
            Response.End();
        }

        #endregion

        #region "Bind Data"

        private void BindEmployees()
        {
            DataTable objBind = new DataTable();
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    lstEmployees.DataSource = objBind;
                    lstEmployees.DataBind();
                    lstEmployees.Visible = true;
                }
                else
                {
                    lstEmployees.Visible = false;
                }
                updatePanel.Update();
            }
        }

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Employees.* From Employees");
            return objBind;
        }

        #endregion

        #region "Datalist Methods"

        protected void lstEmployees_ItemCommand(object sender, DataListCommandEventArgs e)
        {
            if (e.CommandName.ToLower() != "sort" & e.CommandName.ToLower() != "page")
            {
                string[] CommandArgument = e.CommandArgument.ToString().Split(',');
                int EmployeeID = -1;

                if (CommandArgument.Length > 0)
                {
                    EmployeeID =Convert.ToInt32(CommandArgument[0]);
                }

                switch (e.CommandName.ToLower())
                {
                    case "exportpdf":
                        if (EmployeeID>0)
                        {
                            ExportToPDF(EmployeeID, "EmployeeInfo");
                        }
                        break;
                }
            }
        }

        protected void lstEmployees_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ImageButton cmdExport = (ImageButton)e.Item.FindControl("cmdExport");
                if (cmdExport != null)
                {
                    cmdExport.ToolTip = "Click to Export";
                    ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
                }
            }
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindEmployees();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}

VB.NET Code

'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 ExportRecordUsingItextsharpInDatalist

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Export PDF"

        Private Sub ExportToPDF(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
            Dim bf As BaseFont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
            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
                Dim writer As PdfWriter = PdfWriter.GetInstance(document, msReport)
                document.AddAuthor("Thu thuat lap trinh")
                document.AddSubject("Export to PDF")
                document.Open()

                Dim cBreak As New Chunk(Environment.NewLine)
                Dim pBreak As New Phrase()
                Dim paBreak As New Paragraph()

                '=================Start Header =====================
                'CompnayName
                Dim sText As String = "THỦ THUẬT LẬP TRÌNH" & vbCrLf
                Dim beginning As New Chunk(sText, fontCompany)
                Dim p1 As New Phrase(beginning)
                Dim pCompanyName As New Paragraph()
                pCompanyName.IndentationLeft = 30
                pCompanyName.Add(p1)
                document.Add(pCompanyName)

                'Website
                Dim sWebsite As String = "Website: http://www.laptrinhdotnet.com"
                sText = ""
                If sWebsite <> "" Then
                    sText = sWebsite & vbCrLf
                End If

                If sText <> "" Then
                    sText = sText.Replace(Environment.NewLine, String.Empty).Replace("  ", String.Empty)
                    beginning = New Chunk(sText, fontSubHeader)
                    p1 = New Phrase(beginning)
                    Dim pAddresse As New Paragraph()
                    pAddresse.IndentationLeft = 30
                    pAddresse.Add(p1)
                    document.Add(pAddresse)
                End If

                Dim sEmail As String = "Email: kenhphanmemviet@gmail.com"
                If sEmail <> "" Then
                    sText = sEmail & vbCrLf
                End If

                If sText <> "" Then
                    sText = sText.Replace(Environment.NewLine, String.Empty).Replace("  ", String.Empty)
                    beginning = New Chunk(sText, fontSubHeader)
                    p1 = New Phrase(beginning)
                    Dim pAddresse As New Paragraph()
                    pAddresse.IndentationLeft = 30
                    pAddresse.Add(p1)
                    document.Add(pAddresse)
                End If
                '=================End Header =====================

                'Title
                sText = "EMPLOYEE INFO" & 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(4)

                datatable.Padding = 1
                datatable.Spacing = 0
                datatable.WidthPercentage = 98

                Dim headerwidths As Single() = {12, 38, 12, 38}
                datatable.Widths = headerwidths

                datatable.DefaultCellBorderWidth = 0
                datatable.BorderWidth = 0
                datatable.DefaultHorizontalAlignment = 3
                datatable.DefaultVerticalAlignment = 1

                Dim objSQL As New SqlDataProvider
                Dim objInfo As DataRow = objSQL.GetRow("Pro_Employees_Get", New ObjectPara("@EmployeeID", ItemID))

                If Not objInfo Is Nothing Then
                    With objInfo
                        'LastName
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("LastName", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("LastName"), fontContent))
                        'FirstName
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("FirstName", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("FirstName"), fontContent))

                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("Title", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("Title"), fontContent))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("TitleOfCourtesy", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("TitleOfCourtesy"), 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

                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("City", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("City"), fontContent))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase("Region", fontTitle))
                        datatable.DefaultColspan = 1
                        datatable.AddCell(New Phrase(objInfo("Region"), fontContent))

                        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 Sub BindEmployees()
            Dim objBind As New DataTable
            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    lstEmployees.DataSource = objBind
                    lstEmployees.DataBind()
                    lstEmployees.Visible = True
                Else
                    lstEmployees.Visible = False
                End If
                updatePanel.Update()
            End If
        End Sub

        Private Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Select Employees.* From Employees")
            Return objBind
        End Function

#End Region

#Region "Datalist Methods"

        Private Sub lstEmployees_ItemCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs) Handles lstEmployees.ItemCommand
            If (e.CommandName.ToLower <> "sort" And e.CommandName.ToLower <> "page") Then
                Dim CommandArgument() As String = e.CommandArgument.ToString.Split(",")
                Dim EmployeeID As Integer = -1

                If CommandArgument.Length > 0 Then
                    EmployeeID = CommandArgument(0)
                End If

                Select Case e.CommandName.ToLower
                    Case "exportpdf"
                        If EmployeeID > 0 Then
                            ExportToPDF(EmployeeID, "EmployeeInfo")
                        End If
                End Select
            End If
        End Sub

        Private Sub lstEmployees_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs) Handles lstEmployees.ItemDataBound
            If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                Dim cmdExport As ImageButton = DirectCast(e.Item.FindControl("cmdExport"), ImageButton)
                If cmdExport IsNot Nothing Then
                    cmdExport.ToolTip = "Click to Export"
                    ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport)
                End If
            End If
        End Sub

#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    BindEmployees()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace

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




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

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 " Sử dụng iTextSharp để Export thông tin bản ghi trong Datalist "

  • 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