.NET (1317)
Children categories
An image watermark is usually a logo or sign that appears on the background of digital documents, indicating the copyright owner of the content. Watermarking your PDF document with an image can prevent your data from being reused or modified. This article demonstrates how to add an image watermark to PDF in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Add an Image Watermark to PDF
The following are the main steps to add an image watermark to a PDF document.
- Create a PdfDocument object, and load a sample PDF file using PdfDocument.LoadFromFile() method.
- Load an image file using Image.FromFile() method.
- Loop through the pages in the document, and get the specific page through PdfDocument.Pages[] property.
- Set the image as background/watermark image of the current page through PdfPageBase.BackgroundImage property. Set the image position and size through PdfPageBase.BackgroundRegion property.
- Save the document to a different PDF file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
using System.Drawing;
namespace AddImageWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//Get the image width and height
int imgWidth = image.Width;
int imgHeight = image.Height;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
{
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
float pageHeight = document.Pages[i].ActualSize.Height;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
document.Pages[i].BackgroundRegion = rect;
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
document.Close();
}
}
}
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument()
'Load a sample PDF document
document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer
For i = 0 To document.Pages.Count- 1 Step i + 1
'Get the page width and height
Dim pageWidth As single = document.Pages(i).ActualSize.Width
Dim pageHeight As single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3f
'Set the background image of current page
document.Pages(i).BackgroundImage = image
Dim rect As Rectangle = New Rectangle(CInt((pageWidth - imgWidth) / 2), CInt((pageHeight - imgHeight) / 2), imgWidth, imgHeight)
document.Pages(i).BackgroundRegion = rect
Next
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close()
End Sub
End Class
End Namespace

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Spire.XLS provides a class named Worksheet, it contains a MergedCells property which makes it easy for us to obtain the merged cells in a worksheet. This property will return an array of the merged cell ranges, after that we can do any desired operations such as unmerge and apply formatting on the cells in the ranges. This article explains how to detect all merged cells in a worksheet and unmerge them once using Spire.XLS.
Here we used a template Excel file which has some merged cells:

Detail steps:
Step 1: Instantiate a Workbook object and load the Excel file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Step 2: Access the first worksheet by passing its sheet index.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Get the merged cell ranges in the first worksheet and put them into a CellRange array.
CellRange[] range = sheet.MergedCells;
Step 4: Traverse through the array and unmerge the merged cells.
foreach (CellRange cell in range)
{
cell.UnMerge();
}
Step 5: Save the file.
workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010);
After executing the code, we'll get the following output file:

Full codes:
using Spire.Xls;
namespace Detect_Merged_Cells
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];
CellRange[] range = sheet.MergedCells;
foreach (CellRange cell in range)
{
cell.UnMerge();
}
workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010);
}
}
}
Imports Spire.Xls
Namespace Detect_Merged_Cells
Class Program
Private Shared Sub Main(args As String())
Dim workbook As New Workbook()
workbook.LoadFromFile("Sample.xlsx")
Dim sheet As Worksheet = workbook.Worksheets(0)
Dim range As CellRange() = sheet.MergedCells
For Each cell As CellRange In range
cell.UnMerge()
Next
workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010)
End Sub
End Class
End Namespace
With the help of Spire.PDF, we have already demonstrated how to add text with different styles to a PDF file. By using the method canvas.drawstring offered by Spire.PDF, we can set the position, font, brush and style for the adding texts. With the PdfFontStyle, we can set the style to underline, bold, italic, regular and strikeout. Sometimes we may need to set multiple font style for the same texts within one paragraph, such as bold and italic together.
Here comes to the code snippet of how to apply two kinds of font styles together for the text on PDF in C#.
Step 1: Create a new PDF document.
PdfDocument pdf = new PdfDocument();
Step 2: Add a new page to the PDF file.
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins());
Step 3: Create the PdfFont as Helvetica with size 10f, apply two font styles for it.
PdfFont font = new PdfFont(PdfFontFamily.Helvetica,10f,PdfFontStyle.Italic | PdfFontStyle.Underline); PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Strikeout); PdfFont font3 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Underline);
Step 4: Create a brush and set its color.
PdfSolidBrush brush = new PdfSolidBrush(Color.Blue); PdfSolidBrush brush2 = new PdfSolidBrush(Color.Gray); PdfSolidBrush brush3 = new PdfSolidBrush(Color.Green);
Step 5: Draw the text string at the specified location with the specified Brush and Font objects.
page.Canvas.DrawString("This sentence is Italic and underline", font, brush, new PointF(10, 10));
page.Canvas.DrawString("This sentence is Bold and strikeout", font2,brush2, new PointF(10, 40));
page.Canvas.DrawString("This sentence is Bold and underline",font3,brush3,new PointF(10, 70));
Step 6: Save the document to file.
pdf.SaveToFile("reslut.pdf");
Please check the effective screenshot as below:

Full codes:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace MultipleFontStyles
{
class Program
{
static void Main(string[] args)
{
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins());
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Italic | PdfFontStyle.Underline);
PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Strikeout);
PdfFont font3 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Underline);
PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.Gray);
PdfSolidBrush brush3 = new PdfSolidBrush(Color.Green);
page.Canvas.DrawString("This sentence is Italic and underline", font, brush, new PointF(10, 10));
page.Canvas.DrawString("This sentence is Bold and strikeout", font2, brush2, new PointF(10, 40));
page.Canvas.DrawString("This sentence is Bold and underline", font3, brush3, new PointF(10, 70));
pdf.SaveToFile("reslut.pdf");
}
}
}
Textbox in Excel is a special kind of graphic object, which allows users to add some text in it. Moreover, textbox can be filled with solid color, gradient, pattern or a picture so that it looks more attractive. This article presents how to add a picture fill to Excel textbox and adjust the position of the picture as well.
Code Snippets:
Step 1: Create a new instance of Workbook class and get the first worksheet.
Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0];
Step 2: Add a textbox shape into the worksheet.
ITextBoxShape shape = sheet.TextBoxes.AddTextBox(2, 2, 200, 300);
Step 3: Fill the textbox with a 160x160 pixels picture.
shape.Fill.CustomPicture(@"C:\Users\Administrator\Desktop\logo.png"); shape.Fill.FillType = ShapeFillType.Picture;
Step 4: Save the file.
workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013);
When we add a picture fill to a textbox using above code, the picture will stretch to fill the shape, like below screenshot.

If you want to prevent the image from stretching, you can adjust the size of the textbox or change the position of the picture, for example, place the image at the central position of the textbox. Following code snippet demonstrates how to center align the picture fill.
//If the height of textbox is larger than the height of original picture, set the picture into vertical center
if (textbox.Height > textbox.Fill.Picture.Height)
{
int difH = textbox.Height - textbox.Fill.Picture.Height;
(textbox.Fill as XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2);
(textbox.Fill as XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2);
}
//If the width of textbox is larger than the width of original picture, set the picture into horizontal center
if (textbox.Width > textbox.Fill.Picture.Width)
{
int difW = textbox.Width - textbox.Fill.Picture.Width;
(textbox.Fill as XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2);
(textbox.Fill as XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2);
}

Full Code:
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.Shapes;
namespace AddingPicture
{
class Program
{
static void Main(string[] args)
{
//load Excel file
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
ITextBoxShape textbox = sheet.TextBoxes.AddTextBox(2, 2, 200, 300);
textbox.Fill.CustomPicture(@"C:\Users\Administrator\Desktop\logo.png");
textbox.Fill.FillType = ShapeFillType.Picture;
//If the height of textbox is larger than the height of original picture, set the picture into vertical center
if (textbox.Height > textbox.Fill.Picture.Height)
{
int difH = textbox.Height - textbox.Fill.Picture.Height;
(textbox.Fill as XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2);
(textbox.Fill as XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2);
}
//If the width of textbox is larger than the width of original picture, set the picture into horizontal center
if (textbox.Width > textbox.Fill.Picture.Width)
{
int difW = textbox.Width - textbox.Fill.Picture.Width;
(textbox.Fill as XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2);
(textbox.Fill as XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2);
}
workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013);
}
}
}
Imports Spire.Xls
Imports Spire.Xls.Core
Imports Spire.Xls.Core.Spreadsheet.Shapes
Namespace AddingPicture
Class Program
Private Shared Sub Main(args As String())
'load Excel file
Dim workbook As New Workbook()
Dim sheet As Worksheet = workbook.Worksheets(0)
Dim textbox As ITextBoxShape = sheet.TextBoxes.AddTextBox(2, 2, 200, 300)
textbox.Fill.CustomPicture("C:\Users\Administrator\Desktop\logo.png")
textbox.Fill.FillType = ShapeFillType.Picture
'If the height of textbox is larger than the height of original picture, set the picture into vertical center
If textbox.Height > textbox.Fill.Picture.Height Then
Dim difH As Integer = textbox.Height - textbox.Fill.Picture.Height
TryCast(textbox.Fill, XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2)
TryCast(textbox.Fill, XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2)
End If
'If the width of textbox is larger than the width of original picture, set the picture into horizontal center
If textbox.Width > textbox.Fill.Picture.Width Then
Dim difW As Integer = textbox.Width - textbox.Fill.Picture.Width
TryCast(textbox.Fill, XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2)
TryCast(textbox.Fill, XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2)
End If
workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013)
End Sub
End Class
End Namespace
We can use the TextDirection enumeration in Spire.Doc.Documents namespace to set the direction of text in a word document. This enumeration contains six members: LeftToRight, TopToBottom, LeftToRightRotated, TopToBottomRotated, RightToLeft and RightToLeftRotated. The following example shows how to set text direction for all text and a part of text in a section.
Detail steps:
Step 1: Initialize a new instance of Document class and load the word document.
Document document = new Document();
document.LoadFromFile("Word.docx");
Step 2: Set text direction for all text in a section.
//Get the first section and set its text direction Section section = document.Sections[0]; section.TextDirection = TextDirection.RightToLeftRotated;
To set text direction for a part of text, we can put the text in a table and then set text direction, as shown in the following step:
Step 3: Add a new section to the document and a table to the section, get the target table cell and set text direction for it, afterwards append text to the cell.
//Add a new section to the document
Section sec = document.AddSection();
//Add a table to the new section
Table table = sec.AddTable();
//Add one row and one column to the table
table.ResetCells(1, 1);
//Get the table cell
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
table.Rows[0].Cells[0].Width = 10;
//Set text direction for the cell and append some text
cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
cell.AddParagraph().AppendText("Hello,world: vertical style");
Add a new paragraph to check if above settings will affect the text direction of other text in this section:
sec.AddParagraph().AppendText("New Paragraph");
Step 4: Save the document.
document.SaveToFile("result.docx", FileFormat.Docx);
Result:
Set text direction for all text in a section:

Set text direction for a part of text:

Full codes:
using Spire.Doc;
using Spire.Doc.Documents;
namespace Set_text_direction_in_Word
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile("Word.docx");
//Set text direction for all text in a section
Section section = document.Sections[0];
section.TextDirection = TextDirection.RightToLeftRotated;
// Set text direction for a part of text
Section sec = document.AddSection();
Table table = sec.AddTable();
table.ResetCells(1, 1);
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
table.Rows[0].Cells[0].Width = 10;
cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
cell.AddParagraph().AppendText("Hello,world: vertical style");
sec.AddParagraph().AppendText("New Paragraph");
//Save the document
document.SaveToFile("result.docx", FileFormat.Docx);
}
}
}
Track Changes in MS Word can track the revisions, corrections, changes, edits, and even suggestions and comments people make to documents. When you receive a revised document with Track Changes turned on, you can decide whether to reject the changes to keep the original content or directly accept them. This article will demonstrate how to programmatically accept or reject all tracked changes in a Word document using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Accept All Tracked Changes in a Word Document
The detailed steps are as follows:
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Accept all changes in the document using Document.AcceptChanges() method.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace AcceptTrackedChanges
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a sample Word document
doc.LoadFromFile("test.docx");
//Accept all changes in the document
doc.AcceptChanges();
//Save the result document
doc.SaveToFile("AcceptTrackedChanges.docx", FileFormat.Docx);
}
}
}

Reject All Tracked Changes in a Word document
The detailed steps are as follows.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Reject all changes in the document using Document.RejectChanges() method.
- Save the document to another file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace RejectTrackedChanges
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a sample Word document
doc.LoadFromFile("test.docx");
//Reject all changes in the document
doc.RejectChanges();
//Save the result document
doc.SaveToFile("RejectAllChanges.docx", FileFormat.Docx);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
A looping slideshow displays each slide automatically for a certain amount of time. Once the slideshow reaches the end, it repeats from the beginning. This article will introduce how to programmatically set a PowerPoint document to keep looping when presenting.
Code Snippet:
Step 1: Initialize an instance of Presentation class. Load a sample PowerPoint document to it.
Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
Step 2: Set the Boolean value of ShowLoop as true, which makes the slideshow repeat with continuous looping.
ppt.ShowLoop = true;
Step 3: Set the PowerPoint document to show animation and narration. Use slide transition timings to advance slide.
ppt.ShowAnimation = true; ppt.ShowNarration = true; ppt.UseTimings = true;
Step 4: Save the file.
ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010);
Full Code:
using Spire.Presentation;
namespace LoopPPT
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
ppt.ShowLoop = true;
ppt.ShowAnimation = true;
ppt.ShowNarration = true;
ppt.UseTimings = true;
ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010);
}
}
}
Imports Spire.Presentation
Namespace LoopPPT
Class Program
Private Shared Sub Main(args As String())
Dim ppt As New Presentation()
ppt.LoadFromFile("C:\Users\Administrator\Desktop\sample.pptx")
ppt.ShowLoop = True
ppt.ShowAnimation = True
ppt.ShowNarration = True
ppt.UseTimings = True
ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010)
End Sub
End Class
End Namespace
When the text entered in a cell is too long to be fully displayed in the current cell, the “AutoFit” feature in Excel allows you to quickly adjust the column width or row height to fit all the content and make the entire worksheet more readable. In this article, you will learn how to programmatically AutoFit the column width and row height in an Excel worksheet using Spire.XLS for .NET.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
AutoFit Column Width and Row Height in Excel
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[] property.
- Get the used range on the specified worksheet using Worksheet.AllocatedRange property.
- AutoFit column width and row height in the range using CellRange.AutoFitColumns() and CellRange.AutoFitRows() methods.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
namespace AutofitColumn
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook object
Workbook workbook = new Workbook();
//Load a sample Excel document
workbook.LoadFromFile(@"E:\Files\Test.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//AutoFit column width and row height
worksheet.AllocatedRange.AutoFitColumns();
worksheet.AllocatedRange.AutoFitRows();
//Save the result file
workbook.SaveToFile("AutoFit.xlsx", FileFormat.Version2010);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Trendline
A trendline is a line superimposed on a chart revealing the overall direction of the data. There are six different types of trendlines:
- linear
- logarithmic
- polynomial
- power
- exponential
- moving average
Add trendline for chart series
Spire.Presentation enables developers to add all types of the trendlines mentioned above by using Charts.ChartSeriesDataFormat.AddTrendLine() method and set the trendline type by using Charts.TrendlinesType enum.
Here comes to the detailed steps:
Step 1: Initialize a new instance of Presentation class and load the ppt file.
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");
Step 2: Get the target chart, add trendline for the first data series of the chart and specify the trendline type.
IChart chart = ppt.Slides[0].Shapes[0] as IChart; ITrendlines it = chart.Series[0].AddTrendLine(TrendlinesType.Linear); //Set the trendline properties to determine what should be displayed. it.displayEquation = false; it.displayRSquaredValue = false;
Step 3: Save the file.
ppt.SaveToFile("output.pptx",FileFormat.Pptx2010);
Output:

Full codes:
using Spire.Presentation;
using Spire.Presentation.Charts;
namespace Add_trendline_for_chart_series
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");
IChart chart = ppt.Slides[0].Shapes[0] as IChart;
ITrendlines it = chart.Series[0].AddTrendLine(TrendlinesType.Linear);
it.displayEquation = false;
it.displayRSquaredValue = false;
ppt.SaveToFile("output.pptx",FileFormat.Pptx2010);
}
}
}
A text box can be formatted to display number, currency, date, time, zip code, phone number, social security number, etc. Adobe Acrobat provides various built-in JavaScripts, such as AFNumber_Keystroke(2, 0, 0, 0, "$", true) and AFNumber_Format(2, 0, 0, 0, "$", true), to format and validate the input of text field. The script with Format suffix is used to format the input, the script with Keystroke suffix is used to validate the input.
However, Spire.PDF has offered corresponding methods to perform formatting and validation on text field. Here is the list of frequently used formats and corresponding methods in Spire.PDF.
| Description | Example | JavaScript | Method |
| Date | 01/31/2008 | AFDate_FormatEx("mm/dd/yyyy"); AFDate_KeystrokeEx("mm/dd/yyyy"); |
GetDateFormatString("mm/dd/yyyy"); GetDateKeystrokeString("mm/dd/yyyy"); |
| Date | 1/31/2008 | AFDate_FormatEx("m/d/yyyy"); AFDate_KeystrokeEx("m/d/yyyy"); |
GetDateFormatString("m/d/yyyy"); GetDateKeystrokeString("m/d/yyyy"); |
| Zip code | 12345 | AFSpecial_Format(0); AFSpecial_Keystroke(0); |
GetSpecialFormatString(0); GetSpecialKeystrokeString(0); |
| Zip+4 | 12345-1234 | AFSpecial_Format(1); AFSpecial_Keystroke(1); |
GetSpecialFormatString(1); GetSpecialKeystrokeString(1); |
| Phone number | (123) 456-7890 | AFSpecial_Format(2); AFSpecial_Keystroke(2); |
GetSpecialFormatString(2); GetSpecialKeystrokeString(2); |
| Money (minus sign if negative) | $12,345.00 -$12,345.00 |
AFNumber_Format(2, 0, 0, 0, "$", true); AFNumber_Keystroke(2, 0, 0, 0, "$", true); |
GetNumberFormatString(2, 0, 0, 0, "$", true); GetNumberKeystrokeString(2, 0, 0, 0, "$", true); |
| Validate | 1.5≤input value≤5.5 | AFRange_Validate(true,1.5,true,5.5) | GetRangeValidateString(true, 1.5, true, 5.5); |
This tutorial demonstrates how to create a text box and display its contents in currency format in C# and VB.NET.
Code Snippets:
Step 1: Create an object of PdfDocument and add a page to it.
PdfDocument pdf = new PdfDocument(); PdfPageBase page = pdf.Pages.Add();
Step 2: Initialize an instance of PdfTextBoxField class and set its position, border width and border style.
PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox"); textbox.Bounds = new RectangleF(10, 10, 100, 20); textbox.BorderWidth = 0.75f; textbox.BorderStyle = PdfBorderStyle.Solid;
Step 3: Set a JavaScript action to be performed when uses type a keystroke into a text field. This action can check the keystroke for validity and reject or modify it.
string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true); PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js); textbox.Actions.KeyPressed = jsAction;
Step 4: Set a JavaScript action to format the value of text field before showing it.
js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true); jsAction = new PdfJavaScriptAction(js); textbox.Actions.Format = jsAction;
Step 5: Add the text box to PDF field and save the file.
pdf.Form.Fields.Add(textbox);
pdf.SaveToFile("FormatField.pdf",FileFormat.PDF);
Output:

Full Code:
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Fields;
using System.Drawing;
namespace FormatTextboxField
{
class Program
{
static void Main(string []args)
{
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();
PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox");
textbox.Bounds = new RectangleF(10, 10, 100, 20);
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;
string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true);
PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js);
textbox.Actions.KeyPressed = jsAction;
js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true);
jsAction = new PdfJavaScriptAction(js);
textbox.Actions.Format = jsAction;
pdf.Form.Fields.Add(textbox);
pdf.SaveToFile("FormatField.pdf", FileFormat.PDF);
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Actions
Imports Spire.Pdf.Fields
Imports System.Drawing
Namespace FormatTextboxField
Class Program
Private Shared Sub Main(args As String())
Dim pdf As New PdfDocument()
Dim page As PdfPageBase = pdf.Pages.Add()
Dim textbox As New PdfTextBoxField(page, "Number-TextBox")
textbox.Bounds = New RectangleF(10, 10, 100, 20)
textbox.BorderWidth = 0.75F
textbox.BorderStyle = PdfBorderStyle.Solid
Dim js As String = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", True)
Dim jsAction As New PdfJavaScriptAction(js)
textbox.Actions.KeyPressed = jsAction
js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", True)
jsAction = New PdfJavaScriptAction(js)
textbox.Actions.Format = jsAction
pdf.Form.Fields.Add(textbox)
pdf.SaveToFile("FormatField.pdf", FileFormat.PDF)
End Sub
End Class
End Namespace