Wednesday, 06 April 2011 09:13
PDF Bookmark in C#, VB.NET
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Bookmarks;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using Spire.Pdf.Tables;
namespace Bookmark
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
//create section
PdfSection section = doc.Sections.Add();
section.PageSettings.Size = PdfPageSize.A4;
section.PageSettings.Margins = margin;
// Create one page
PdfPageBase page = section.Pages.Add();
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Sales Report", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Sales Report", format1).Height;
y = y + 5;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
conn.Open();
OleDbCommand partQueryCommand = PreparePartQueryCommand(conn);
OleDbCommand orderItemQueryCommand = PrepareOrderItemQueryCommand(conn);
DataTable vendors = GetVendors(conn);
for (int i = 0; i < vendors.Rows.Count; i++)
{
if (i > 0)
{
//next page
page = section.Pages.Add();
y = 0;
}
//draw vendor
String vendorTitle = String.Format("{0}. {1}", i + 1, vendors.Rows[i].ItemArray[1]);
PdfLayoutResult drawVendorLayoutResult = DrawVendor(page, vendors, i, vendorTitle, y);
//add vendor bookmark
PdfDestination vendorBookmarkDest = new PdfDestination(page, new PointF(0, y));
PdfBookmark vendorBookmark = doc.Bookmarks.Add(vendorTitle);
vendorBookmark.Color = Color.SaddleBrown;
vendorBookmark.DisplayStyle = PdfTextStyle.Bold;
vendorBookmark.Action = new PdfGoToAction(vendorBookmarkDest);
y = drawVendorLayoutResult.Bounds.Bottom + 5;
page = drawVendorLayoutResult.Page;
//get parts of vendor
DataTable parts = GetParts(partQueryCommand, (double)vendors.Rows[i].ItemArray[0]);
for (int j = 0; j < parts.Rows.Count; j++)
{
if (j > 0)
{
//next page
page = section.Pages.Add();
y = 0;
}
//draw part
String partTitle = String.Format("{0}.{1}. {2}", i + 1, j + 1, parts.Rows[j].ItemArray[1]);
PdfLayoutResult drawPartLayoutResult = DrawPart(page, parts, j, partTitle, y);
//add part bookmark
PdfDestination partBookmarkDest = new PdfDestination(page, new PointF(0, y));
PdfBookmark partBookmark = vendorBookmark.Add(partTitle);
partBookmark.Color = Color.Coral;
partBookmark.DisplayStyle = PdfTextStyle.Italic;
partBookmark.Action = new PdfGoToAction(partBookmarkDest);
y = drawPartLayoutResult.Bounds.Bottom + 5;
page = drawPartLayoutResult.Page;
//get order items
String orderItemsTitle = String.Format("{0} - Order Items", parts.Rows[j].ItemArray[1]);
DataTable orderItems = GetOrderItems(orderItemQueryCommand, (double)parts.Rows[j].ItemArray[0]);
DrawOrderItems(page, orderItems, orderItemsTitle, y);
}
}
}
//Save pdf file.
doc.SaveToFile("Bookmark.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("Bookmark.pdf");
}
private static DataTable GetVendors(OleDbConnection conn)
{
String query
= " SELECT VendorNo, VendorName, Address1, City, State, Zip, Country, Phone, FAX "
+ " FROM vendors ";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
private static DataTable GetParts(OleDbCommand query, double vendorId)
{
query.Parameters[0].Value = vendorId;
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
private static DataTable GetOrderItems(OleDbCommand query, double partId)
{
query.Parameters[0].Value = partId;
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
private static PdfLayoutResult DrawVendor(PdfPageBase page, DataTable vendors, int index, String title, float y)
{
//draw title
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
DataRow row = vendors.Rows[index];
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y);
y = y + font1.MeasureString(title).Height + 1;
//draw table
Object[][] data = new Object[vendors.Columns.Count][];
for (int i = 0; i < vendors.Columns.Count; i++)
{
data[i] = new Object[2];
data[i][0] = vendors.Columns[i].ColumnName;
data[i][1] = vendors.Rows[index].ItemArray[i];
}
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(2, 2, 1, 1);
grid.DataSource = data;
float width
= page.Canvas.ClientSize.Width
- (grid.Columns.Count + 1) * 0.75f;
grid.Columns[0].Width = width * 0.20f;
grid.Columns[1].Width = width * 0.80f;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 10f));
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Style.Font = font2;
grid.Rows[i].Cells[0].Style.BackgroundBrush = PdfBrushes.CadetBlue;
grid.Rows[i].Cells[1].Style.BackgroundBrush = PdfBrushes.SkyBlue;
}
PdfGridLayoutFormat layout = new PdfGridLayoutFormat();
layout.Break = PdfLayoutBreakType.FitPage;
layout.Layout = PdfLayoutType.Paginate;
return grid.Draw(page, new PointF(0, y), layout);
}
private static PdfLayoutResult DrawPart(PdfPageBase page, DataTable parts, int index, String title, float y)
{
//draw title
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
DataRow row = parts.Rows[index];
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y);
y = y + font1.MeasureString(title).Height + 1;
//draw table
Object[][] data = new Object[2][];
data[0] = new String[parts.Columns.Count];
for (int i = 0; i < parts.Columns.Count; i++)
{
data[0][i] = parts.Columns[i].ColumnName;
}
data[1] = row.ItemArray;
PdfTable table = new PdfTable();
table.Style.CellPadding = 2;
table.Style.BorderPen = new PdfPen(PdfBrushes.Black, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.GreenYellow;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 9f));
table.Style.HeaderSource = PdfHeaderSource.Rows;
table.Style.HeaderRowCount = 1;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.ForestGreen;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
table.DataSource = data;
float width
= page.Canvas.ClientSize.Width
- (table.Columns.Count + 1) * table.Style.BorderPen.Width;
for (int i = 0; i < table.Columns.Count; i++)
{
table.Columns[i].Width = i == 1 ? width * 0.35f : width * 0.13f;
}
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitPage;
tableLayout.Layout = PdfLayoutType.Paginate;
return table.Draw(page, new PointF(0, y), tableLayout);
}
private static PdfLayoutResult DrawOrderItems(PdfPageBase page, DataTable orderItems, String title, float y)
{
//draw title
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y);
y = y + font1.MeasureString(title).Height + 1;
PdfTable table = new PdfTable();
table.Style.CellPadding = 2;
table.Style.BorderPen = new PdfPen(PdfBrushes.Black, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.MediumTurquoise;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 8f));
table.Style.AlternateStyle = new PdfCellStyle();
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.PaleTurquoise;
table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 8f));
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Teal;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Bold));
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
table.DataSource = orderItems;
for (int i = 2; i < table.Columns.Count; i++)
{
table.Columns[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);
}
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitPage;
tableLayout.Layout = PdfLayoutType.Paginate;
return table.Draw(page, new PointF(0, y), tableLayout);
}
private static OleDbCommand PreparePartQueryCommand(OleDbConnection conn)
{
OleDbCommand command = new OleDbCommand();
command.CommandText
= " SELECT PartNo, Description, OnHand, OnOrder, Cost, ListPrice "
+ " FROM parts WHERE VendorNo = @VendorNo";
OleDbParameter param = new OleDbParameter("@VendorNo", OleDbType.Double);
command.Parameters.Add(param);
command.Connection = conn;
return command;
}
private static OleDbCommand PrepareOrderItemQueryCommand(OleDbConnection conn)
{
OleDbCommand command = new OleDbCommand();
command.CommandText
= " SELECT OrderNo, ItemNo, Qty, Discount "
+ " FROM items WHERE PartNo = @PartNo";
OleDbParameter param = new OleDbParameter("@PartNo", OleDbType.Double);
command.Parameters.Add(param);
command.Connection = conn;
return command;
}
}
}
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Actions
Imports Spire.Pdf.Bookmarks
Imports Spire.Pdf.General
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Grid
Imports Spire.Pdf.Tables
Namespace Bookmark
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
'create section
Dim section As PdfSection = doc.Sections.Add()
section.PageSettings.Size = PdfPageSize.A4
section.PageSettings.Margins = margin
' Create one page
Dim page As PdfPageBase = section.Pages.Add()
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Sales Report", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Sales Report", format1).Height
y = y + 5
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold))
Dim font3 As New PdfTrueTypeFont(New Font("Arial", 10.0F, FontStyle.Bold))
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"
conn.Open()
Dim partQueryCommand As OleDbCommand = PreparePartQueryCommand(conn)
Dim orderItemQueryCommand As OleDbCommand = PrepareOrderItemQueryCommand(conn)
Dim vendors As DataTable = GetVendors(conn)
For i As Integer = 0 To vendors.Rows.Count - 1
If i > 0 Then
'next page
page = section.Pages.Add()
y = 0
End If
'draw vendor
Dim vendorTitle As String = String.Format("{0}. {1}", i + 1, vendors.Rows(i).ItemArray(1))
Dim drawVendorLayoutResult As PdfLayoutResult = DrawVendor(page, vendors, i, vendorTitle, y)
'add vendor bookmark
Dim vendorBookmarkDest As New PdfDestination(page, New PointF(0, y))
Dim vendorBookmark As PdfBookmark = doc.Bookmarks.Add(vendorTitle)
vendorBookmark.Color = Color.SaddleBrown
vendorBookmark.DisplayStyle = PdfTextStyle.Bold
vendorBookmark.Action = New PdfGoToAction(vendorBookmarkDest)
y = drawVendorLayoutResult.Bounds.Bottom + 5
page = drawVendorLayoutResult.Page
'get parts of vendor
Dim parts As DataTable = GetParts(partQueryCommand, CDbl(vendors.Rows(i).ItemArray(0)))
For j As Integer = 0 To parts.Rows.Count - 1
If j > 0 Then
'next page
page = section.Pages.Add()
y = 0
End If
'draw part
Dim partTitle As String _
= String.Format("{0}.{1}. {2}", i + 1, j + 1, parts.Rows(j).ItemArray(1))
Dim drawPartLayoutResult As PdfLayoutResult = DrawPart(page, parts, j, partTitle, y)
'add part bookmark
Dim partBookmarkDest As New PdfDestination(page, New PointF(0, y))
Dim partBookmark As PdfBookmark = vendorBookmark.Add(partTitle)
partBookmark.Color = Color.Coral
partBookmark.DisplayStyle = PdfTextStyle.Italic
partBookmark.Action = New PdfGoToAction(partBookmarkDest)
y = drawPartLayoutResult.Bounds.Bottom + 5
page = drawPartLayoutResult.Page
'get order items
Dim orderItemsTitle As String _
= String.Format("{0} - Order Items", parts.Rows(j).ItemArray(1))
Dim orderItems As DataTable _
= GetOrderItems(orderItemQueryCommand, CDbl(parts.Rows(j).ItemArray(0)))
DrawOrderItems(page, orderItems, orderItemsTitle, y)
Next j
Next i
End Using
'Save pdf file.
doc.SaveToFile("Bookmark.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("Bookmark.pdf")
End Sub
Private Shared Function GetVendors(ByVal conn As OleDbConnection) As DataTable
Dim query As String _
= " SELECT VendorNo, VendorName, Address1, City, State, Zip, Country, Phone, FAX " _
& " FROM vendors "
Using adapter As New OleDbDataAdapter(query, conn)
Dim dataTable As New DataTable()
adapter.Fill(dataTable)
Return dataTable
End Using
End Function
Private Shared Function GetParts(ByVal query As OleDbCommand, ByVal vendorId As Double) As DataTable
query.Parameters(0).Value = vendorId
Using adapter As New OleDbDataAdapter(query)
Dim dataTable As New DataTable()
adapter.Fill(dataTable)
Return dataTable
End Using
End Function
Private Shared Function GetOrderItems(ByVal query As OleDbCommand, ByVal partId As Double) As DataTable
query.Parameters(0).Value = partId
Using adapter As New OleDbDataAdapter(query)
Dim dataTable As New DataTable()
adapter.Fill(dataTable)
Return dataTable
End Using
End Function
Private Shared Function DrawVendor(ByVal page As PdfPageBase, ByVal vendors As DataTable, _
ByVal index As Integer, ByVal title As String, ByVal y As Single) As PdfLayoutResult
'draw title
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold))
Dim row As DataRow = vendors.Rows(index)
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y)
y = y + font1.MeasureString(title).Height + 1
'draw table
Dim data(vendors.Columns.Count - 1)() As Object
For i As Integer = 0 To vendors.Columns.Count - 1
data(i) = New Object(1) {}
data(i)(0) = vendors.Columns(i).ColumnName
data(i)(1) = vendors.Rows(index).ItemArray(i)
Next i
Dim grid As New PdfGrid()
grid.Style.CellPadding = New PdfPaddings(2, 2, 1, 1)
grid.DataSource = data
Dim width As Single = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1) * 0.75F
grid.Columns(0).Width = width * 0.2F
grid.Columns(1).Width = width * 0.8F
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 10.0F, FontStyle.Bold))
Dim font3 As New PdfTrueTypeFont(New Font("Arial", 10.0F))
For i As Integer = 0 To grid.Rows.Count - 1
grid.Rows(i).Style.Font = font2
grid.Rows(i).Cells(0).Style.BackgroundBrush = PdfBrushes.CadetBlue
grid.Rows(i).Cells(1).Style.BackgroundBrush = PdfBrushes.SkyBlue
Next i
Dim layout As New PdfGridLayoutFormat()
layout.Break = PdfLayoutBreakType.FitPage
layout.Layout = PdfLayoutType.Paginate
Return grid.Draw(page, New PointF(0, y), layout)
End Function
Private Shared Function DrawPart(ByVal page As PdfPageBase, ByVal parts As DataTable, ByVal index As Integer, _
ByVal title As String, ByVal y As Single) As PdfLayoutResult
'draw title
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 10.0F, FontStyle.Bold))
Dim row As DataRow = parts.Rows(index)
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y)
y = y + font1.MeasureString(title).Height + 1
'draw table
Dim data(1)() As Object
data(0) = New String(parts.Columns.Count - 1) {}
For i As Integer = 0 To parts.Columns.Count - 1
data(0)(i) = parts.Columns(i).ColumnName
Next i
data(1) = row.ItemArray
Dim table As New PdfTable()
table.Style.CellPadding = 2
table.Style.BorderPen = New PdfPen(PdfBrushes.Black, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.GreenYellow
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 9.0F))
table.Style.HeaderSource = PdfHeaderSource.Rows
table.Style.HeaderRowCount = 1
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.ForestGreen
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Bold))
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
table.DataSource = data
Dim width As Single _
= page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
For i As Integer = 0 To table.Columns.Count - 1
table.Columns(i).Width = If(i = 1, width * 0.35F, width * 0.13F)
Next i
Dim tableLayout As New PdfTableLayoutFormat()
tableLayout.Break = PdfLayoutBreakType.FitPage
tableLayout.Layout = PdfLayoutType.Paginate
Return table.Draw(page, New PointF(0, y), tableLayout)
End Function
Private Shared Function DrawOrderItems(ByVal page As PdfPageBase, ByVal orderItems As DataTable, _
ByVal title As String, ByVal y As Single) As PdfLayoutResult
'draw title
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Bold))
page.Canvas.DrawString(title, font1, PdfBrushes.Black, 0, y)
y = y + font1.MeasureString(title).Height + 1
Dim table As New PdfTable()
table.Style.CellPadding = 2
table.Style.BorderPen = New PdfPen(PdfBrushes.Black, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.MediumTurquoise
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 8.0F))
table.Style.AlternateStyle = New PdfCellStyle()
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.PaleTurquoise
table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Arial", 8.0F))
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Teal
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 8.0F, FontStyle.Bold))
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
table.DataSource = orderItems
For i As Integer = 2 To table.Columns.Count - 1
table.Columns(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Right)
Next i
Dim tableLayout As New PdfTableLayoutFormat()
tableLayout.Break = PdfLayoutBreakType.FitPage
tableLayout.Layout = PdfLayoutType.Paginate
Return table.Draw(page, New PointF(0, y), tableLayout)
End Function
Private Shared Function PreparePartQueryCommand(ByVal conn As OleDbConnection) As OleDbCommand
Dim command As New OleDbCommand()
command.CommandText _
= " SELECT PartNo, Description, OnHand, OnOrder, Cost, ListPrice " _
& " FROM parts WHERE VendorNo = @VendorNo"
Dim param As New OleDbParameter("@VendorNo", OleDbType.Double)
command.Parameters.Add(param)
command.Connection = conn
Return command
End Function
Private Shared Function PrepareOrderItemQueryCommand(ByVal conn As OleDbConnection) As OleDbCommand
Dim command As New OleDbCommand()
command.CommandText _
= " SELECT OrderNo, ItemNo, Qty, Discount " _
& " FROM items WHERE PartNo = @PartNo"
Dim param As New OleDbParameter("@PartNo", OleDbType.Double)
command.Parameters.Add(param)
command.Connection = conn
Return command
End Function
End Class
End Namespace
Wednesday, 06 April 2011 09:07
PDF Attachment in C#, VB.NET
The sample demonstrates how to work with attachment and attachment annotation in PDF document.

using System;
using System.Drawing;
using System.IO;
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Attachments;
using Spire.Pdf.Graphics;
namespace Attachment
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
//create section
PdfSection section = doc.Sections.Add();
section.PageSettings.Size = PdfPageSize.A4;
section.PageSettings.Margins = margin;
// Create one page
PdfPageBase page = section.Pages.Add();
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Attachment", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Attachment", format1).Height;
y = y + 5;
//attachment
PdfAttachment attachment = new PdfAttachment("Header.png");
attachment.Data = File.ReadAllBytes(@"Header.png");
attachment.Description = "Page header picture of demo.";
attachment.MimeType = "image/png";
doc.Attachments.Add(attachment);
attachment = new PdfAttachment("Footer.png");
attachment.Data = File.ReadAllBytes(@"Footer.png");
attachment.Description = "Page footer picture of demo.";
attachment.MimeType = "image/png";
doc.Attachments.Add(attachment);
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Bold));
PointF location = new PointF(0, y);
String label = "Sales Report Chart";
byte[] data = File.ReadAllBytes(@"SalesReportChart.png");
SizeF size = font2.MeasureString(label);
RectangleF bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation1
= new PdfAttachmentAnnotation(bounds, "SalesReportChart.png", data);
annotation1.Color = Color.Teal;
annotation1.Flags = PdfAnnotationFlags.ReadOnly;
annotation1.Icon = PdfAttachmentIcon.Graph;
annotation1.Text = "Sales Report Chart";
(page as PdfNewPage).Annotations.Add(annotation1);
y = y + size.Height + 2;
location = new PointF(0, y);
label = "Science Personification Boston";
data = File.ReadAllBytes(@"SciencePersonificationBoston.jpg");
size = font2.MeasureString(label);
bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation2
= new PdfAttachmentAnnotation(bounds, "SciencePersonificationBoston.jpg", data);
annotation2.Color = Color.Orange;
annotation2.Flags = PdfAnnotationFlags.NoZoom;
annotation2.Icon = PdfAttachmentIcon.PushPin;
annotation2.Text = "SciencePersonificationBoston.jpg, from Wikipedia, the free encyclopedia";
(page as PdfNewPage).Annotations.Add(annotation2);
y = y + size.Height + 2;
location = new PointF(0, y);
label = "Picture of Science";
data = File.ReadAllBytes(@"Wikipedia_Science.png");
size = font2.MeasureString(label);
bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation3
= new PdfAttachmentAnnotation(bounds, "Wikipedia_Science.png", data);
annotation3.Color = Color.SaddleBrown;
annotation3.Flags = PdfAnnotationFlags.Locked;
annotation3.Icon = PdfAttachmentIcon.Tag;
annotation3.Text = "Wikipedia_Science.png, from Wikipedia, the free encyclopedia";
(page as PdfNewPage).Annotations.Add(annotation3);
y = y + size.Height + 2;
location = new PointF(0, y);
label = "Hawaii Killer Font";
data = File.ReadAllBytes(@"Hawaii_Killer.ttf");
size = font2.MeasureString(label);
bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation4
= new PdfAttachmentAnnotation(bounds, "Hawaii_Killer.ttf", data);
annotation4.Color = Color.CadetBlue;
annotation4.Flags = PdfAnnotationFlags.NoRotate;
annotation4.Icon = PdfAttachmentIcon.Paperclip;
annotation4.Text = "Hawaii Killer Font, from http://www.1001freefonts.com";
(page as PdfNewPage).Annotations.Add(annotation4);
y = y + size.Height + 2;
//Save pdf file.
doc.SaveToFile("Attachment.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("Attachment.pdf");
}
}
}
Imports System.Drawing
Imports System.IO
Imports Spire.Pdf
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.Attachments
Imports Spire.Pdf.Graphics
Namespace Attachment
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
'create section
Dim section As PdfSection = doc.Sections.Add()
section.PageSettings.Size = PdfPageSize.A4
section.PageSettings.Margins = margin
' Create one page
Dim page As PdfPageBase = section.Pages.Add()
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Attachment", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Attachment", format1).Height
y = y + 5
'attachment
Dim attachment As New PdfAttachment("Header.png")
attachment.Data = File.ReadAllBytes("Header.png")
attachment.Description = "Page header picture of demo."
attachment.MimeType = "image/png"
doc.Attachments.Add(attachment)
attachment = New PdfAttachment("Footer.png")
attachment.Data = File.ReadAllBytes("Footer.png")
attachment.Description = "Page footer picture of demo."
attachment.MimeType = "image/png"
doc.Attachments.Add(attachment)
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 12.0F, FontStyle.Bold))
Dim location As New PointF(0, y)
Dim label As String = "Sales Report Chart"
Dim data() As Byte = File.ReadAllBytes("SalesReportChart.png")
Dim size As SizeF = font2.MeasureString(label)
Dim bounds As New RectangleF(location, size)
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds)
bounds = New RectangleF(bounds.Right + 3, bounds.Top, font2.Height \ 2, font2.Height)
Dim annotation1 As New PdfAttachmentAnnotation(bounds, "SalesReportChart.png", data)
annotation1.Color = Color.Teal
annotation1.Flags = PdfAnnotationFlags.ReadOnly
annotation1.Icon = PdfAttachmentIcon.Graph
annotation1.Text = "Sales Report Chart"
TryCast(page, PdfNewPage).Annotations.Add(annotation1)
y = y + size.Height + 2
location = New PointF(0, y)
label = "Science Personification Boston"
data = File.ReadAllBytes("SciencePersonificationBoston.jpg")
size = font2.MeasureString(label)
bounds = New RectangleF(location, size)
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds)
bounds = New RectangleF(bounds.Right + 3, bounds.Top, font2.Height \ 2, font2.Height)
Dim annotation2 As New PdfAttachmentAnnotation(bounds, "SciencePersonificationBoston.jpg", data)
annotation2.Color = Color.Orange
annotation2.Flags = PdfAnnotationFlags.NoZoom
annotation2.Icon = PdfAttachmentIcon.PushPin
annotation2.Text = "SciencePersonificationBoston.jpg, from Wikipedia, the free encyclopedia"
TryCast(page, PdfNewPage).Annotations.Add(annotation2)
y = y + size.Height + 2
location = New PointF(0, y)
label = "Picture of Science"
data = File.ReadAllBytes("Wikipedia_Science.png")
size = font2.MeasureString(label)
bounds = New RectangleF(location, size)
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds)
bounds = New RectangleF(bounds.Right + 3, bounds.Top, font2.Height \ 2, font2.Height)
Dim annotation3 As New PdfAttachmentAnnotation(bounds, "Wikipedia_Science.png", data)
annotation3.Color = Color.SaddleBrown
annotation3.Flags = PdfAnnotationFlags.Locked
annotation3.Icon = PdfAttachmentIcon.Tag
annotation3.Text = "Wikipedia_Science.png, from Wikipedia, the free encyclopedia"
TryCast(page, PdfNewPage).Annotations.Add(annotation3)
y = y + size.Height + 2
location = New PointF(0, y)
label = "Hawaii Killer Font"
data = File.ReadAllBytes("Hawaii_Killer.ttf")
size = font2.MeasureString(label)
bounds = New RectangleF(location, size)
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds)
bounds = New RectangleF(bounds.Right + 3, bounds.Top, font2.Height \ 2, font2.Height)
Dim annotation4 As New PdfAttachmentAnnotation(bounds, "Hawaii_Killer.ttf", data)
annotation4.Color = Color.CadetBlue
annotation4.Flags = PdfAnnotationFlags.NoRotate
annotation4.Icon = PdfAttachmentIcon.Paperclip
annotation4.Text = "Hawaii Killer Font, from http://www.1001freefonts.com"
TryCast(page, PdfNewPage).Annotations.Add(annotation4)
y = y + size.Height + 2
'Save pdf file.
doc.SaveToFile("Attachment.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("Attachment.pdf")
End Sub
End Class
End Namespace
Published in
Interaction
Tagged under
Wednesday, 06 April 2011 09:02
PDF ActionChain in C#, VB.NET
The sample demonstrates how to work with action, javascript action, page destination action and action annotation in PDF document.

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Actions;
using Spire.Pdf.General;
using Spire.Pdf.Tables;
using System.Data.OleDb;
using System.Data;
namespace ActionChain
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//Draw pages
PdfPageBase lastPage = DrawPages(doc);
//script
String script
= "app.alert({"
+ " cMsg: \"I'll lead; you must follow me.\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
PdfJavaScriptAction action1 = new PdfJavaScriptAction(script);
doc.AfterOpenAction = action1;
//script
script
= "app.alert({"
+ " cMsg: \"The firt page!\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
PdfJavaScriptAction action2 = new PdfJavaScriptAction(script);
action1.NextAction = action2;
PdfDestination dest = new PdfDestination(lastPage);
dest.Zoom = 1;
PdfGoToAction action3 = new PdfGoToAction(dest);
action2.NextAction = action3;
//script
script
= "app.alert({"
+ " cMsg: \"Oh sorry, it's the last page. I'm missing!\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
PdfJavaScriptAction action4 = new PdfJavaScriptAction(script);
action3.NextAction = action4;
//Save pdf file.
doc.SaveToFile("ActionChain.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("ActionChain.pdf");
}
private static PdfPageBase DrawPages(PdfDocument doc)
{
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Part List", format1).Height;
y = y + 5;
//create data table
PdfTable table = new PdfTable();
table.Style.CellPadding = 2;
table.Style.BorderPen = new PdfPen(brush1, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
table.Style.AlternateStyle = new PdfCellStyle();
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow;
table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText
= " select Description, OnHand, OnOrder, Cost, ListPrice from parts ";
command.Connection = conn;
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
table.DataSourceType = PdfTableDataSourceType.TableDirect;
table.DataSource = dataTable;
}
}
float width
= page.Canvas.ClientSize.Width
- (table.Columns.Count + 1) * table.Style.BorderPen.Width;
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 0)
{
table.Columns[i].Width = width * 0.40f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
}
else
{
table.Columns[i].Width = width * 0.15f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
}
}
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitElement;
tableLayout.Layout = PdfLayoutType.Paginate;
PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout);
y = result.Bounds.Bottom + 3;
PdfBrush brush2 = PdfBrushes.Gray;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
result.Page.Canvas.DrawString(String.Format("* {0} parts in the list.", table.Rows.Count),
font2, brush2, 5, y);
return result.Page;
}
}
}
Imports System.Data.OleDb
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Actions
Imports Spire.Pdf.General
Imports Spire.Pdf.Tables
Namespace ActionChain
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'Draw pages
Dim lastPage As PdfPageBase = DrawPages(doc)
'script
Dim script As String _
= "app.alert({" _
& " cMsg: ""I'll lead; you must follow me.""," _
& " nIcon: 3," _
& " cTitle: ""JavaScript Action""" _
& "});"
Dim action1 As New PdfJavaScriptAction(script)
doc.AfterOpenAction = action1
'script
script _
= "app.alert({" _
& " cMsg: ""The firt page!""," _
& " nIcon: 3," _
& " cTitle: ""JavaScript Action""" _
& "});"
Dim action2 As New PdfJavaScriptAction(script)
action1.NextAction = action2
Dim dest As New PdfDestination(lastPage)
dest.Zoom = 1
Dim action3 As New PdfGoToAction(dest)
action2.NextAction = action3
'script
script _
= "app.alert({" _
& " cMsg: ""Oh sorry, it's the last page. I'm missing!""," _
& " nIcon: 3," _
& " cTitle: ""JavaScript Action""" _
& "});"
Dim action4 As New PdfJavaScriptAction(script)
action3.NextAction = action4
'Save pdf file.
doc.SaveToFile("ActionChain.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("ActionChain.pdf")
End Sub
Private Shared Function DrawPages(ByVal doc As PdfDocument) As PdfPageBase
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Part List", format1).Height
y = y + 5
'create data table
Dim table As New PdfTable()
table.Style.CellPadding = 2
table.Style.BorderPen = New PdfPen(brush1, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F))
table.Style.AlternateStyle = New PdfCellStyle()
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow
table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F))
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold))
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"
Dim command As New OleDbCommand()
command.CommandText = " select Description, OnHand, OnOrder, Cost, ListPrice from parts "
command.Connection = conn
Using dataAdapter As New OleDbDataAdapter(command)
Dim dataTable As New DataTable()
dataAdapter.Fill(dataTable)
table.DataSourceType = PdfTableDataSourceType.TableDirect
table.DataSource = dataTable
End Using
End Using
Dim width As Single _
= page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
For i As Integer = 0 To table.Columns.Count - 1
If i = 0 Then
table.Columns(i).Width = width * 0.4F * width
table.Columns(i).StringFormat _
= New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
Else
table.Columns(i).Width = width * 0.15F * width
table.Columns(i).StringFormat _
= New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
End If
Next i
Dim tableLayout As New PdfTableLayoutFormat()
tableLayout.Break = PdfLayoutBreakType.FitElement
tableLayout.Layout = PdfLayoutType.Paginate
Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y), tableLayout)
y = result.Bounds.Bottom + 3
Dim brush2 As PdfBrush = PdfBrushes.Gray
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9.0F))
result.Page.Canvas.DrawString(String.Format("* {0} parts in the list.", table.Rows.Count), _
font2, brush2, 5, y)
Return result.Page
End Function
End Class
End Namespace
Published in
Interaction
Wednesday, 06 April 2011 08:55
PDF Action in C#, VB.NET
The sample demonstrates how to work with action, javascript action, page destination action and action annotation in PDF document.

using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
namespace Action
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Part List", format1).Height;
y = y + 2;
//table top
PdfDestination tableTopDest = new PdfDestination(page);
tableTopDest.Location = new PointF(0, y);
tableTopDest.Mode = PdfDestinationMode.Location;
tableTopDest.Zoom = 1f;
//Draw table
PdfTrueTypeFont buttonFont = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
float buttonWidth = 70;
float buttonHeight = buttonFont.Height * 1.5f;
float tableTop = y;
PdfLayoutResult tableLayoutResult = DrawTable(page, y + buttonHeight + 5);
//table bottom
PdfDestination tableBottomDest = new PdfDestination(tableLayoutResult.Page);
tableBottomDest.Location = new PointF(0, tableLayoutResult.Bounds.Bottom);
tableBottomDest.Mode = PdfDestinationMode.Location;
tableBottomDest.Zoom = 1f;
//go to table bottom
float x = page.Canvas.ClientSize.Width - buttonWidth;
PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
RectangleF buttonBounds = new RectangleF(x, tableTop, buttonWidth, buttonHeight);
page.Canvas.DrawRectangle(PdfBrushes.DarkGray, buttonBounds);
page.Canvas.DrawString("To Bottom", buttonFont, PdfBrushes.CadetBlue, buttonBounds, format2);
PdfGoToAction action1 = new PdfGoToAction(tableBottomDest);
PdfActionAnnotation annotation1
= new PdfActionAnnotation(buttonBounds, action1);
annotation1.Border = new PdfAnnotationBorder(0.75f);
annotation1.Color = Color.LightGray;
(page as PdfNewPage).Annotations.Add(annotation1);
//go to table top
float tableBottom = tableLayoutResult.Bounds.Bottom + 5;
buttonBounds = new RectangleF(x, tableBottom, buttonWidth, buttonHeight);
tableLayoutResult.Page.Canvas.DrawRectangle(PdfBrushes.DarkGray, buttonBounds);
tableLayoutResult.Page.Canvas.DrawString("To Top", buttonFont, PdfBrushes.CadetBlue, buttonBounds, format2);
PdfGoToAction action2 = new PdfGoToAction(tableTopDest);
PdfActionAnnotation annotation2
= new PdfActionAnnotation(buttonBounds, action2);
annotation2.Border = new PdfAnnotationBorder(0.75f);
annotation2.Color = Color.LightGray;
(tableLayoutResult.Page as PdfNewPage).Annotations.Add(annotation2);
//goto last page
PdfNamedAction action3 = new PdfNamedAction(PdfActionDestination.LastPage);
doc.AfterOpenAction = action3;
//script
String script
= "app.alert({"
+ " cMsg: \"Oh no, you want to leave me.\","
+ " nIcon: 3,"
+ " cTitle: \"JavaScript Action\""
+ "});";
PdfJavaScriptAction action4 = new PdfJavaScriptAction(script);
doc.BeforeCloseAction = action4;
//Save pdf file.
doc.SaveToFile("Action.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("Action.pdf");
}
private static PdfLayoutResult DrawTable(PdfPageBase page, float y)
{
PdfBrush brush1 = PdfBrushes.Black;
//create data table
PdfTable table = new PdfTable();
table.Style.CellPadding = 2;
table.Style.BorderPen = new PdfPen(brush1, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
table.Style.AlternateStyle = new PdfCellStyle();
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow;
table.Style.AlternateStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText
= " select Description, OnHand, OnOrder, Cost, ListPrice from parts ";
command.Connection = conn;
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
table.DataSourceType = PdfTableDataSourceType.TableDirect;
table.DataSource = dataTable;
}
}
float width
= page.Canvas.ClientSize.Width
- (table.Columns.Count + 1) * table.Style.BorderPen.Width;
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 0)
{
table.Columns[i].Width = width * 0.40f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
}
else
{
table.Columns[i].Width = width * 0.15f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
}
}
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitElement;
tableLayout.Layout = PdfLayoutType.Paginate;
PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout);
y = result.Bounds.Bottom + 3;
PdfBrush brush2 = PdfBrushes.Gray;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
result.Page.Canvas.DrawString(String.Format("* {0} parts in the list.", table.Rows.Count),
font2, brush2, 5, y);
return result;
}
}
}
Imports System.Data
Imports System.Data.OleDb
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Actions
Imports Spire.Pdf.Annotations
Imports Spire.Pdf.General
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Namespace Action
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Part List", format1).Height
y = y + 2
'table top
Dim tableTopDest As New PdfDestination(page)
tableTopDest.Location = New PointF(0, y)
tableTopDest.Mode = PdfDestinationMode.Location
tableTopDest.Zoom = 1.0F
'Draw table
Dim buttonFont As New PdfTrueTypeFont(New Font("Arial", 10.0F, FontStyle.Bold))
Dim buttonWidth As Single = 70
Dim buttonHeight As Single = buttonFont.Height * 1.5F
Dim tableTop As Single = y
Dim tableLayoutResult As PdfLayoutResult = DrawTable(page, y + buttonHeight + 5)
'table bottom
Dim tableBottomDest As New PdfDestination(tableLayoutResult.Page)
tableBottomDest.Location = New PointF(0, tableLayoutResult.Bounds.Bottom)
tableBottomDest.Mode = PdfDestinationMode.Location
tableBottomDest.Zoom = 1.0F
'go to table bottom
Dim x As Single = page.Canvas.ClientSize.Width - buttonWidth
Dim format2 As New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
Dim buttonBounds As New RectangleF(x, tableTop, buttonWidth, buttonHeight)
page.Canvas.DrawRectangle(PdfBrushes.DarkGray, buttonBounds)
page.Canvas.DrawString("To Bottom", buttonFont, PdfBrushes.CadetBlue, buttonBounds, format2)
Dim action1 As New PdfGoToAction(tableBottomDest)
Dim annotation1 As New PdfActionAnnotation(buttonBounds, action1)
annotation1.Border = New PdfAnnotationBorder(0.75F)
annotation1.Color = Color.LightGray
TryCast(page, PdfNewPage).Annotations.Add(annotation1)
'go to table top
Dim tableBottom As Single = tableLayoutResult.Bounds.Bottom + 5
buttonBounds = New RectangleF(x, tableBottom, buttonWidth, buttonHeight)
tableLayoutResult.Page.Canvas.DrawRectangle(PdfBrushes.DarkGray, buttonBounds)
tableLayoutResult.Page.Canvas.DrawString("To Top", buttonFont, _
PdfBrushes.CadetBlue, buttonBounds, format2)
Dim action2 As New PdfGoToAction(tableTopDest)
Dim annotation2 As New PdfActionAnnotation(buttonBounds, action2)
annotation2.Border = New PdfAnnotationBorder(0.75F)
annotation2.Color = Color.LightGray
TryCast(tableLayoutResult.Page, PdfNewPage).Annotations.Add(annotation2)
'goto last page
Dim action3 As New PdfNamedAction(PdfActionDestination.LastPage)
doc.AfterOpenAction = action3
'script
Dim script As String _
= "app.alert({" & " cMsg: ""Oh no, you want to leave me.""," _
& " nIcon: 3," & " cTitle: ""JavaScript Action""" & "});"
Dim action4 As New PdfJavaScriptAction(script)
doc.BeforeCloseAction = action4
'Save pdf file.
doc.SaveToFile("Action.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("Action.pdf")
End Sub
Private Shared Function DrawTable(ByVal page As PdfPageBase, ByVal y As Single) As PdfLayoutResult
Dim brush1 As PdfBrush = PdfBrushes.Black
'create data table
Dim table As New PdfTable()
table.Style.CellPadding = 2
table.Style.BorderPen = New PdfPen(brush1, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F))
table.Style.AlternateStyle = New PdfCellStyle()
table.Style.AlternateStyle.BackgroundBrush = PdfBrushes.LightYellow
table.Style.AlternateStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F))
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold))
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"
Dim command As New OleDbCommand()
command.CommandText = " select Description, OnHand, OnOrder, Cost, ListPrice from parts "
command.Connection = conn
Using dataAdapter As New OleDbDataAdapter(command)
Dim dataTable As New DataTable()
dataAdapter.Fill(dataTable)
table.DataSourceType = PdfTableDataSourceType.TableDirect
table.DataSource = dataTable
End Using
End Using
Dim width As Single _
= page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
For i As Integer = 0 To table.Columns.Count - 1
If i = 0 Then
table.Columns(i).Width = width * 0.4F * width
table.Columns(i).StringFormat _
= New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
Else
table.Columns(i).Width = width * 0.15F * width
table.Columns(i).StringFormat _
= New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
End If
Next i
Dim tableLayout As New PdfTableLayoutFormat()
tableLayout.Break = PdfLayoutBreakType.FitElement
tableLayout.Layout = PdfLayoutType.Paginate
Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y), tableLayout)
y = result.Bounds.Bottom + 3
Dim brush2 As PdfBrush = PdfBrushes.Gray
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9.0F))
result.Page.Canvas.DrawString(String.Format("* {0} parts in the list.", _
table.Rows.Count), font2, brush2, 5, y)
Return result
End Function
End Class
End Namespace
Published in
Interaction
Tagged under
Wednesday, 06 April 2011 08:52
PDF List in C#, VB.NET
The sample demonstrates how to work with ordered list, multiple levels list and set list style.

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;
using System.Data.OleDb;
namespace List
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Categories List", format1).Height;
y = y + 5;
RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize);
PdfLinearGradientBrush brush2
= new PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical);
PdfLinearGradientBrush brush3
= new PdfLinearGradientBrush(rctg, Color.OrangeRed, Color.Navy, PdfLinearGradientMode.Vertical);
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 10f), true);
PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 8f), true);
PdfOrderedMarker marker1
= new PdfOrderedMarker(PdfNumberStyle.LowerRoman, new PdfFont(PdfFontFamily.Helvetica, 10f));
PdfOrderedMarker marker2
= new PdfOrderedMarker(PdfNumberStyle.Numeric, new PdfFont(PdfFontFamily.Helvetica, 8f));
PdfSortedList vendorList = new PdfSortedList(font2);
vendorList.Indent = 0;
vendorList.TextIndent = 5;
vendorList.Brush = brush2;
vendorList.Marker = marker1;
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText
= " select VendorNo, VendorName from vendors ";
command.Connection = conn;
OleDbCommand command2 = new OleDbCommand();
command2.CommandText
= " select Description from parts where VendorNo = @VendorNo";
command2.Connection = conn;
OleDbParameter param = new OleDbParameter("@VendorNo", OleDbType.Double);
command2.Parameters.Add(param);
conn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
double id = reader.GetDouble(0);
PdfListItem item = vendorList.Items.Add(reader.GetString(1));
PdfSortedList subList = new PdfSortedList(font3);
subList.Marker = marker2;
subList.Brush = brush3;
item.SubList = subList;
subList.TextIndent = 20;
command2.Parameters[0].Value = id;
using (OleDbDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
subList.Items.Add(reader2.GetString(0));
}
}
String maxNumberLabel = Convert.ToString(subList.Items.Count);
subList.Indent = 30 - font3.MeasureString(maxNumberLabel).Width;
}
}
PdfTextLayout textLayout = new PdfTextLayout();
textLayout.Break = PdfLayoutBreakType.FitPage;
textLayout.Layout = PdfLayoutType.Paginate;
vendorList.Draw(page, new PointF(0, y), textLayout);
//Save pdf file.
doc.SaveToFile("List.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("List.pdf");
}
}
}
Imports System.Data.OleDb
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Lists
Namespace List
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold), True)
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Categories List", format1).Height
y = y + 5
Dim rctg As New RectangleF(New PointF(0, 0), page.Canvas.ClientSize)
Dim brush2 As New PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical)
Dim brush3 As New PdfLinearGradientBrush(rctg, Color.OrangeRed, Color.Navy, PdfLinearGradientMode.Vertical)
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 10.0F), True)
Dim font3 As New PdfTrueTypeFont(New Font("Arial", 8.0F), True)
Dim marker1 As New PdfOrderedMarker(PdfNumberStyle.LowerRoman, New PdfFont(PdfFontFamily.Helvetica, 10.0F))
Dim marker2 As New PdfOrderedMarker(PdfNumberStyle.Numeric, New PdfFont(PdfFontFamily.Helvetica, 8.0F))
Dim vendorList As New PdfSortedList(font2)
vendorList.Indent = 0
vendorList.TextIndent = 5
vendorList.Brush = brush2
vendorList.Marker = marker1
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"
Dim command As New OleDbCommand()
command.CommandText = " select VendorNo, VendorName from vendors "
command.Connection = conn
Dim command2 As New OleDbCommand()
command2.CommandText = " select Description from parts where VendorNo = @VendorNo"
command2.Connection = conn
Dim param As New OleDbParameter("@VendorNo", OleDbType.Double)
command2.Parameters.Add(param)
conn.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
Do While reader.Read()
Dim id As Double = reader.GetDouble(0)
Dim item As PdfListItem = vendorList.Items.Add(reader.GetString(1))
Dim subList As New PdfSortedList(font3)
subList.Marker = marker2
subList.Brush = brush3
item.SubList = subList
subList.TextIndent = 20
command2.Parameters(0).Value = id
Using reader2 As OleDbDataReader = command2.ExecuteReader()
Do While reader2.Read()
subList.Items.Add(reader2.GetString(0))
Loop
End Using
Dim maxNumberLabel As String = Convert.ToString(subList.Items.Count)
subList.Indent = 30 - font3.MeasureString(maxNumberLabel).Width
Loop
End Using
Dim textLayout As New PdfTextLayout()
textLayout.Break = PdfLayoutBreakType.FitPage
textLayout.Layout = PdfLayoutType.Paginate
vendorList.Draw(page, New PointF(0, y), textLayout)
'Save pdf file.
doc.SaveToFile("List.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("List.pdf")
End Sub
End Class
End Namespace
Wednesday, 06 April 2011 08:17
PDF SimpleList in C#, VB.NET
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;
namespace SimpleList
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Categories List", format1).Height;
y = y + 5;
RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize);
PdfLinearGradientBrush brush
= new PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical);
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
String formatted
= "Beverages\nCondiments\nConfections\nDairy Products\nGrains/Cereals\nMeat/Poultry\nProduce\nSeafood";
PdfList list = new PdfList(formatted);
list.Font = font;
list.Indent = 8;
list.TextIndent = 5;
list.Brush = brush;
PdfLayoutResult result = list.Draw(page, 0, y);
y = result.Bounds.Bottom;
PdfSortedList sortedList = new PdfSortedList(formatted);
sortedList.Font = font;
sortedList.Indent = 8;
sortedList.TextIndent = 5;
sortedList.Brush = brush;
sortedList.Draw(page, 0, y);
//Save pdf file.
doc.SaveToFile("SimpleList.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("SimpleList.pdf");
}
}
}
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Lists
Namespace SimpleList
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold), True)
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Categories List", format1).Height
y = y + 5
Dim rctg As New RectangleF(New PointF(0, 0), page.Canvas.ClientSize)
Dim brush As New PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical)
Dim font As New PdfFont(PdfFontFamily.Helvetica, 12.0F, PdfFontStyle.Bold)
Dim formatted As String = "Beverages" & vbLf & "Condiments" & vbLf & "Confections" _
& vbLf & "Dairy Products" & vbLf & "Grains/Cereals" & vbLf & "Meat/Poultry" & _
vbLf & "Produce" & vbLf & "Seafood"
Dim list As New PdfList(formatted)
list.Font = font
list.Indent = 8
list.TextIndent = 5
list.Brush = brush
Dim result As PdfLayoutResult = list.Draw(page, 0, y)
y = result.Bounds.Bottom
Dim sortedList As New PdfSortedList(formatted)
sortedList.Font = font
sortedList.Indent = 8
sortedList.TextIndent = 5
sortedList.Brush = brush
sortedList.Draw(page, 0, y)
'Save pdf file.
doc.SaveToFile("SimpleList.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("SimpleList.pdf")
End Sub
End Class
End Namespace
Wednesday, 06 April 2011 06:56
PDF ImageWaterMark in C#, VB.NET
The sample demonstrates how to draw an image as watermark in PDF document.

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace ImageWaterMark
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
Image img = Image.FromFile(@"Background.png");
page.BackgroundImage = img;
//Draw page
DrawPage(page);
//Save pdf file.
doc.SaveToFile("ImageWaterMark.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("ImageWaterMark.pdf");
}
private static void DrawPage(PdfPageBase page)
{
float pageWidth = page.Canvas.ClientSize.Width;
float y = 0;
//page header
PdfPen pen1 = new PdfPen(Color.LightGray, 1f);
PdfBrush brush1 = new PdfSolidBrush(Color.LightGray);
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Italic));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Right);
String text = "Demo of Spire.Pdf";
page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1);
SizeF size = font1.MeasureString(text, format1);
y = y + size.Height + 1;
page.Canvas.DrawLine(pen1, 0, y, pageWidth, y);
//title
y = y + 5;
PdfBrush brush2 = new PdfSolidBrush(Color.Black);
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center);
format2.CharacterSpacing = 1f;
text = "Summary of Science";
page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2);
size = font2.MeasureString(text, format2);
y = y + size.Height + 6;
//icon
PdfImage image = PdfImage.FromFile(@"Wikipedia_Science.png");
page.Canvas.DrawImage(image, new PointF(pageWidth - image.PhysicalDimension.Width, y));
float imageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2;
float imageBottom = image.PhysicalDimension.Height + y;
//refenrence content
PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 9f));
PdfStringFormat format3 = new PdfStringFormat();
format3.ParagraphIndent = font3.Size * 2;
format3.MeasureTrailingSpaces = true;
format3.LineSpacing = font3.Size * 1.5f;
String text1 = "(All text and picture from ";
String text2 = "Wikipedia";
String text3 = ", the free encyclopedia)";
page.Canvas.DrawString(text1, font3, brush2, 0, y, format3);
size = font3.MeasureString(text1, format3);
float x1 = size.Width;
format3.ParagraphIndent = 0;
PdfTrueTypeFont font4 = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Underline));
PdfBrush brush3 = PdfBrushes.Blue;
page.Canvas.DrawString(text2, font4, brush3, x1, y, format3);
size = font4.MeasureString(text2, format3);
x1 = x1 + size.Width;
page.Canvas.DrawString(text3, font3, brush2, x1, y, format3);
y = y + size.Height;
//content
PdfStringFormat format4 = new PdfStringFormat();
text = System.IO.File.ReadAllText(@"Summary_of_Science.txt");
PdfTrueTypeFont font5 = new PdfTrueTypeFont(new Font("Arial", 10f));
format4.LineSpacing = font5.Size * 1.5f;
PdfStringLayouter textLayouter = new PdfStringLayouter();
float imageLeftBlockHeight = imageBottom - y;
PdfStringLayoutResult result
= textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight));
if (result.ActualSize.Height < imageBottom - y)
{
imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight;
result = textLayouter.Layout(text, font5, format4, new SizeF(imageLeftSpace, imageLeftBlockHeight));
}
foreach (LineInfo line in result.Lines)
{
page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4);
y = y + result.LineHeight;
}
PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font5, brush2);
PdfTextLayout textLayout = new PdfTextLayout();
textLayout.Break = PdfLayoutBreakType.FitPage;
textLayout.Layout = PdfLayoutType.Paginate;
RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize);
textWidget.StringFormat = format4;
textWidget.Draw(page, bounds, textLayout);
}
}
}
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Namespace ImageWaterMark
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim img As Image = Image.FromFile("Background.png")
page.BackgroundImage = img
'Draw table
DrawPage(page)
'Save pdf file.
doc.SaveToFile("ImageWaterMark.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("ImageWaterMark.pdf")
End Sub
Private Shared Sub DrawPage(ByVal page As PdfPageBase)
Dim pageWidth As Single = page.Canvas.ClientSize.Width
Dim y As Single = 0
'page header
Dim pen1 As New PdfPen(Color.LightGray, 1.0F)
Dim brush1 As PdfBrush = New PdfSolidBrush(Color.LightGray)
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 8.0F, FontStyle.Italic))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Right)
Dim text As String = "Demo of Spire.Pdf"
page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1)
Dim size As SizeF = font1.MeasureString(text, format1)
y = y + size.Height + 1
page.Canvas.DrawLine(pen1, 0, y, pageWidth, y)
'title
y = y + 5
Dim brush2 As PdfBrush = New PdfSolidBrush(Color.Black)
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format2 As New PdfStringFormat(PdfTextAlignment.Center)
format2.CharacterSpacing = 1.0F
text = "Summary of Science"
page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2)
size = font2.MeasureString(text, format2)
y = y + size.Height + 6
'icon
Dim image As PdfImage = PdfImage.FromFile("Wikipedia_Science.png")
page.Canvas.DrawImage(image, New PointF(pageWidth - image.PhysicalDimension.Width, y))
Dim imageLeftSpace As Single = pageWidth - image.PhysicalDimension.Width - 2
Dim imageBottom As Single = image.PhysicalDimension.Height + y
'refenrence content
Dim font3 As New PdfTrueTypeFont(New Font("Arial", 9.0F))
Dim format3 As New PdfStringFormat()
format3.ParagraphIndent = font3.Size * 2
format3.MeasureTrailingSpaces = True
format3.LineSpacing = font3.Size * 1.5F
Dim text1 As String = "(All text and picture from "
Dim text2 As String = "Wikipedia"
Dim text3 As String = ", the free encyclopedia)"
page.Canvas.DrawString(text1, font3, brush2, 0, y, format3)
size = font3.MeasureString(text1, format3)
Dim x1 As Single = size.Width
format3.ParagraphIndent = 0
Dim font4 As New PdfTrueTypeFont(New Font("Arial", 9.0F, FontStyle.Underline))
Dim brush3 As PdfBrush = PdfBrushes.Blue
page.Canvas.DrawString(text2, font4, brush3, x1, y, format3)
size = font4.MeasureString(text2, format3)
x1 = x1 + size.Width
page.Canvas.DrawString(text3, font3, brush2, x1, y, format3)
y = y + size.Height
'content
Dim format4 As New PdfStringFormat()
text = System.IO.File.ReadAllText("Summary_of_Science.txt")
Dim font5 As New PdfTrueTypeFont(New Font("Arial", 10.0F))
format4.LineSpacing = font5.Size * 1.5F
Dim textLayouter As New PdfStringLayouter()
Dim imageLeftBlockHeight As Single = imageBottom - y
Dim result As PdfStringLayoutResult _
= textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight))
If result.ActualSize.Height < imageBottom - y Then
imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight
result = textLayouter.Layout(text, font5, format4, New SizeF(imageLeftSpace, imageLeftBlockHeight))
End If
For Each line As LineInfo In result.Lines
page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4)
y = y + result.LineHeight
Next line
Dim textWidget As New PdfTextWidget(result.Remainder, font5, brush2)
Dim textLayout As New PdfTextLayout()
textLayout.Break = PdfLayoutBreakType.FitPage
textLayout.Layout = PdfLayoutType.Paginate
Dim bounds As New RectangleF(New PointF(0, y), page.Canvas.ClientSize)
textWidget.StringFormat = format4
textWidget.Draw(page, bounds, textLayout)
End Sub
End Class
End Namespace
Wednesday, 06 April 2011 05:52
PDF TextWaterMark in C#, VB.NET
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
namespace TextWaterMark
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
PdfTilingBrush brush
= new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("Spire.Pdf Demo",
new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,
new PdfStringFormat(PdfTextAlignment.Center));
brush.Graphics.Restore();
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
//Draw the page
DrawPage(page);
//Save pdf file.
doc.SaveToFile("TextWaterMark.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("TextWaterMark.pdf");
}
private static void DrawPage(PdfPageBase page)
{
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Category Sales by Year", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Category Sales by Year", format1).Height;
y = y + 5;
String[][] data
= {
new String[]{"Category Name", "1994 Sale Amount", "1995 Sale Amount", "1996 Sale Amount"},
new String[]{"Beverages", "38,487.20", "102,479.46", "126,901.53"},
new String[]{"Condiments", "16,402.95", "51,041.83", "38,602.31"},
new String[]{"Confections", "23,812.90", "79,752.25", "63,792.07"},
new String[]{"Dairy Products", "30,027.79", "116,495.45", "87,984.05"},
new String[]{"Grains/Cereals", "7,313.92", "53,823.48", "34,607.19"},
new String[]{"Meat/Poultry", "19,856.86", "77,164.75", "66,000.75"},
new String[]{"Produce", "10,694.96", "45,973.69", "43,315.93"},
new String[]{"Seafood", "16,247.77", "64,195.51", "50,818.46"}
};
PdfTable table = new PdfTable();
table.Style.CellPadding = 2;
table.Style.BorderPen = new PdfPen(brush1, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f));
table.Style.HeaderSource = PdfHeaderSource.Rows;
table.Style.HeaderRowCount = 1;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
table.DataSource = data;
PdfLayoutResult result = table.Draw(page, new PointF(0, y));
y = y + result.Bounds.Height + 5;
PdfBrush brush2 = PdfBrushes.LightGray;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
page.Canvas.DrawString("* All data from NorthWind", font2, brush2, 5, y);
}
}
}
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Namespace TextWaterMark
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim brush As New PdfTilingBrush(New SizeF(page.Canvas.ClientSize.Width \ 2, page.Canvas.ClientSize.Height \ 3))
brush.Graphics.SetTransparency(0.3F)
brush.Graphics.Save()
brush.Graphics.TranslateTransform(brush.Size.Width \ 2, brush.Size.Height \ 2)
brush.Graphics.RotateTransform(-45)
brush.Graphics.DrawString("Spire.Pdf Demo", New PdfFont(PdfFontFamily.Helvetica, 24), _
PdfBrushes.Violet, 0, 0, New PdfStringFormat(PdfTextAlignment.Center))
brush.Graphics.Restore()
brush.Graphics.SetTransparency(1)
page.Canvas.DrawRectangle(brush, New RectangleF(New PointF(0, 0), page.Canvas.ClientSize))
'Draw the page
DrawPage(page)
'Save pdf file.
doc.SaveToFile("TextWaterMark.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("TextWaterMark.pdf")
End Sub
Private Shared Sub DrawPage(ByVal page As PdfPageBase)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Category Sales by Year", font1, brush1, _
page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Category Sales by Year", format1).Height
y = y + 5
Dim data()() As String _
= {New String() {"Category Name", "1994 Sale Amount", "1995 Sale Amount", "1996 Sale Amount"}, _
New String() {"Beverages", "38,487.20", "102,479.46", "126,901.53"}, _
New String() {"Condiments", "16,402.95", "51,041.83", "38,602.31"}, _
New String() {"Confections", "23,812.90", "79,752.25", "63,792.07"}, _
New String() {"Dairy Products", "30,027.79", "116,495.45", "87,984.05"}, _
New String() {"Grains/Cereals", "7,313.92", "53,823.48", "34,607.19"}, _
New String() {"Meat/Poultry", "19,856.86", "77,164.75", "66,000.75"}, _
New String() {"Produce", "10,694.96", "45,973.69", "43,315.93"}, _
New String() {"Seafood", "16,247.77", "64,195.51", "50,818.46"}}
Dim table As New PdfTable()
table.Style.CellPadding = 2
table.Style.BorderPen = New PdfPen(brush1, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F))
table.Style.HeaderSource = PdfHeaderSource.Rows
table.Style.HeaderRowCount = 1
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold))
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
table.DataSource = data
Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y))
y = y + result.Bounds.Height + 5
Dim brush2 As PdfBrush = PdfBrushes.LightGray
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9.0F))
page.Canvas.DrawString("* All data from NorthWind", font2, brush2, 5, y)
End Sub
End Class
End Namespace
Wednesday, 06 April 2011 05:33
PDF Grid in C#, VB.NET
The sample demonstrates how to draw nested table in PDF document and set table row&cell format.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
namespace Grid
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape);
float y = 10;
float x1 = page.Canvas.ClientSize.Width;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Vendor List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Vendor List", format1).Height;
y = y + 5;
String[] data
= {
"VendorName;Address1;City;State;Country",
"Cacor Corporation;161 Southfield Rd;Southfield;OH;U.S.A.",
"Underwater;50 N 3rd Street;Indianapolis;IN;U.S.A.",
"J.W. Luscher Mfg.;65 Addams Street;Berkely;MA;U.S.A.",
"Scuba Professionals;3105 East Brace;Rancho Dominguez;CA;U.S.A.",
"Divers' Supply Shop;5208 University Dr;Macon;GA;U.S.A.",
"Techniques;52 Dolphin Drive;Redwood City;CA;U.S.A.",
"Perry Scuba;3443 James Ave;Hapeville;GA;U.S.A.",
"Beauchat, Inc.;45900 SW 2nd Ave;Ft Lauderdale;FL;U.S.A.",
"Amor Aqua;42 West 29th Street;New York;NY;U.S.A.",
"Aqua Research Corp.;P.O. Box 998;Cornish;NH;U.S.A.",
"B&K Undersea Photo;116 W 7th Street;New York;NY;U.S.A.",
"Diving International Unlimited;1148 David Drive;San Diego;DA;U.S.A.",
"Nautical Compressors;65 NW 167 Street;Miami;FL;U.S.A.",
"Glen Specialties, Inc.;17663 Campbell Lane;Huntington Beach;CA;U.S.A.",
"Dive Time;20 Miramar Ave;Long Beach;CA;U.S.A.",
"Undersea Systems, Inc.;18112 Gotham Street;Huntington Beach;CA;U.S.A.",
"Felix Diving;310 S Michigan Ave;Chicago;IL;U.S.A.",
"Central Valley Skin Divers;160 Jameston Ave;Jamaica;NY;U.S.A.",
"Parkway Dive Shop;241 Kelly Street;South Amboy;NJ;U.S.A.",
"Marine Camera & Dive;117 South Valley Rd;San Diego;CA;U.S.A.",
"Dive Canada;275 W Ninth Ave;Vancouver;British Columbia;Canada",
"Dive & Surf;P.O. Box 20210;Indianapolis;IN;U.S.A.",
"Fish Research Labs;29 Wilkins Rd Dept. SD;Los Banos;CA;U.S.A."
};
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
String[] header = data[0].Split(';');
grid.Columns.Add(header.Length);
float width
= page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
grid.Columns[0].Width = width * 0.25f;
grid.Columns[1].Width = width * 0.25f;
grid.Columns[2].Width = width * 0.25f;
grid.Columns[3].Width = width * 0.15f;
grid.Columns[4].Width = width * 0.10f;
PdfGridRow headerRow = grid.Headers.Add(1)[0];
headerRow.Style.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold), true);
headerRow.Style.BackgroundBrush
= new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), Color.Red, Color.Blue);
for (int i = 0; i < header.Length; i++)
{
headerRow.Cells[i].Value = header[i];
headerRow.Cells[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
if (i == 0)
{
headerRow.Cells[i].Style.BackgroundBrush = PdfBrushes.Gray;
}
}
Random random = new Random();
Dictionary groupByCountry = new Dictionary();
for (int r = 1; r < data.Length; r++)
{
PdfGridRow row = grid.Rows.Add();
row.Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
byte[] buffer = new byte[6];
random.NextBytes(buffer);
PdfRGBColor color1 = new PdfRGBColor(buffer[0], buffer[1], buffer[2]);
PdfRGBColor color2 = new PdfRGBColor(buffer[3], buffer[4], buffer[5]);
row.Style.BackgroundBrush
= new PdfLinearGradientBrush(new PointF(0, 0), new PointF(x1, 0), color1, color2);
String[] rowData = data[r].Split(';');
for (int c = 0; c < rowData.Length; c++)
{
row.Cells[c].Value = rowData[c];
if (c == 0)
{
row.Cells[c].Style.BackgroundBrush = PdfBrushes.Gray;
}
if(c < 3)
{
row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
}
else
{
row.Cells[c].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
}
if (c == 4)
{
if (groupByCountry.ContainsKey(rowData[c]))
{
groupByCountry[rowData[c]] = groupByCountry[rowData[c]] + 1;
}
else
{
groupByCountry[rowData[c]] = 1;
}
}
}
}
StringBuilder totalAmount = new StringBuilder();
foreach (KeyValuePair country in groupByCountry)
{
totalAmount.AppendFormat("{0}:\t{1}", country.Key, country.Value);
totalAmount.AppendLine();
}
PdfGridRow totalAmountRow = grid.Rows.Add();
totalAmountRow.Style.BackgroundBrush = PdfBrushes.Plum;
totalAmountRow.Cells[0].Value = "Total Amount";
totalAmountRow.Cells[0].Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold), true);
totalAmountRow.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
totalAmountRow.Cells[1].ColumnSpan = 4;
totalAmountRow.Cells[1].Value = totalAmount.ToString();
totalAmountRow.Cells[1].Style.Font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold | FontStyle.Italic), true);
totalAmountRow.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
//append product list
PdfGrid productList = new PdfGrid();
productList.Style.Font = new PdfTrueTypeFont(new Font("Arial", 8f), true);
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText
= " select p.Description "
+ " from vendors v "
+ " inner join parts p "
+ " on v.VendorNo = p.VendorNo "
+ " where v.VendorName = 'Cacor Corporation'";
command.Connection = conn;
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
productList.DataSource = dataTable;
}
}
productList.Headers[0].Cells[0].Value = "Cacor Corporation";
productList.Headers[0].Cells[0].Style.Font = new PdfTrueTypeFont(new Font("Arial", 8f, FontStyle.Bold), true);
productList.Headers[0].Cells[0].Style.Borders.All = new PdfPen(new PdfTilingBrush(new SizeF(1, 1)), 0);
grid.Rows[0].Cells[0].Value = productList;
grid.Rows[0].Cells[0].StringFormat.Alignment = PdfTextAlignment.Left;
PdfLayoutResult result = grid.Draw(page, new PointF(0, y));
y = y + result.Bounds.Height + 5;
PdfBrush brush2 = PdfBrushes.Gray;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
result.Page.Canvas.DrawString(String.Format("* All {0} vendors in the list", grid.Rows.Count - 1),
font2, brush2, 5, y);
//Save pdf file.
doc.SaveToFile("Grid.pdf");
doc.Close();
//Launching the Pdf file.
PDFDocumentViewer("Grid.pdf");
}
private void PDFDocumentViewer(string fileName)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch { }
}
}
}
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.OleDb
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Grid
Namespace Grid
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape)
Dim y As Single = 10
Dim x1 As Single = page.Canvas.ClientSize.Width
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16F, FontStyle.Bold), True)
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Vendor List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
y = y + font1.MeasureString("Vendor List", format1).Height
y = y + 5
Dim data As [String]() = {"VendorName;Address1;City;State;Country", "Cacor Corporation;161 Southfield Rd;Southfield;OH;U.S.A.", "Underwater;50 N 3rd Street;Indianapolis;IN;U.S.A.", "J.W. Luscher Mfg.;65 Addams Street;Berkely;MA;U.S.A.", "Scuba Professionals;3105 East Brace;Rancho Dominguez;CA;U.S.A.", "Divers' Supply Shop;5208 University Dr;Macon;GA;U.S.A.", _
"Techniques;52 Dolphin Drive;Redwood City;CA;U.S.A.", "Perry Scuba;3443 James Ave;Hapeville;GA;U.S.A.", "Beauchat, Inc.;45900 SW 2nd Ave;Ft Lauderdale;FL;U.S.A.", "Amor Aqua;42 West 29th Street;New York;NY;U.S.A.", "Aqua Research Corp.;P.O. Box 998;Cornish;NH;U.S.A.", "B&K Undersea Photo;116 W 7th Street;New York;NY;U.S.A.", _
"Diving International Unlimited;1148 David Drive;San Diego;DA;U.S.A.", "Nautical Compressors;65 NW 167 Street;Miami;FL;U.S.A.", "Glen Specialties, Inc.;17663 Campbell Lane;Huntington Beach;CA;U.S.A.", "Dive Time;20 Miramar Ave;Long Beach;CA;U.S.A.", "Undersea Systems, Inc.;18112 Gotham Street;Huntington Beach;CA;U.S.A.", "Felix Diving;310 S Michigan Ave;Chicago;IL;U.S.A.", _
"Central Valley Skin Divers;160 Jameston Ave;Jamaica;NY;U.S.A.", "Parkway Dive Shop;241 Kelly Street;South Amboy;NJ;U.S.A.", "Marine Camera & Dive;117 South Valley Rd;San Diego;CA;U.S.A.", "Dive Canada;275 W Ninth Ave;Vancouver;British Columbia;Canada", "Dive & Surf;P.O. Box 20210;Indianapolis;IN;U.S.A.", "Fish Research Labs;29 Wilkins Rd Dept. SD;Los Banos;CA;U.S.A."}
Dim grid As New PdfGrid()
grid.Style.CellPadding = New PdfPaddings(1, 1, 1, 1)
Dim header As [String]() = data(0).Split(";"C)
grid.Columns.Add(header.Length)
Dim width As Single = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1)
grid.Columns(0).Width = width * 0.25F
grid.Columns(1).Width = width * 0.25F
grid.Columns(2).Width = width * 0.25F
grid.Columns(3).Width = width * 0.15F
grid.Columns(4).Width = width * 0.1F
Dim headerRow As PdfGridRow = grid.Headers.Add(1)(0)
headerRow.Style.Font = New PdfTrueTypeFont(New Font("Arial", 11F, FontStyle.Bold), True)
headerRow.Style.BackgroundBrush = New PdfLinearGradientBrush(New PointF(0, 0), New PointF(x1, 0), Color.Red, Color.Blue)
For i As Integer = 0 To header.Length - 1
headerRow.Cells(i).Value = header(i)
headerRow.Cells(i).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
If i = 0 Then
headerRow.Cells(i).Style.BackgroundBrush = PdfBrushes.Gray
End If
Next
Dim random As New Random()
Dim groupByCountry As New Dictionary(Of [String], Integer)()
For r As Integer = 1 To data.Length - 1
Dim row As PdfGridRow = grid.Rows.Add()
row.Style.Font = New PdfTrueTypeFont(New Font("Arial", 10F), True)
Dim buffer As Byte() = New Byte(5) {}
random.NextBytes(buffer)
Dim color1 As New PdfRGBColor(buffer(0), buffer(1), buffer(2))
Dim color2 As New PdfRGBColor(buffer(3), buffer(4), buffer(5))
row.Style.BackgroundBrush = New PdfLinearGradientBrush(New PointF(0, 0), New PointF(x1, 0), color1, color2)
Dim rowData As [String]() = data(r).Split(";"C)
For c As Integer = 0 To rowData.Length - 1
row.Cells(c).Value = rowData(c)
If c = 0 Then
row.Cells(c).Style.BackgroundBrush = PdfBrushes.Gray
End If
If c < 3 Then
row.Cells(c).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
Else
row.Cells(c).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
End If
If c = 4 Then
If groupByCountry.ContainsKey(rowData(c)) Then
groupByCountry(rowData(c)) = groupByCountry(rowData(c)) + 1
Else
groupByCountry(rowData(c)) = 1
End If
End If
Next
Next
Dim totalAmount As New StringBuilder()
For Each country As KeyValuePair(Of [String], Integer) In groupByCountry
totalAmount.AppendFormat("{0}:" & vbTab & "{1}", country.Key, country.Value)
totalAmount.AppendLine()
Next
Dim totalAmountRow As PdfGridRow = grid.Rows.Add()
totalAmountRow.Style.BackgroundBrush = PdfBrushes.Plum
totalAmountRow.Cells(0).Value = "Total Amount"
totalAmountRow.Cells(0).Style.Font = New PdfTrueTypeFont(New Font("Arial", 10F, FontStyle.Bold), True)
totalAmountRow.Cells(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
totalAmountRow.Cells(1).ColumnSpan = 4
totalAmountRow.Cells(1).Value = totalAmount.ToString()
totalAmountRow.Cells(1).Style.Font = New PdfTrueTypeFont(New Font("Arial", 10F, FontStyle.Bold Or FontStyle.Italic), True)
totalAmountRow.Cells(1).StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
'append product list
Dim productList As New PdfGrid()
productList.Style.Font = New PdfTrueTypeFont(New Font("Arial", 8F), True)
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\Data\demo.mdb"
Dim command As New OleDbCommand()
command.CommandText = " select p.Description " & " from vendors v " & " inner join parts p " & " on v.VendorNo = p.VendorNo " & " where v.VendorName = 'Cacor Corporation'"
command.Connection = conn
Using dataAdapter As New OleDbDataAdapter(command)
Dim dataTable As New DataTable()
dataAdapter.Fill(dataTable)
productList.DataSource = dataTable
End Using
End Using
productList.Headers(0).Cells(0).Value = "Cacor Corporation"
productList.Headers(0).Cells(0).Style.Font = New PdfTrueTypeFont(New Font("Arial", 8F, FontStyle.Bold), True)
productList.Headers(0).Cells(0).Style.Borders.All = New PdfPen(New PdfTilingBrush(New SizeF(1, 1)), 0)
grid.Rows(0).Cells(0).Value = productList
grid.Rows(0).Cells(0).StringFormat.Alignment = PdfTextAlignment.Left
Dim result As PdfLayoutResult = grid.Draw(page, New PointF(0, y))
y = y + result.Bounds.Height + 5
Dim brush2 As PdfBrush = PdfBrushes.Gray
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9F))
result.Page.Canvas.DrawString([String].Format("* All {0} vendors in the list", grid.Rows.Count - 1), font2, brush2, 5, y)
'Save pdf file.
doc.SaveToFile("Grid.pdf")
doc.Close()
'Launching the Pdf file.
PDFDocumentViewer("Grid.pdf")
End Sub
Private Sub PDFDocumentViewer(fileName As String)
Try
System.Diagnostics.Process.Start(fileName)
Catch
End Try
End Sub
End Class
End Namespace
Wednesday, 06 April 2011 05:30
PDF TableLayout in C#, VB.NET
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
namespace TableLayout
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
//margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
// Create one page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
float y = 10;
//title
PdfBrush brush1 = PdfBrushes.Black;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
y = y + font1.MeasureString("Part List", format1).Height;
y = y + 5;
//create data table
PdfTable table = new PdfTable();
table.Style.CellPadding = 1;
table.Style.BorderPen = new PdfPen(brush1, 0.75f);
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue;
table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial", 10f), true);
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions;
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue;
table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold), true);
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
table.Style.ShowHeader = true;
table.Style.RepeatHeader = true;
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
OleDbCommand command = new OleDbCommand();
command.CommandText
= " select * from parts ";
command.Connection = conn;
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataTable.Columns.RemoveAt(1);
table.DataSourceType = PdfTableDataSourceType.TableDirect;
table.DataSource = dataTable;
}
}
float width
= page.Canvas.ClientSize.Width
- (table.Columns.Count + 1) * table.Style.BorderPen.Width;
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 1)
{
table.Columns[i].Width = width * 0.4f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
}
else
{
table.Columns[i].Width = width * 0.12f * width;
table.Columns[i].StringFormat
= new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
}
}
table.BeginRowLayout += new BeginRowLayoutEventHandler(table_BeginRowLayout);
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitElement;
tableLayout.Layout = PdfLayoutType.Paginate;
PdfLayoutResult result = table.Draw(page, new PointF(0, y), tableLayout);
y = result.Bounds.Bottom + 5;
PdfBrush brush2 = PdfBrushes.Gray;
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f));
result.Page.Canvas.DrawString(String.Format("* All {0} parts in the list", table.Rows.Count),
font2, brush2, 5, y);
//Save pdf file.
doc.SaveToFile("TableLayout.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("TableLayout.pdf");
}
static void table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
{
if (args.RowIndex < 0)
{
//header
return;
}
if (args.RowIndex % 3 == 0)
{
args.CellStyle.BackgroundBrush = PdfBrushes.LightYellow;
}
else
{
args.CellStyle.BackgroundBrush = PdfBrushes.SkyBlue;
}
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.OleDb
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Namespace SimpleTable
Friend Class Program
Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As New PdfDocument()
'margin
Dim unitCvtr As New PdfUnitConvertor()
Dim margin As New PdfMargins()
margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Bottom = margin.Top
margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
margin.Right = margin.Left
' Create one page
Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, margin)
Dim y As Single = 10
'title
Dim brush1 As PdfBrush = PdfBrushes.Black
Dim font1 As New PdfTrueTypeFont(New Font("Arial", 16.0F, FontStyle.Bold))
Dim format1 As New PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Part List", font1, brush1, page.Canvas.ClientSize.Width \ 2, y, format1)
y = y + font1.MeasureString("Part List", format1).Height
y = y + 5
'create data table
Dim table As New PdfTable()
table.Style.CellPadding = 1
table.Style.BorderPen = New PdfPen(brush1, 0.75F)
table.Style.DefaultStyle.BackgroundBrush = PdfBrushes.SkyBlue
table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("Arial", 10.0F), True)
table.Style.HeaderSource = PdfHeaderSource.ColumnCaptions
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.CadetBlue
table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("Arial", 11.0F, FontStyle.Bold), True)
table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
table.Style.ShowHeader = True
table.Style.RepeatHeader = True
Using conn As New OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb"
Dim command As New OleDbCommand()
command.CommandText = " select * from parts "
command.Connection = conn
Using dataAdapter As New OleDbDataAdapter(command)
Dim dataTable As New DataTable()
dataAdapter.Fill(dataTable)
dataTable.Columns.RemoveAt(1)
table.DataSourceType = PdfTableDataSourceType.TableDirect
table.DataSource = dataTable
End Using
End Using
Dim width As Single = page.Canvas.ClientSize.Width - (table.Columns.Count + 1) * table.Style.BorderPen.Width
For i As Integer = 0 To table.Columns.Count - 1
If i = 1 Then
table.Columns(i).Width = width * 0.4F * width
table.Columns(i).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
Else
table.Columns(i).Width = width * 0.12F * width
table.Columns(i).StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle)
End If
Next i
AddHandler table.BeginRowLayout, AddressOf table_BeginRowLayout
Dim tableLayout As New PdfTableLayoutFormat()
tableLayout.Break = PdfLayoutBreakType.FitElement
tableLayout.Layout = PdfLayoutType.Paginate
Dim result As PdfLayoutResult = table.Draw(page, New PointF(0, y), tableLayout)
y = result.Bounds.Bottom + 5
Dim brush2 As PdfBrush = PdfBrushes.Gray
Dim font2 As New PdfTrueTypeFont(New Font("Arial", 9.0F))
result.Page.Canvas.DrawString(String.Format("* All {0} parts in the list", table.Rows.Count), font2, brush2, 5, y)
'Save pdf file.
doc.SaveToFile("TableLayout.pdf")
doc.Close()
'Launching the Pdf file.
Process.Start("TableLayout.pdf")
End Sub
Private Shared Sub table_BeginRowLayout(ByVal sender As Object, ByVal args As BeginRowLayoutEventArgs)
If args.RowIndex < 0 Then
'header
Return
End If
If args.RowIndex Mod 3 = 0 Then
args.CellStyle.BackgroundBrush = PdfBrushes.LightYellow
Else
args.CellStyle.BackgroundBrush = PdfBrushes.SkyBlue
End If
End Sub
End Class
End Namespace



