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:

How to Format Textbox Field using JavaScript in C#, VB.NET

Full Code:

[C#]
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);
        }
    }
}
[VB.NET]
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

C#: Convert Excel to ODS or ODS to Excel

2024-12-16 03:17:00 Written by Koohji

Excel, developed by Microsoft, is a widely used spreadsheet application that offers a range of features for data analysis, visualization, and management. ODS (OpenDocument Spreadsheet), on the other hand, is an open standard format for spreadsheets, which means it can be read and edited by various software applications, including LibreOffice and Apache OpenOffice.

Converting between these two formats can be necessary for compatibility, sharing, or specific feature requirements. In this article, you will learn how to convert Excel to ODS or OSD to Excel in C# 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

Convert Excel to ODS (OpenDocument Spreadsheet) in C#

You can load an Excel (.xls or .xlsx) file and then save it as an ODS file through the Workbook.SaveToFile(string fileName, FileFormat.ODS) method. The following are the detailed steps:

  • Create a Workbook instance.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Save the Excel file to ODS format using Workbook.SaveToFile(string fileName, FileFormat.ODS) method.
  • C#
using Spire.Xls;

namespace ConvertExcelToODS
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Workbook instance
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            // Save the Excel to ODS file
            workbook.SaveToFile("ToODS.ods", FileFormat.ODS);
        }
    }
}

Convert an Excel file to an ODS file

Convert ODS to Excel (XLS/XLSX) in C#

Spire.XLS for .NET also supports converting an ODS file back to Excel XLS or XLS format. The following are the detailed steps:

  • Create a Workbook instance.
  • Load an ODS file using Workbook.LoadFromFile() method.
  • Save the ODS file in XLS or XLSX format using Workbook.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
using Spire.Xls;

namespace ODSToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Workbook instance
            Workbook workbook = new Workbook();

            // Load an ODS file
            workbook.LoadFromFile("ToODS.ods");

            // Save the ODS file in XLSX format
            workbook.SaveToFile("ToExcel.xlsx", FileFormat.Version2016);

            // Save the ODS file in XLS format
            workbook.SaveToFile("ToExcel.xls", FileFormat.Version97to2003);
        }
    }
}

The output XLS and XLSX files converted from an ODS file

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.

C#/VB.NET: Split Word Documents

2022-10-27 08:57:00 Written by Koohji

In MS Word, you can split a document by manually cutting the content from the original document and pasting it into a new document. Although the task is simple, it can also be quite tedious and time-consuming especially when dealing with a long document. This article will demonstrate how to programmatically split a Word document into multiple files 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

Split a Word Document by Page Break

A Word document can contain multiple pages separated by page breaks. To split a Word document by page break, you can refer to the below steps and code.

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create a new Word document and add a section to it.
  • Traverse through all body child objects of each section in the original document and determine whether the child object is a paragraph or a table.
  • If the child object of the section is a table, directly add it to the section of new document using Section.Body.ChildObjects.Add() method.
  • If the child object of the section is a paragraph, first add the paragraph object to the section of the new document. Then traverse through all child objects of the paragraph and determine whether the child object is a page break.
  • If the child object of the paragraph is a page break, get its index and then remove the page break from its paragraph by index.
  • Save the new Word document and then repeat the above processes.
  • C#
  • VB.NET
using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace SplitByPageBreak
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document original = new Document();

            //Load a sample Word document
            original.LoadFromFile(@"E:\Files\SplitByPageBreak.docx");

            //Create a new Word document and add a section to it
            Document newWord = new Document();
            Section section = newWord.AddSection();
            int index = 0;

            //Traverse through all sections of the original document
            foreach (Section sec in original.Sections)
            {
                //Traverse through all body child objects of each section
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph para = obj as Paragraph;
                        sec.CloneSectionPropertiesTo(section);

                        //Add paragraph object in the section of original document into section of new document
                        section.Body.ChildObjects.Add(para.Clone());

                        //Traverse through all child objects of each paragraph and determine whether the object is a page break
                        foreach (DocumentObject parobj in para.ChildObjects)
                        {
                            if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                            {
                                //Get the index of page break in paragraph
                                int i = para.ChildObjects.IndexOf(parobj);

                                //Remove the page break from its paragraph
                                section.Body.LastParagraph.ChildObjects.RemoveAt(i);

                                //Save the new Word document
                                newWord.SaveToFile(String.Format("result\out-{0}.docx", index), FileFormat.Docx);
                                index++;

                                //Create a new document and add a section
                                newWord = new Document();
                                section = newWord.AddSection();

                                //Add paragraph object in original section into section of new document
                                section.Body.ChildObjects.Add(para.Clone());
                                if (section.Paragraphs[0].ChildObjects.Count == 0)
                                {
                                    //Remove the first blank paragraph
                                    section.Body.ChildObjects.RemoveAt(0);
                                }
                                else
                                {
                                    //Remove the child objects before the page break
                                    while (i >= 0)
                                    {
                                        section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                        }
                    }
                    if (obj is Table)
                    {
                        //Add table object in original section into section of new document
                        section.Body.ChildObjects.Add(obj.Clone());
                    }
                }
            }

            //Save to file
            newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);

        }
    }
}

C#/VB.NET: Split Word Documents

Split a Word Document by Section Break

In Word, a section is a part of a document that contains its own page formatting. For documents that contain multiple sections, Spire.Doc for .NET also supports splitting documents by section breaks. The detailed steps are as follows.

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Define a new Word document object.
  • Traverse through all sections of the original Word document.
  • Clone each section of the original document using Document.Sections.Clone() method.
  • Add the cloned section to the new document as a new section using Document.Sections.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Doc;

namespace SplitBySectionBreak
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document
            document.LoadFromFile(@"E:\Files\SplitBySectionBreak.docx");

            //Define a new Word document object
            Document newWord;

            //Traverse through all sections of the original Word document
            for (int i = 0; i < document.Sections.Count; i++)
            {
                newWord = new Document();

                //Clone each section of the original document and add it to the new document as new section
                newWord.Sections.Add(document.Sections[i].Clone());

                //Save the result document 
                newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
            }
        }
    }
}

C#/VB.NET: Split Word Documents

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.

We have already demonstrated how to create the excel pivot table with Spire.XLS for .NET. It enables developers to set the property of PivotFieldFormatType to set format for the Data fields on pivot table. The following code sample will show you how to set display formats for data fields in C#.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.Xls.dll in the bin folder as the reference of Visual Studio.

Firstly please check the original DataField format on PivotTable:

Set Data fields format on Excel PivotTable in C#

Step 1: Create a new Excel workbook and load from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Accessing the first Pivot table from the first worksheet.

XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

Step 4: Accessing the Data Field.

PivotDataField pivotDataField = pt.DataFields[0];

Step 5: Setting data display format by setting the property of PivotFieldFormatType as PercentageOfColumn.

pivotDataField.ShowDataAs = PivotFieldFormatType.PercentageOfColumn;

Step 6: Save the document to file.

workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);

The effective screenshot after setting the Datafield format in PivotTable:

Set Data fields format on Excel PivotTable in C#

Full codes of how to set the Datafields type in Excel Pivot Table.

using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;
namespace SetDataFieldsformat
{
    class Program
    {
     static void Main(string[] args)
{

    Workbook workbook = new Workbook();
    workbook.LoadFromFile("Sample.xlsx");

    Worksheet sheet = workbook.Worksheets[0];

    XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

    PivotDataField pivotDataField = pt.DataFields[0];

    pivotDataField.ShowDataAs = PivotFieldFormatType.PercentageOfColumn;

    workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
}


            }
        }

A PDF document encrypted with a user password legally cannot be opened without the password. We’d better detect if a document is password protected or not before we try to open it. This article presents how to determine if a PDF document is encrypted with password using Spire.PDF in C#, VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class.

PdfDocument doc = new PdfDocument();

Step 2: Load a sample PDF document.

doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

Step 3: Detect whether the document is encrypted with password or not.

bool isEncrypted = doc.IsEncrypted;
Console.WriteLine(isEncrypted);

Result:

How to detect if a PDF document is password protected in C#, VB.NET

Full Code:

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


namespace Detect
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

            bool isEncrypted = doc.IsEncrypted;
            Console.WriteLine(isEncrypted);
            Console.Read();
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace Detect
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
doc.LoadFromFile("C:\Users\Administrator\Desktop\Encrypted.pdf")

Dim isEncrypted As Boolean = doc.IsEncrypted
Console.WriteLine(isEncrypted)
Console.Read()
		End Sub
	End Class
End Namespace

Sometimes, we may need to change the zoom factor when displaying the data on the excel worksheet to fulfil our requirements. In this article, we will demonstrate how to set the zoom factor on Excel work sheet in C# with the help of Spire.XLS.

Firstly, please view the screenshot of how Microsoft Excel to set the zoom factor after click View--Zoom on the top toolbox:

How to set the Zoom Factor on Excel worksheet in C#

Spire.XLS enables developers to set the value of worksheet’s zoom property to the specific zoom factor via sheet.Zoom. Here comes to the steps of how to control the zoom factor by Spire.XLS.

Step 1: Create a new Excel workbook and load from file.

Workbook wb = new Workbook();
wb.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the Excel workbook.

Worksheet sheet = wb.Worksheets[0];

Step 3: Set the value of worksheet's zoom property to the specific zoom factor.

sheet.Zoom = 100;

Step 4: Save the document to file.

wb.SaveToFile("result.xlsx", ExcelVersion.Version2010);

Effective screenshot after setting the zoom factor:

How to set the Zoom Factor on Excel worksheet in C#

Full codes:

using Spire.Xls;
namespace Zoom
{
    class Program
    {

        static void Main(string[] args)
        {

            Workbook wb = new Workbook();
            wb.LoadFromFile("Sample.xlsx");

            Worksheet sheet = wb.Worksheets[0];
            sheet.Zoom = 100;

            wb.SaveToFile("result.xlsx", ExcelVersion.Version2010);
        }
    }
}

In Word, we can split a word document in an easiest way - open a copy of the original document, delete the sections that we don’t want and then save the remains to local drive. But doing this section by section is rather cumbersome and boring. This article will explain how we can use Spire.Doc for .NET to programmatically split a Word document into multiple documents by section break instead of copying and deleting manually.

Detail steps and code snippets:

Step 1: Initialize a new word document object and load the original word document which has two sections.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Define another new word document object.

Document newWord;

Step 3: Traverse through all sections of the original word document, clone each section and add it to a new word document as new section, then save the document to specific path.

for (int i = 0; i < document.Sections.Count; i++)
{
    newWord = new Document();
    newWord.Sections.Add(document.Sections[i].Clone());
    newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
}

Run the project and we'll get the following output:

How to split a Word document into multiple documents by section break in C#

Full codes:

using System;
using Spire.Doc;

namespace Split_Word_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Test.doc");
            Document newWord;
            for (int i = 0; i < document.Sections.Count; i++)
            {
                newWord = new Document();
                newWord.Sections.Add(document.Sections[i].Clone());
                newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
            }
        }
    }
}

Spire.PDF for .NET provides several font classes such as PdfFont, PdfTrueTypeFont and PdfCjkStandardFont which enable developers to add various fonts to PDF files. In this article we will learn how to generate fonts that support Chinese characters and use the fonts to add simplified and traditional Chinese characters to a PDF file in C# and VB.NET.

Before start, please ensure you have installed the corresponding font on system. If not, you can download it from the following link:

http://www.adobe.com/support/downloads/thankyou.jsp?ftpID=5508&fileID=5521

Detail steps and code snippets:

Step 1: Create a new PDF document and add a new page to it.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Use PdfTrueTypeFont class and PdfCjkStandardFont class to generate fonts that support simplified and traditional Chinese characters.

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 11f), true);
PdfCjkStandardFont font1 = new PdfCjkStandardFont(PdfCjkFontFamily.MonotypeSungLight, 11f);

Step 3: Use PdfCanvas.DrawString(string s, PdfFontBase font, PdfBrush brush, float x, float y) method and the generated fonts to draw Chinese characters to specified location of the PDF file.

page.Canvas.DrawString("中国", font, PdfBrushes.Red, 50, 50);
page.Canvas.DrawString("中國", font1, PdfBrushes.Red, 50, 70);

Step 4: Save the PDF file to disk.

pdf.SaveToFile("result.pdf");

Run the project and we'll get the following result PDF file:

How to add simplified and traditional Chinese characters to PDF in C#, VB.NET

Full codes:

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

namespace Add_Chinese_Characters_to_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add();
            
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 11f), true);
            PdfCjkStandardFont font1 = new PdfCjkStandardFont(PdfCjkFontFamily.MonotypeSungLight, 11f);
            page.Canvas.DrawString("中国", font, PdfBrushes.Red, 50, 50);
            page.Canvas.DrawString("中國", font1, PdfBrushes.Red, 50, 70);
            pdf.SaveToFile("result.pdf");
            System.Diagnostics.Process.Start("result.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace Add_Chinese_Characters_to_PDF
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument()
			Dim page As PdfPageBase = pdf.Pages.Add()
			Dim font As New PdfTrueTypeFont(New Font("Arial Unicode MS", 11F), True)
			Dim font1 As New PdfCjkStandardFont(PdfCjkFontFamily.MonotypeSungLight, 11F)
			page.Canvas.DrawString("中国", font, PdfBrushes.Red, 50, 50)
			page.Canvas.DrawString("中國", font1, PdfBrushes.Red, 50, 70)
			pdf.SaveToFile("result.pdf")
			System.Diagnostics.Process.Start("result.pdf")
		End Sub
	End Class
End Namespace

Generally, when we open a PDF document from a PDF viewer, it displays the first page instead of others. For some reasons, we may want to skip the first few pages and start on another page. This article will introduce how to specify a particular page when viewing a PDF document in C# and VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class and a load a sample PDF file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

Step 2: Create a PdfGoToAction which will redirect to a destination (page 2 in this case) in the current document.

PdfDestination destination = new PdfDestination(doc.Pages[1]);
PdfGoToAction action = new PdfGoToAction(destination);

Step 3: Sets the action to execute after the document is opened.

doc.AfterOpenAction = action;

Step 4: Save the file.

doc.SaveToFile("GoTo2Page.pdf",FileFormat.PDF);

Output:

The document opens at the second page.

How to open a PDF document at a specific page in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.General;

namespace OpenPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

            PdfDestination destination = new PdfDestination(doc.Pages[1]);
            PdfGoToAction action = new PdfGoToAction(destination);
            action.Destination.Zoom = 0.8F;
            doc.AfterOpenAction = action;

            doc.SaveToFile("GoTo2Page.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Actions
Imports Spire.Pdf.General

Namespace OpenPDF
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")

			Dim destination As New PdfDestination(doc.Pages(1))
			Dim action As New PdfGoToAction(destination)
			action.Destination.Zoom = 0.8F
			doc.AfterOpenAction = action

			doc.SaveToFile("GoTo2Page.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

Adding page numbers to a PDF document is not only practical but also aesthetically pleasing, as it provides a polished look akin to professionally published materials. Whether you're dealing with a digital copy of a novel, a report, or any other type of lengthy document, having page numbers can significantly improve its readability and utility. In this article, you will learn how to add page numbers to a PDF document in C# 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

PDF Coordinate System

When utilizing Spire.PDF for .NET to manipulate an existing PDF document, it's important to note that the coordinate system's origin is located at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.

Typically, page numbers are positioned within the header or footer section of a document. Therefore, it is crucial to take into account the page size and margins when determining the appropriate placement for the page numbers.

C#: Add Page Numbers to a PDF Document

Add Left-Aligned Page Numbers in the Footer in C#

In the Spire.PDF for .NET library, there are two classes available: PdfPageNumberField and PdfPageCountField. These classes allow you to retrieve and display the current page number and the total page count when they are added to a page of a PDF document. If you wish to insert text such as "Page X" or "Page X of Y", you can utilize the PdfCompositeField class, which enables you to combine the desired text with one or more fields into a single field.

The following are the steps to add left-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToLeftCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // Get the page size
            SizeF pageSize = doc.Pages[0].Size;

            // Set the location of the composite field
            compositeField.Location = new PointF(72, pageSize.Height - 45);

            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);
            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToLeftCorner.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

Add Center-Aligned Page Numbers in the Footer in C#

In order to align the page number in the footer section to the center, it is crucial to dynamically calculate the width of the text "Page X of Y." This calculation is essential as it determines the X coordinate of the page number (PdfCompositeField). To achieve center alignment, the X coordinate is calculated by subtracting the width of the page number from the page width and dividing the result by 2, as follows: (PageWidth - PageNumberWidth)/2.

The following are the steps to add center-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToCenter.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

Add Right-Aligned Page Numbers in the Footer in C#

To position the page number in the footer section's right corner, it is essential to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) is determined by subtracting the combined width of the page number and the right page margin from the page width, as follows: PageWidth - (PageNumberWidth + RightPageMargin).

Below are the steps to add right-aligned page numbers in the PDF footer in C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToRigthCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF(pageSize.Width - pageNumberSize.Width - 72, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToRigthCorner.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

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.

page 36