News Ticker

Menu

Sử dụng iTextSharp để hiển thị ảnh trong ô của bảng khi Export trong Asp.net

(Display images in cells of a table in PDF) – Khi sử dụng iTextSharp để chèn ảnh vào file PDF việc xác định vị trí cần chèn là công việc đòi hỏi độ chính xác và mất nhiều thời gian để căn chỉnh tọa độ. Vậy việc chèn ảnh vào các ô trong Table thì sao? Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng iTextSharp để chèn ảnh vào các ô của Table khi Export 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 Customers trong SQL Server

B2: Tạo Bảng Players có cấu trúc phía dưới

STTTên trườngKiểu trườngGhi chú
1ItemIDIntTrường tự tăng
2Namenvarchar(35)
3Midfieldnvarchar(50)
4DateofbirthDatetime
5Countrynvarchar(50)
6Clubnvarchar(50)
7Heightnvarchar(50)
8Weightnvarchar(50)
9ImageURLnvarchar(200)

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


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
B4: 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.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace UsingiTextSharpDisplayImagesInCellsTable
{
    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;
            }
        }
        #endregion
    }
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace UsingiTextSharpDisplayImagesInCellsTable

    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

#End Region

    End Class

End Namespace

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B5: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục Images của Project

B6: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ Page Title="Using iTextSharp to Display Images in Cells of a Table in PDF" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UsingiTextSharpDisplayImagesInCellsTable._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Using iTextSharp to Display Images in Cells of a Table in PDF
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                        <asp:LinkButton id="cmdExport" runat="server" CssClass="btn btn-small" OnClick="cmdExport_Click" Causesvalidation="false">
                            <i class="icon-exportpdf"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="Export PDF"></asp:label>
                        </asp:LinkButton>
                    </td>
                </tr>
                <tr id="trMessage" runat="server" visible="false">
                    <td>
                        <asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="PlayerID" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                          <ItemStyle HorizontalAlign="Left" width="15%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblName" Text='<%# Eval("Name") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Midfield">
                                          <ItemStyle HorizontalAlign="Left" width="12%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblMidfield" Text='<%# Eval("Midfield") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>  
                                <asp:TemplateField HeaderText="Dateofbirth">
                                          <ItemStyle HorizontalAlign="Center" width="10%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblDateofbirth" Text='<%# Eval("Dateofbirth","{0:d}") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>   
                                <asp:TemplateField HeaderText="Country">
                                          <ItemStyle width="10%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>  
                                <asp:TemplateField HeaderText="Club">
                                          <ItemStyle width="10%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblClub" Text='<%# Eval("Club") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Height">
                                          <ItemStyle width="10%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblHeight" Text='<%# Eval("Height") %>' runat="server"></asp:Label>
                                    </ItemTemplate>         
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Weight">
                                    <ItemStyle width="10%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblWeight" Text='<%# Eval("Weight") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>      
                                <asp:TemplateField HeaderText="Image">
                                          <ItemStyle HorizontalAlign="Center" width="3%" />   
                                    <ItemTemplate>
                                        <asp:Image ID="imgPlayer" Width="40" ImageUrl='<%#Eval("ImageURL")%>' runat="server" />
                                    </ItemTemplate>                          
                                </asp:TemplateField>                               
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdExport" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Content>

B7: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace UsingiTextSharpDisplayImagesInCellsTable
{
    public partial class _Default : System.Web.UI.Page
    {
        #region "Private Methods"

        private byte[] imageToByteArray(System.Drawing.Image obj)
        {
            using (var ms = new MemoryStream())
            {
                obj.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }

        #endregion

        #region "Export PDF"

        private void ExportToPDF(string FileName)
        {
            DataTable objBind = new DataTable();
            Document oDoc = new Document(PageSize.A4, 20, 20, 30, 20);
            System.IO.MemoryStream msReport = new System.IO.MemoryStream();
            string sText = "";
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            Font fontHeader = new Font(bf, 12, Font.BOLD, Color.BLUE);
            Font fontTableHeader = new Font(bf, 10, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")));
            Font fontContent = new Font(bf, 11, Font.NORMAL, Color.BLACK);
            string DEFAULT_BACKGROUNDCOLOR_HEADERROW = "#99cd00";
            string DEFAULT_BORDERCOLOR_TABLE = "#808080";

            try
            {
                PdfWriter writer = PdfWriter.GetInstance(oDoc, msReport);
                Chunk beginning = default(Chunk);
                Phrase p1 = default(Phrase);
                oDoc.Open();

                //Title
                sText = "LIST ACCOUNT";
                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);
                    oDoc.Add(pAddresse);
                }

                iTextSharp.text.Table datatable = new iTextSharp.text.Table(5);
                datatable.Padding = 2;
                datatable.Spacing = 1;
                datatable.WidthPercentage = 95;

                float[] HeaderWidths = {26,18,20,18,12};
                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(DEFAULT_BORDERCOLOR_TABLE));
                datatable.BorderColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BORDERCOLOR_TABLE));

                objBind = BindData();

                if (objBind != null)
                {
                    if (objBind.Rows.Count > 0)
                    {
                        //Header Table
                        Cell cellText = new Cell(new Phrase("Name", fontTableHeader));
                        cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                        datatable.AddCell(cellText);

                        cellText = new Cell(new Phrase("Midfield", fontTableHeader));
                        cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                        datatable.AddCell(cellText);

                        cellText = new Cell(new Phrase("Country", fontTableHeader));
                        cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                        datatable.AddCell(cellText);

                        cellText = new Cell(new Phrase("Club", fontTableHeader));
                        cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                        datatable.AddCell(cellText);

                        cellText = new Cell(new Phrase("Image", fontTableHeader));
                        cellText.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW));
                        datatable.AddCell(cellText);

                        foreach (DataRow row in objBind.Rows)
                        {
                            if (row != null)
                            {
                                datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;
                                datatable.AddCell(new Phrase(row["Name"].ToString(), fontContent));
                                datatable.AddCell(new Phrase(row["Midfield"].ToString(), fontContent));
                                datatable.AddCell(new Phrase(row["Country"].ToString(), fontContent));
                                datatable.AddCell(new Phrase(row["Club"].ToString(), fontContent));
                                //Add Image
                                string ImageName = "";
                                Cell cell = new Cell();
                                if (row["ImageURL"] != null)
                                {
                                    ImageName = row["ImageURL"].ToString();
                                }
                                iTextSharp.text.Image img = new Jpeg(imageToByteArray(System.Drawing.Image.FromFile(Server.MapPath(ImageName))));
                                img.ScaleToFit(50, 50);
                                cell = new Cell(img);
                                cell.VerticalAlignment = Element.ALIGN_CENTER;
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                                datatable.AddCell(cell);
                            }
                        }
                        oDoc.Add(datatable);
                    }
                }
            }
            catch
            {
            }
            oDoc.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 BindPlayers()
              {
                     DataTable objBind = new DataTable();
                     objBind = BindData();

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

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

              #endregion

        #region "Event Handles"

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

        protected void cmdExport_Click(object sender, System.EventArgs e)
        {
            ExportToPDF("List-Players.pdf");
        }

        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO
Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf

Namespace UsingiTextSharpDisplayImagesInCellsTable

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Methods"

        Private Function imageToByteArray(ByVal obj As System.Drawing.Image) As Byte()
            Using ms = New MemoryStream()
                obj.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
                Return ms.ToArray()
            End Using
        End Function

#End Region

#Region "Export PDF"

        Private Sub ExportToPDF(ByVal FileName As String)
            Dim objBind As New DataTable
            Dim oDoc As New Document(PageSize.A4, 20, 20, 30, 20)
            Dim msReport As New System.IO.MemoryStream()
            Dim FilePath As String = ""
            Dim sText As String = ""
            Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED)
            Dim fontHeader As New Font(bf, 12, Font.BOLD, Color.BLUE)
            Dim fontTableHeader As New Font(bf, 10, Font.BOLD, New Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")))
            Dim fontContent As New Font(bf, 11, Font.NORMAL, Color.BLACK)
            Dim DEFAULT_BACKGROUNDCOLOR_HEADERROW As String = "#99cd00"
            Dim DEFAULT_BORDERCOLOR_TABLE As String = "#808080"

            Try
                Dim writer As PdfWriter = PdfWriter.GetInstance(oDoc, msReport)
                Dim beginning As Chunk
                Dim p1 As Phrase
                oDoc.Open()

                'Title
                sText = "LIST ACCOUNT" & 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)
                    oDoc.Add(pAddresse)
                End If

                Dim datatable As New iTextSharp.text.Table(5)
                datatable.Padding = 2
                datatable.Spacing = 1
                datatable.WidthPercentage = 95

                Dim HeaderWidths As Single() = {26, 18, 20, 18, 12}
                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(DEFAULT_BORDERCOLOR_TABLE))
                datatable.BorderColor = New iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BORDERCOLOR_TABLE))

                objBind = BindData()

                If Not objBind Is Nothing Then
                    If objBind.Rows.Count > 0 Then
                        'Header Table
                        Dim cellText As New Cell(New Phrase("Name", fontTableHeader))
                        cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                        datatable.AddCell(cellText)

                        cellText = New Cell(New Phrase("Midfield", fontTableHeader))
                        cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                        datatable.AddCell(cellText)

                        cellText = New Cell(New Phrase("Country", fontTableHeader))
                        cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                        datatable.AddCell(cellText)

                        cellText = New Cell(New Phrase("Club", fontTableHeader))
                        cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                        datatable.AddCell(cellText)

                        cellText = New Cell(New Phrase("Image", fontTableHeader))
                        cellText.BackgroundColor = New Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BACKGROUNDCOLOR_HEADERROW))
                        datatable.AddCell(cellText)

                        For Each row As DataRow In objBind.Rows
                            If Not row Is Nothing Then
                                datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT
                                datatable.AddCell(New Phrase(row("Name").ToString(), fontContent))
                                datatable.AddCell(New Phrase(row("Midfield").ToString(), fontContent))
                                datatable.AddCell(New Phrase(row("Country").ToString(), fontContent))
                                datatable.AddCell(New Phrase(row("Club").ToString(), fontContent))
                                'Add Image
                                Dim ImageName As String = ""
                                Dim cell As New Cell
                                If Not IsDBNull(row("ImageURL")) Then
                                    ImageName = row("ImageURL")
                                End If
                                Dim img As iTextSharp.text.Image = New Jpeg(imageToByteArray(System.Drawing.Image.FromFile(Server.MapPath(ImageName))))
                                img.ScaleToFit(50, 50)
                                cell = New Cell(img)
                                cell.VerticalAlignment = Element.ALIGN_CENTER
                                cell.HorizontalAlignment = Element.ALIGN_CENTER
                                datatable.AddCell(cell)
                            End If
                        Next
                        oDoc.Add(datatable)
                    End If
                End If
            Catch e As Exception
                Console.Error.WriteLine(e.Message)
            End Try
            oDoc.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 BindPlayers()
            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
            End If
            updatePanel.Update()
        End Sub

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

#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
                    BindPlayers()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdExport.Click
            ExportToPDF("List-Players.pdf")
        End Sub

#End Region

    End Class

End Namespace

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:

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 để hiển thị ảnh trong ô của bảng khi Export 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