(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.
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Players có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | ItemID | Int | Trường tự tăng |
2 | Name | nvarchar(35) | |
3 | Midfield | nvarchar(50) | |
4 | Dateofbirth | Datetime | |
5 | Country | nvarchar(50) | |
6 | Club | nvarchar(50) | |
7 | Height | nvarchar(50) | |
8 | Weight | nvarchar(50) | |
9 | ImageURL | nvarchar(200) |
- B3: Nhập dữ liệu cho bảng Players
- 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 stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(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 AsString
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
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
<%@ PageTitle="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> <asp:label id="lblExport" runat="server" Text="Export PDF"></asp:label>
</asp:LinkButton>
</td>
</tr>
<trid="trMessage"runat="server"visible="false">
<td>
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="PlayerID"width="100%">
<AlternatingRowStyleCssClass="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 voidExportToPDF(string FileName)
{
DataTable objBind = newDataTable();
Document oDoc = newDocument(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 = newFont(bf, 12, Font.BOLD, Color.BLUE);
Font fontTableHeader = newFont(bf, 10, Font.BOLD, new Color(System.Drawing.ColorTranslator.FromHtml("#ffffff")));
Font fontContent = newFont(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 = newiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BORDERCOLOR_TABLE));
datatable.BorderColor = newiTextSharp.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 voidBindPlayers()
{
DataTable objBind = newDataTable();
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 DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select * from Players");
return objBind;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindPlayers();
}
}
catch
{
}
}
protected voidcmdExport_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 FunctionimageToByteArray(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 SubExportToPDF(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 AsNew Font(bf, 10, Font.BOLD, NewColor(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 AsPdfWriter = PdfWriter.GetInstance(oDoc, msReport)
Dim beginning AsChunk
Dim p1 AsPhrase
oDoc.Open()
'Title
sText = "LIST ACCOUNT"& vbCrLf
If sText <> "" Then
beginning = New Chunk(sText, fontHeader)
p1 = New Phrase(beginning)
Dim pAddresse AsNew Paragraph()
pAddresse.IndentationLeft = 10
pAddresse.Alignment = 1
pAddresse.Add(p1)
oDoc.Add(pAddresse)
End If
Dim datatable AsNew 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 = NewiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BORDERCOLOR_TABLE))
datatable.BorderColor = NewiTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml(DEFAULT_BORDERCOLOR_TABLE))
objBind = BindData()
If NotobjBind Is NothingThen
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 AsiTextSharp.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 FunctionBindData() 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 SubPage_Load(ByVal sender AsObject, 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 SubcmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdExport.Click
ExportToPDF("List-Players.pdf")
End Sub
#End Region
End Class
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment