Wednesday, 06 July 2011 03:48

Draw PDF Arc in C#, VB.NET

An 'arc' is part of the circumference of a circle. In geometry, an arc is a closed segment of a differentiable curve in the two-dimensional plane; for example, a circular arc is a segment of the circumference of a circle. If the arc is part of a great circle (or great ellipse), it is called a great arc. This article will introduce a solution to draw PDF arc and set arc position and size via this .NET PDF component Spire.PDF for .NET in C#, VB.NET. First let us see the PDF arc which is drawn by code in the end of this section:

When we draw PDF arcs, we first need to know this method provided by Spire.PDF for .NET: Spire.Pdf.PdfPageBase.Canvas.DrawArc(PdfPen pen, float x, float y, float width, float height, float startAngle, float sweepAngle); As we see, there are seven parameters passed in this method. The first parameter is a class: Spire.Pdf.Graphics.PdfPen. By using this class, we can draw arc in PDF. If we want to set the color of PDF arc and the thickness of the arc line, we can use another two classes which are offered by Microsoft: System.Drawing.Color and System.Single. The second and third parameters: "float x" and "float y" determine the distance between the arcs and PDF left and top margin. The fourth and fifth parameters are the width and height of PDF arc. The last two parameters start angle and sweep angle which decide which kind of arc we draw.

Here we can download Spire.PDF for .NET; and install it on system. After adding Spire.Pdf dll, we can start our task according to below code:

[C#]
```using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace pdfcircle
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
// Create one page
//draw PDF arcs and set its size and position
PdfGraphicsState state = page.Canvas.Save();
PdfPen pen = new PdfPen(Color.DeepSkyBlue, 4f);
PdfPen pen1 = new PdfPen(Color.Red, 4f);
PdfPen pen2 = new PdfPen(Color.Red, 4f);
PdfPen pen3 = new PdfPen(Color.DeepSkyBlue, 4f);
PdfPen pen4 = new PdfPen(Color.Black, 4f);
PdfPen pen5 = new PdfPen(Color.Black, 4f);
PdfPen pen6 = new PdfPen(Color.Black, 4f);
PdfPen pen7 = new PdfPen(Color.Black, 4f);
PdfPen pen8 = new PdfPen(Color.Red, 1f);
PdfPen pen9= new PdfPen(Color.Red, 1f);
page.Canvas.DrawArc(pen, 130, 100, 20, 90, 20, 300);
page.Canvas.DrawArc(pen1, 60, 100, 20, 90, 20,300);
page.Canvas.DrawArc(pen2, 90, 100, 20, 90, 218, 300);
page.Canvas.DrawArc(pen3, 160, 100, 20, 90, 218, 300);
page.Canvas.DrawArc(pen4, 70, 130, 5, 5, 0, 360);
page.Canvas.DrawArc(pen5, 95, 130, 5, 5, 0, 360);
page.Canvas.DrawArc(pen6, 140, 130, 5, 5, 0, 360);
page.Canvas.DrawArc(pen7, 161, 130, 5, 5, 0, 360);
page.Canvas.DrawArc(pen8, 83, 145, 5, 5, 350,200);
page.Canvas.DrawArc(pen9, 150, 145, 5, 5, 350, 200);
//restor graphics
page.Canvas.Restore(state);
doc.SaveToFile("Arcs.pdf");
System.Diagnostics.Process.Start("Arcs.pdf");
}
}
}```
[VB.NET]
```Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace pdfcircle
Class Program
Private Shared Sub Main(args As String())
'Create a pdf document.
Dim doc As New PdfDocument()
' Create one page
Dim page As PdfPageBase = doc.Pages.Add()
'draw PDF arcs and set its size and position
Dim state As PdfGraphicsState = page.Canvas.Save()
Dim pen As New PdfPen(Color.DeepSkyBlue, 4F)
Dim pen1 As New PdfPen(Color.Red, 4F)
Dim pen2 As New PdfPen(Color.Red, 4F)
Dim pen3 As New PdfPen(Color.DeepSkyBlue, 4F)
Dim pen4 As New PdfPen(Color.Black, 4F)
Dim pen5 As New PdfPen(Color.Black, 4F)
Dim pen6 As New PdfPen(Color.Black, 4F)
Dim pen7 As New PdfPen(Color.Black, 4F)
Dim pen8 As New PdfPen(Color.Red, 1F)
Dim pen9 As New PdfPen(Color.Red, 1F)
page.Canvas.DrawArc(pen, 130, 100, 20, 90, 20, _
300)
page.Canvas.DrawArc(pen1, 60, 100, 20, 90, 20, _
300)
page.Canvas.DrawArc(pen2, 90, 100, 20, 90, 218, _
300)
page.Canvas.DrawArc(pen3, 160, 100, 20, 90, 218, _
300)
page.Canvas.DrawArc(pen4, 70, 130, 5, 5, 0, _
360)
page.Canvas.DrawArc(pen5, 95, 130, 5, 5, 0, _
360)
page.Canvas.DrawArc(pen6, 140, 130, 5, 5, 0, _
360)
page.Canvas.DrawArc(pen7, 161, 130, 5, 5, 0, _
360)
page.Canvas.DrawArc(pen8, 83, 145, 5, 5, 350, _
200)
page.Canvas.DrawArc(pen9, 150, 145, 5, 5, 350, _
200)
'restor graphics
page.Canvas.Restore(state)
doc.SaveToFile("Arcs.pdf")
System.Diagnostics.Process.Start("Arcs.pdf")
End Sub
End Class
End Namespace
```

Spire.PDF for .NET is a .NET PDF library that enables users to draw different kinds of shapes in PDF document in C#, VB.NET.

Wednesday, 06 July 2011 03:26

Draw Circles in PDF in C#, VB.NET

Circles can be defined as the curves traced out by points that move so that its distance from a given point is constant. They are also look as special ellipses in which the two foci are coincident and the eccentricity is “0”. Whatever they are, they are indispensable in PDF document. This section will introduce a solution to draw circles and set their size and position in PDF file via a .NET PDF component Spire.PDF for .NET in C#, VB.NET.

When we draw circles in PDF, we only need to call one method in Spire.PDF: Spire.Pdf.PdfPageBase.Canvas.DrawPie(PdfPen pen, float x, float y, float width, float height, float startAngle, float sweepAngle); Here there are seven parameters in this method. The first one is the class Spire.Pdf.Graphics.PdfPen which can define the color and the outline of the circle. If we change this parameter to be another class Spire.Pdf.Graphics.PdfBrush, we can easily fill the circle with a certain color. The second and third parameters determine the exact distance between the PDF margin and the circle. "float x" decides the distance of left margin with circle, while "float y" means the distance between the top margin with the circle. By setting the fourth and fifth parameters, we can decide the circle width and height. The last two parameters are the start angle and sweep angle when drawing circles. Now please view the circles in PDF as below picture:

Here we can quickly download Spire.PDF for .NET . After adding Spire.Pdf dll in the download Bin folder, we can draw circles in PDF file via Spire.PDF by below code.

[C#]
```using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace pdf_circles
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
// Create one page
//save graphics state
PdfGraphicsState state = page.Canvas.Save();
PdfPen pen = new PdfPen(Color.Red, 1f);
PdfPen pen1 = new PdfPen(Color.GreenYellow, 2f);
PdfBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);
page.Canvas.DrawPie(pen, 30, 30, 80, 90, 360, 360);
page.Canvas.DrawPie(brush, 150, 30, 100, 90, 360, 360);
page.Canvas.DrawPie(pen1,290, 30, 70, 90, 360, 360);
//restor graphics
page.Canvas.Restore(state);
doc.SaveToFile("Circles.pdf");
System.Diagnostics.Process.Start("Circles.pdf");
}
}
}
```
[VB.NET]
```Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace pdf_circles
Class Program
Private Shared Sub Main(args As String())
'Create a pdf document.
Dim doc As New PdfDocument()
' Create one page
Dim page As PdfPageBase = doc.Pages.Add()
'save graphics state
Dim state As PdfGraphicsState = page.Canvas.Save()
Dim pen As New PdfPen(Color.Red, 1F)
Dim pen1 As New PdfPen(Color.GreenYellow, 2F)
Dim brush As PdfBrush = New PdfSolidBrush(Color.DeepSkyBlue)
page.Canvas.DrawPie(pen, 30, 30, 80, 90, 360, _
360)
page.Canvas.DrawPie(brush, 150, 30, 100, 90, 360, _
360)
page.Canvas.DrawPie(pen1, 290, 30, 70, 90, 360, _
360)
'restor graphics
page.Canvas.Restore(state)
doc.SaveToFile("Circles.pdf")
System.Diagnostics.Process.Start("Circles.pdf")
End Sub
End Class
End Namespace
```

Spire.PDF for .NET is a PDF component that enables users to draw different kinds of shapes in PDF document in C#, VB.NET.

Tuesday, 05 July 2011 06:11

Draw Rectangles in PDF in C#, VB.NET

In Euclidean plane geometry, a rectangle is any quadrilateral with four right angles. The term "oblong" is occasionally used to refer to a non-square rectangle. A rectangle with vertices ABCD would be denoted as ABCD. It’s simple for people to draw rectangles in paper. While how about drawing rectangles in PDF document? This section will show you the exact answer. This section will introduce a solution to draw rectangles and set the size and position of rectangles in PDF via a .NET PDF component Spire.PDF for .NET with C#, VB.NET.

In Spire.PDF, there are two classes: Spire.Pdf.Graphics.PdfPen and Spire.Pdf.Granphics.PdfBrush. By using the first class, we can set the color and decide the outline of the PDF rectangle. While the second class can quickly help us fill the rectangles with a color we want. Now let us see this method: Spire.Pdf.PdfPageBase.Canvas.DrawRectangle(PdfPen pen, RectangleF rectangle); There are two parameters passed. One is the PdfPen which I referred above. The other represents the location and size of a rectangle. By calling this method, we can draw rectangles and set their size and position very quickly. Now let us view the rectangles as below picture:

Here we can download Spire.PDF for .NET and install it on system. After adding Spire.Pdf dll, we can draw rectangle in our PDF document as below code:

[C#]
```using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace PDF_rectangles
{
class Program
{
static void Main(string[] args)
{
//create a PDF
PdfDocument pdfDoc = new PdfDocument();
//save graphics state
PdfGraphicsState state = page.Canvas.Save();
//draw rectangles
PdfPen pen = new PdfPen(Color.ForestGreen, 0.1f);
PdfPen pen1 = new PdfPen(Color.Red, 3f);
PdfBrush brush = new PdfSolidBrush(Color.Orange);
page.Canvas.DrawRectangle(pen, new Rectangle(new Point(2, 7), new Size(120, 120)));
page.Canvas.DrawRectangle(pen1, new Rectangle(new Point(350, 7), new Size(160, 120)));
page.Canvas.DrawRectangle(brush, new RectangleF(new Point(158, 7), new SizeF(160, 120)));
//restor graphics
page.Canvas.Restore(state);
pdfDoc.SaveToFile("Rectangles.pdf");
System.Diagnostics.Process.Start("Rectangles.pdf");
}
}
}
```
[VB.NET]
```Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace PDF_rectangles
Class Program
Private Shared Sub Main(args As String())
'create a PDF
Dim pdfDoc As New PdfDocument()
Dim page As PdfPageBase = pdfDoc.Pages.Add()
'save graphics state
Dim state As PdfGraphicsState = page.Canvas.Save()
'draw rectangles
Dim pen As New PdfPen(Color.ForestGreen, 0.1F)
Dim pen1 As New PdfPen(Color.Red, 3F)
Dim brush As PdfBrush = New PdfSolidBrush(Color.Orange)
page.Canvas.DrawRectangle(pen, New Rectangle(New Point(2, 7), New Size(120, 120)))
page.Canvas.DrawRectangle(pen1, New Rectangle(New Point(350, 7), New Size(160, 120)))
page.Canvas.DrawRectangle(brush, New RectangleF(New Point(158, 7), New SizeF(160, 120)))
'restor graphics
page.Canvas.Restore(state)
pdfDoc.SaveToFile("Rectangles.pdf")
System.Diagnostics.Process.Start("Rectangles.pdf")
End Sub
End Class
End Namespace
```

Spire.PDF for .NET is a .NET PDF component that can draw different kinds of shapes in PDF document such as Circles, Arcs. Ellipse and Five-pointed Star.

Monday, 04 July 2011 08:57

Create Digital Signature in PDF in C#, VB.NET

Digital signature is the alternative way of signing documents in era of electronic exchange of documents. Creating digital signature in PDF, without any doubt, becomes one of the most popular ways to protect PDF file from editing and tampering. This section will introduce a solution to create digital signature in PDF via a .NET PDF component.

Spire.PDF for .NET, with rich features to protect and manipulate PDF documents, allows you to keep your PDF secure by creating digital signature in PDF with C#, VB.NET. As long as the digital signature is signed, the signer's identity has been verified and your PDF document can be safe and cannot be modified.

In the key code, first you are required to create one instance of Spire.Pdf.Security.PdfCertificate class with two parameters passed: a certificate file and the file password. This instance is named to be digi. After that, digi is used as a parameter of another instance in a different class: PdfSignature class. Here it is called signature. In order to sign PDF digital signature in any page, a "page" parameter is provided. Through DocumentPermission, you can restrict the PDF permission to be AllowComments, AllowFormFill and ForbidChanges.

[C#]
```PdfDocument doc = new PdfDocument("Sample.pdf");
PdfPageBase page = doc.Pages[0];

PdfCertificate cert = new PdfCertificate("Demo.pfx", "e-iceblue");

PdfSignature signature = new PdfSignature(doc, page, cert, "demo");

signature.ContactInfo = "Harry";
signature.Certificated = true;

signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;

doc.SaveToFile("Result.pdf");
```
[VB.NET]
```Private Sub SurroundingSub()
Dim doc As PdfDocument = New PdfDocument("Sample.pdf")
Dim page As PdfPageBase = doc.Pages(0)
Dim cert As PdfCertificate = New PdfCertificate("Demo.pfx", "e-iceblue")
Dim signature As PdfSignature = New PdfSignature(doc, page, cert, "demo")
signature.ContactInfo = "Harry"
signature.Certificated = True
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill
doc.SaveToFile("Result.pdf")
End Sub
```

Spire.PDF for .NET is a .NET PDF component which can secure your PDF by encrypting PDF and creating PDF digital signature. When you need to unlock PDF file, it also enables you to decrypt PDF in a fast way.

Monday, 04 July 2011 08:19

Encrypt PDF Document in C#, VB.NET

Encrypting PDF is a way people commonly used to protect PDF. Whether for a company or for individual, using PDF encryption to place some certain restrictions is indispensable. In order to make the PDF document available to read but unable to modify by unauthorized users, two passwords are required for an encrypted PDF document: owner password and user password. This section will particularly introduce a simple solution to quickly encrypt PDF with C#, VB.NET via Spire.PDF for .NET.

Spire.PDF for .NET as a .NET PDF component, can encrypt your PDF by owner and user password. Owner password is provided to fully access to PDF file such as reset password and restrictions. While user password allows users to open the document as well as subject to the restrictions placed by owner.

In the encryption solution, an object of the PDFSecurity class which is included in the namespace Spire.PDFDocument.Security is used to set the owner and user password. Please feel free to download Spire.PDF for .NET and load your PDF file and then protect it.

Protect PDF by setting password and specify document restrictions.

Step 1: Set PDF key size by the enum."Spire.Pdf.Security.PdfEncryptionKeySize".Three kinds of key size are available here: Key128Bit, Key256Bit and Key40Bit, you can use any one among the three.

[C#]
```doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
```
[VB.NET]
`doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit `

Step 2: Encrypt PDF file by setting owner and user password. The password size you set should not be over the key size.

[C#]
```doc.Security.OwnerPassword = "e-iceblue";
```
[VB.NET]
```doc.Security.OwnerPassword = "e-iceblue"

Step 3: Specify access restrictions of user password. There are nine permissions are available in the solution. You can see them as below picture.

[C#]
```doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent;
```
[VB.NET]
```doc.Security.Permissions = PdfPermissionsFlags.Print Or PdfPermissionsFlags. CopyContent
```

After running your project, you will be requested a password when you open this encrypted PDF file. Please look at the effective screenshot below:

Friday, 01 July 2011 02:51

Marker Designer

Introduction

A Marker Designer represents a single data point or value that gives a mean to Spire.XLS to place relevant data into different cells of the worksheet in a workbook. We make use of Designer spreadsheets in which we write marker designers into different cells. Normally a marker designer consists of DataSource and a Field Name and starts with "&=". The DataSource can be a DataSet, DataTable, DataView or an Object variable etc. You can also make use of dynamic formulas that allows you to insert MS Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. Moreover, you may calculate totals and sub totals of any data field too.

Marker designer is a way to let Spire.XLS know that what information you wish to place in an Excel designer spreadsheet. Marker designers allow you to create templates that contain only relevant information and are formatted to meet your needs.

Designer spreadsheets are standard Excel files that contain the visual formatting, formulas and marker designers. They can contain marker designers that reference one or more data sources such as information from a project and information for related contacts. Marker designers are written into cells where you want information to be filled in.

All marker designers start with "&=", without the quotes. An example of a data marker is &=Party.FullName. If the data marker results in more than one item, i.e. row then following rows will be moved down automatically to make room for all of the new information. Thus sub-totals and totals can be placed on the following row after the data marker to make calculations based on inserted data. In order to make calculations on the rows that are inserted, you must use Dynamic Formulas.

Marker designers consist of the Data Source and Field Name parts for most information. Special information may also be passed with variables and variable arrays. Variables always fill only one cell whereas variable arrays may fill several ones. You may only use one data marker per cell. Unused marker designers will be removed.

Marker designer may also contain parameters. Parameters allow you to modify how the information will be laid out. They are appended to the end of marker designer in parenthesis as a comma separated list.

Marker designer Options

```&=DataSource.FieldName
&=[Data Source].[Field Name]
&=VariableName
```

Formulas

Formulas allow you to insert Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. And they can repeat for each inserted row or use only the cell where the data marker is placed for it.

If value of a cell referred to other cells, such as (copy:rc6), it means the value of the cell will be referred by cells of column 6. Multiple refer can be used like this: (copy:rc5,copy:rc7).

Note: Separate them with comma

Cell "G6" contains the formula = D6*E6, cell "G7" contains = D7*E7 and cell "G8" contains = D8*E8, etc.

The following illustrates a repeating dynamic formula and the resulting Excel worksheet.

Result:

Sum and Subtotal

Below is showing you how to use these 2 formulas:

Result:

Code:

```          Workbook workbook = new Workbook();

DataTable dt = (DataTable)dataGrid1.DataSource;

Worksheet sheet = workbook.Worksheets[0];
//fill parameter
//fill DataTable
workbook.MarkerDesigner.Apply();

//AutoFit
sheet.AllocatedRange.AutoFitRows();
sheet.AllocatedRange.AutoFitColumns();

workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);
```

Marker Designer Full Demo

Friday, 24 June 2011 06:06

PDF header presents consistent information of a PDF document. It can be automatic page number, a date, a section title, an icon or an image. Whatever it is, it is an important part for a PDF file. This article will introduce how to add a header when programmatically creating a PDF document from scratch.

You can add both text and image in your PDF header by using Spire.PDF for .NET. In order to display the header content appropriately, you can also set text format and image size. The picture below shows the output after adding header in PDF:

Main Steps:

Step 1: Define a custom function CreateHeaderTemplate() to create a page template element that servers as header, and return a PdfPageDocumentElement object.

In the code below, we first initialize a page template object that can be used as header, then call DrawString() method, DrawImage() method and DrawLine() method to insert text,image and line into the header space.

```static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins)
{
//get page size
SizeF pageSize = doc.PageSettings.Size;

//create a PdfPageTemplateElement object as header space
PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);

//declare two float variables
float x = margins.Left;
float y = 0;

float width = headerImage.Width / 3;
float height = headerImage.Height / 3;

PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2);

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 25f, FontStyle.Bold));
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);

}
```

Step 2: Create a PDF document, call the method CreateHeaderTemplate() to create a header template and apply it to the document.

```static void Main(string[] args)
{
//create a PDF document
PdfDocument doc = new PdfDocument();
doc.PageSettings.Size = PdfPageSize.A4;

//reset the default margins to 0
doc.PageSettings.Margins = new PdfMargins(0);

//create a PdfMargins object, the parameters indicate the page margins you want to set
PdfMargins margins = new PdfMargins(60, 60, 60, 60);

//create a header template with content and apply it to page template

//apply blank templates to other parts of page template
doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom);
doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

//save the file
}
```

Full Code:

[C#]
```static void Main(string[] args)
{
//create a PDF document
PdfDocument doc = new PdfDocument();
doc.PageSettings.Size = PdfPageSize.A4;

//reset the default margins to 0
doc.PageSettings.Margins = new PdfMargins(0);

//create a PdfMargins object, the parameters indicate the page margins you want to set
PdfMargins margins = new PdfMargins(60, 60, 60, 60);

//create a header template with content and apply it to page template

//apply blank templates to other parts of page template
doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom);
doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

//save the file
}
static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins)
{
//get page size
SizeF pageSize = doc.PageSettings.Size;

//create a PdfPageTemplateElement object as header space
PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);

//declare two float variables
float x = margins.Left;
float y = 0;

float width = headerImage.Width / 3;
float height = headerImage.Height / 3;

PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2);

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 25f, FontStyle.Bold));
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);

}
```
[VB.NET]
```[VB.NET]
Private Shared Sub Main(ByVal args As String())
Dim doc As PdfDocument = New PdfDocument()
doc.PageSettings.Size = PdfPageSize.A4
doc.PageSettings.Margins = New PdfMargins(0)
Dim margins As PdfMargins = New PdfMargins(60, 60, 60, 60)
doc.Template.Bottom = New PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Bottom)
doc.Template.Left = New PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height)
doc.Template.Right = New PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height)
End Sub

Private Shared Function CreateHeaderTemplate(ByVal doc As PdfDocument, ByVal margins As PdfMargins) As PdfPageTemplateElement
Dim pageSize As SizeF = doc.PageSettings.Size
Dim headerSpace As PdfPageTemplateElement = New PdfPageTemplateElement(pageSize.Width, margins.Top)
Dim x As Single = margins.Left
Dim y As Single = 0
Dim headerImage As PdfImage = PdfImage.FromFile("logo.png")
Dim width As Single = headerImage.Width / 3
Dim height As Single = headerImage.Height / 3
Dim pen As PdfPen = New PdfPen(PdfBrushes.Gray, 1)
headerSpace.Graphics.DrawLine(pen, x, y + margins.Top - 2, pageSize.Width - x, y + margins.Top - 2)
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Impact", 25F, FontStyle.Bold))
Dim format As PdfStringFormat = New PdfStringFormat(PdfTextAlignment.Left)
Dim size As SizeF = font.MeasureString(headerText, format)
headerSpace.Graphics.DrawString(headerText, font, PdfBrushes.Gray, pageSize.Width - x - size.Width - 2, margins.Top - (size.Height + 5), format)
End Function
```
Friday, 24 June 2011 05:51

Add PDF Footer in C#, VB.NET

A PDF header or footer presents consistent information (For example: a date, page numbering, the title of the overall document, or author’s name) in the page margins throughout a PDF. In this article, you will learn to add text and automatic page numbering to footer space when creating a PDF document from scratch.

Spire.PDF has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField, PdfPageNumberField, etc.

Step 1: Define a custom function CreateFooterTemplate() to create a page template element that servers as footer, and return a PdfPageDocumentElement object.

```static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
{
//get page size
SizeF pageSize = doc.PageSettings.Size;

//create a PdfPageTemplateElement object which works as footer space
PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
footerSpace.Foreground = false;

//declare two float variables
float x = margins.Left;
float y = 0;

//draw line in footer space
PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

//draw text in footer space
y = y + 5;
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

//draw dynamic field in footer space
PdfPageNumberField number = new PdfPageNumberField();
PdfPageCountField count = new PdfPageCountField();
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
SizeF size = font.MeasureString(compositeField.Text);
compositeField.Bounds = new RectangleF(pageSize.Width - x , y, size.Width, size.Height);
compositeField.Draw(footerSpace.Graphics);

//return footerSpace
return footerSpace;
}
```

Step 2: Create a PDF document, call the method CreateFooterTemplate() to create a footer template and apply it to the document.

```static void Main(string[] args)
{
//create a PDF document
PdfDocument doc = new PdfDocument();
doc.PageSettings.Size = PdfPageSize.A4;

//reset the default margins to 0
doc.PageSettings.Margins = new PdfMargins(0);

//create a PdfMargins object, the parameters indicate the page margins you want to set
PdfMargins margins = new PdfMargins(60, 60, 60, 60);

//create a footer template with content and apply it to bottom page template
doc.Template.Bottom = CreateFooterTemplate(doc, margins);

//apply blank templates to other parts of page template
doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

//add two pages in the document

//save the file
doc.SaveToFile("PdfFooter.pdf");
}
```

Output:

Full Code:

[C#]
```static void Main(string[] args)
{
//create a PDF document
PdfDocument doc = new PdfDocument();
doc.PageSettings.Size = PdfPageSize.A4;

//reset the default margins to 0
doc.PageSettings.Margins = new PdfMargins(0);

//create a PdfMargins object, the parameters indicate the page margins you want to set
PdfMargins margins = new PdfMargins(60, 60, 60, 60);

//create a footer template with content and apply it to page template
doc.Template.Bottom = CreateFooterTemplate(doc, margins);

//apply blank templates to other parts of page template
doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

//add two pages in the document

//save the file
doc.SaveToFile("PdfFooter.pdf");
}
static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
{
//get page size
SizeF pageSize = doc.PageSettings.Size;

//create a PdfPageTemplateElement object which works as footer space
PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
footerSpace.Foreground = false;

//declare two float variables
float x = margins.Left;
float y = 0;

//draw line in footer space
PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

//draw text in footer space
y = y + 5;
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

//draw dynamic field in footer space
PdfPageNumberField number = new PdfPageNumberField();
PdfPageCountField count = new PdfPageCountField();
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
SizeF size = font.MeasureString(compositeField.Text);
compositeField.Bounds = new RectangleF(pageSize.Width - x , y, size.Width, size.Height);
compositeField.Draw(footerSpace.Graphics);

//return footerSpace
return footerSpace;
}
```
[VB.NET]
```Private Shared Sub Main(ByVal args As String())
Dim doc As PdfDocument = New PdfDocument()
doc.PageSettings.Size = PdfPageSize.A4
doc.PageSettings.Margins = New PdfMargins(0)
Dim margins As PdfMargins = New PdfMargins(60, 60, 60, 60)
doc.Template.Bottom = CreateFooterTemplate(doc, margins)
doc.Template.Top = New PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top)
doc.Template.Left = New PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height)
doc.Template.Right = New PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height)
doc.SaveToFile("PdfFooter.pdf")
End Sub

Private Shared Function CreateFooterTemplate(ByVal doc As PdfDocument, ByVal margins As PdfMargins) As PdfPageTemplateElement
Dim pageSize As SizeF = doc.PageSettings.Size
Dim footerSpace As PdfPageTemplateElement = New PdfPageTemplateElement(pageSize.Width, margins.Bottom)
footerSpace.Foreground = False
Dim x As Single = margins.Left
Dim y As Single = 0
Dim pen As PdfPen = New PdfPen(PdfBrushes.Gray, 1)
footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y)
y = y + 5
Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Impact", 10F), True)
Dim format As PdfStringFormat = New PdfStringFormat(PdfTextAlignment.Left)
Dim footerText As String = "E-iceblue Technology Co., Ltd." & vbLf & "Tel:028-81705109" & vbLf & "Website:http://www.e-iceblue.com"
footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format)
Dim number As PdfPageNumberField = New PdfPageNumberField()
Dim count As PdfPageCountField = New PdfPageCountField()
Dim compositeField As PdfCompositeField = New PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count)
compositeField.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
Dim size As SizeF = font.MeasureString(compositeField.Text)
compositeField.Bounds = New RectangleF(pageSize.Width - x, y, size.Width, size.Height)
compositeField.Draw(footerSpace.Graphics)
Return footerSpace
End Function
```
Friday, 24 June 2011 05:28

Read PDF Images and Text in C#, VB.NET

This section aims at introducing a solution to read PDF via a .net PDF component in C#, VB.NET. In this solution, you can realize your PDF read task in only three steps. Besides, you can save the extracted image to be many commonly used formats such as jpg, jpeg, png, bmp, tiff, gif etc. Some special texts such as texts which are written from right to left for example Herbrew, Arabic etc all can be read from PDF.

Spire.PDF for .NET, a professional .NET PDF component for reading, editing and manipulating PDF file, enables you to read your PDF file in a fast way. First, you can implement PdfDocument.LoadFromFile(string filename) method to load your PDF file from system.Then, please call the methods ExtractText and ExtractImages to extract PDF txt and images. System.IO.File.WriteAllText(string path, string contents) and Image.Save(string filename, ImageFormat format) , you can save the extracted text and images respectively.Please download Spire.PDF for .NET and view below picture:

Detail Code:

[C#]
```using Spire.Pdf;

namespace extract_pdf
{
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();

StringBuilder buffer = new StringBuilder();
IList images = new List();

foreach (PdfPageBase page in doc.Pages)
{
buffer.Append(page.ExtractText());
foreach (Image image in page.ExtractImages())
{
}
}

doc.Close();
//save text
String fileName = "TextInPdf.txt";
File.WriteAllText(fileName, buffer.ToString());
//save image
int index = 0;
foreach (Image image in images)
{
String imageFileName
= String.Format("Image-{0}.png", index++);
image.Save(imageFileName, ImageFormat.Png);
}
//Launching the Text file.
System.Diagnostics.Process.Start(fileName);
}

}
}
```
[VB.NET]
```Imports Spire.Pdf

Namespace extract_pdf
Class Program
Private Shared Sub Main(ByVal args() As String)
'Create a pdf document.
Dim doc As PdfDocument = New PdfDocument
Dim buffer As StringBuilder = New StringBuilder
Dim images As IList(Of Image) = New List(Of Image)
For Each page As PdfPageBase In doc.Pages
buffer.Append(page.ExtractText)
For Each image As Image In page.ExtractImages
Next
Next
doc.Close
'save text
Dim fileName As String = "TextInPdf.txt"
File.WriteAllText(fileName, buffer.ToString)
'save image
Dim index As Integer = 0
For Each image As Image In images
Dim imageFileName As String = String.Format("Image-{0}.png", index++)
image.Save(imageFileName, ImageFormat.Png)
Next
'Launching the Text file.
System.Diagnostics.Process.Start(fileName)
End Sub
End Class
End Namespace
```

Spire.PDF is a .NET PDF component, which enables users to perform a wide range of PDF document processing tasks directly, such as generate, read, write and modify PDF document in WPF, .NET and Silverlight.

Page 123 of 124