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.

Spire.Presentation for .NET provides two flexible methods: RemoveNode() and RemoveNodeByPosition() for developers to remove nodes from SmartArt. In this article, we will learn how to remove a specific node by position from SmartArt in PowerPoint using the RemoveNodeByPosition() method.

Below is the screenshot of the original SmartArt:

How to remove a specific node by position from SmartArt in PowerPoint

Detail steps:

Step 1: Create a new instance of Presentation class and load the PPT file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("SmartArt.pptx");

Step 2: Get the SmartArt and collect nodes.

ISmartArt smartart = presentation.Slides[0].Shapes[0] as ISmartArt;
ISmartArtNodeCollection nodes = smartart.Nodes;

Step 3: Call nodes.RemoveNodeByPosition(int position) method to remove the specific node by position.

nodes.RemoveNodeByPosition(0);

Step 4: Save the file to disk.

presentation.SaveToFile("RemoveNodes.pptx", FileFormat.Pptx2010);

Running the project, we'll get the following result SmartArt:

How to remove a specific node by position from SmartArt in PowerPoint

Full codes:

[C#]
using Spire.Presentation;
using Spire.Presentation.Diagrams;

namespace Remove_Node_from_SmartArt_in_PowerPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("SmartArt.pptx");

            ISmartArt smartart = presentation.Slides[0].Shapes[0] as ISmartArt;
            ISmartArtNodeCollection nodes = smartart.Nodes;

            nodes.RemoveNodeByPosition(0);

            presentation.SaveToFile("RemoveNodes.pptx", FileFormat.Pptx2010);
        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports Spire.Presentation.Diagrams

Namespace Remove_Node_from_SmartArt_in_PowerPoint
	Class Program
		Private Shared Sub Main(args As String())
			Dim presentation As New Presentation()
			presentation.LoadFromFile("SmartArt.pptx")

			Dim smartart As ISmartArt = TryCast(presentation.Slides(0).Shapes(0), ISmartArt)
			Dim nodes As ISmartArtNodeCollection = smartart.Nodes

			nodes.RemoveNodeByPosition(0)

			presentation.SaveToFile("RemoveNodes.pptx", FileFormat.Pptx2010)
		End Sub
	End Class
End Namespace

Spire.PDF supports to save the PDF files into different image file formats, such as BMP, JPG, PNG, GIF and TIFF. It also supports to save the PDF files as the Enhanced Metafile (EMF) image file format. This article will demonstrate how to save the PDF file as the EMF image file format in C#. With the help of Spire.PDF, we only need three lines of codes to finish the conversion function.

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

Here comes to the steps of how to export the PDF file to EMF in C#:

Step 1: Create a new PDF document and load from file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("sample.pdf");

Step 2: Call to use the SaveAsImage method to save all the PDF pages as System.Drawing.Imaging.ImageFormat.Emf file format.

for (int i = 0; i < doc.Pages.Count; i++)
{
    String fileName = String.Format("Sample-img-{0}.emf", i);
    using (Image image = doc.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300))
     {
       image.Save(fileName, System.Drawing.Imaging.ImageFormat.Emf);
     }

}

Effective screenshot:

Covert PDF to EMF image file format in C#

Full codes:

using Spire.Pdf;
using System;
using System.Drawing;

namespace ConvertPDFtoEMF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("sample.pdf");

            for (int i = 0; i < doc.Pages.Count; i++)
            {
              using (Image image = doc.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300))
               {
                 image.Save(fileName, System.Drawing.Imaging.ImageFormat.Emf);
               }

            }
        }
    }
}

Sometimes, we may need to change the zoom factor when displaying a PDF file to fulfil our requirements. In this article, we will demonstrate how to open a PDF file at a specific zoom factor/percentage (such as default, 100 percent or any other zoom factors as required) by using Spire.PDF for .NET.

Now, please check the original zoom factor of the PDF file as below picture:

How to open a PDF file at a specific zoom factor/percentage in C#, VB.NET

Then refer to the following detail steps:

Step 1: Create a new instance of PdfDocument class, load the original PDF file and get its first page.

PdfDocument pdf = new PdfDocument("Stories.pdf");         
PdfPageBase page = pdf.Pages[0];

Step 2: Create a new PdfDestination object using the PdfDestination(PdfPageBase page, PointF location) class which has two parameters: the page and the page display location. Then set the value of its zoom property to the specific zoom factor/percentage.

PdfDestination dest = new PdfDestination(page, new PointF(-40f, -40f));
// Here we set its zoom factor to 100%. If you want to set the zoom factor to default, please set the value of zoom property to 0f.
dest.Zoom = 1f;

Step 3: Create a new instance of PdfGoToAction class and enable the zoom factor resetting action to be executed when the PDF file is opened.

PdfGoToAction gotoaction = new PdfGoToAction(dest);
pdf.AfterOpenAction = gotoaction;

Step 4: Save the PDF file.

pdf.SaveToFile("result.pdf");

The result zoom factor of the PDF file:

How to open a PDF file at a specific zoom factor/percentage in C#, VB.NET

Full codes:

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

namespace Set_the_zoom_factor
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument("Stories.pdf");         
            PdfPageBase page = pdf.Pages[0];
            PdfDestination dest = new PdfDestination(page, new PointF(-40f, -40f));
            dest.Zoom = 1f;
            PdfGoToAction gotoaction = new PdfGoToAction(dest);
            pdf.AfterOpenAction = gotoaction;
            pdf.SaveToFile("result.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Actions
Imports Spire.Pdf.General
Imports System.Drawing

Namespace Set_the_zoom_factor
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument("Stories.pdf")
			Dim page As PdfPageBase = pdf.Pages(0)
			Dim dest As New PdfDestination(page, New PointF(-40F, -40F))
			dest.Zoom = 1F
			Dim gotoaction As New PdfGoToAction(dest)
			pdf.AfterOpenAction = gotoaction
			pdf.SaveToFile("result.pdf")
		End Sub
	End Class
End Namespace

By default, when we insert an image to a cell, the image automatically be placed at top left corner. If there are some text in the same cell, then the text will be covered by the image. To avoid the problem, we need to vertically or horizontally align the picture. This article focuses on how to align a picture within a cell using Spire.XLS with C#, VB.NET.

Code Snippet:

Step 1: Create an object of Workbook and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Insert an image to the specific cell using Pictures.Add(int topRow, int leftColumn, string filename) method.

string picPath = @"C:\Users\Administrator\Desktop\scenery.jpg";
ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath);

Step 3: Adjust the column width and row height so that the cell can contain the picture.

sheet.Columns[0].ColumnWidth = 50;
sheet.Rows[0].RowHeight = 150;

Step 4: Vertically and horizontally align the image by setting values for LeftColumnOffset and TopRowOffset properties.

picture.LeftColumnOffset = 100;
picture.TopRowOffset = 25;

Step 5: Save the file.

wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013);

Output:

How to Align a Picture within a Cell in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
namespace AlignPicture
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook wb = new Workbook();
            Worksheet sheet = wb.Worksheets[0];

            sheet.Range["A1"].Text = "Align Picture Within A Cell:";
            sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Top;

            string picPath = @"C:\Users\Administrator\Desktop\scenery.jpg";
            ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath);

            sheet.Columns[0].ColumnWidth = 50;
            sheet.Rows[0].RowHeight = 150;

            picture.LeftColumnOffset = 100;
            picture.TopRowOffset = 25;

            wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace AlignPicture
	Class Program
		Private Shared Sub Main(args As String())
			Dim wb As New Workbook()
			Dim sheet As Worksheet = wb.Worksheets(0)

			sheet.Range("A1").Text = "Align Picture Within A Cell:"
			sheet.Range("A1").Style.VerticalAlignment = VerticalAlignType.Top

			Dim picPath As String = "C:\Users\Administrator\Desktop\scenery.jpg"
			Dim picture As ExcelPicture = sheet.Pictures.Add(1, 1, picPath)

			sheet.Columns(0).ColumnWidth = 50
			sheet.Rows(0).RowHeight = 150

			picture.LeftColumnOffset = 100
			picture.TopRowOffset = 25

			wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013)
		End Sub
	End Class
End Namespace

The table of contents plays a critical role in enhancing the readability and navigability of a document. It provides readers with a clear overview of the document's structure and enables them to quickly locate and access specific sections or information they are interested in. This can be especially valuable for longer documents, such as reports, books, or academic papers, where readers may need to refer back to specific sections or chapters multiple times. In this article, we'll explore how to create a table of contents in a PDF document 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Create a Table of Contents in PDF in C# and VB.NET

A table of contents mainly includes the TOC title (e.g. Table of Contents), TOC content, page numbers, and actions that will take you to the target pages when clicked on. To create a table of contents in PDF using Spire.PDF for .NET, you can follow these steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the page count of the document using PdfDocument.Pages.Count property.
  • Insert a new page into the PDF document as the first page using PdfDocument.Pages.Insert(0) method.
  • Draw the TOC title, TOC content, and page numbers on the page using PdfPageBase.Canvas.DrawString() method.
  • Create actions using PdfActionAnnotation class and add the actions to the page using PdfNewPage.Annotations.Add() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;

namespace TableOfContents
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the PdfDocument class
            PdfDocument doc = new PdfDocument();
            //Load a PDF document
            doc.LoadFromFile("Sample.PDF");

            //Get the page count of the document
            int pageCount = doc.Pages.Count;

            //Insert a new page into the pdf document as the first page
            PdfPageBase tocPage = doc.Pages.Insert(0);

            //Draw TOC title on the new page
            string title = "Table of Contents";
            PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Arial", 20, FontStyle.Bold));
            PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            PointF location = new PointF(tocPage.Canvas.ClientSize.Width / 2, titleFont.MeasureString(title).Height + 10);
            tocPage.Canvas.DrawString(title, titleFont, PdfBrushes.CornflowerBlue, location, centerAlignment);

            //Draw TOC content on the new page
            PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("Arial", 14));
            String[] titles = new String[pageCount];
            for (int i = 0; i < titles.Length; i++)
            {
                titles[i] = string.Format("This is page {0}", i + 1);
            }
            float y = titleFont.MeasureString(title).Height + 10;
            float x = 0;

            //Draw page numbers of the target pages on the new page
            for (int i = 1; i <= pageCount; i++)
            {
                string text = titles[i - 1];
                SizeF titleSize = titlesFont.MeasureString(text);

                PdfPageBase navigatedPage = doc.Pages[i];

                string pageNumText = (i + 1).ToString();
                SizeF pageNumTextSize = titlesFont.MeasureString(pageNumText);
                tocPage.Canvas.DrawString(text, titlesFont, PdfBrushes.CadetBlue, 0, y);
                float dotLocation = titleSize.Width + 2 + x;
                float pageNumlocation = tocPage.Canvas.ClientSize.Width - pageNumTextSize.Width;
                for (float j = dotLocation; j < pageNumlocation; j++)
                {
                    if (dotLocation >= pageNumlocation)
                    {
                        break;
                    }
                    tocPage.Canvas.DrawString(".", titlesFont, PdfBrushes.Gray, dotLocation, y);
                    dotLocation += 3;
                }
                tocPage.Canvas.DrawString(pageNumText, titlesFont, PdfBrushes.CadetBlue, pageNumlocation, y);

                //Add actions that will take you to the target pages when clicked on to the new page
                location = new PointF(0, y);
                RectangleF titleBounds = new RectangleF(location, new SizeF(tocPage.Canvas.ClientSize.Width, titleSize.Height));
                PdfDestination Dest = new PdfDestination(navigatedPage, new PointF(-doc.PageSettings.Margins.Top, -doc.PageSettings.Margins.Left));
                PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest));
                action.Border = new PdfAnnotationBorder(0);
                (tocPage as PdfNewPage).Annotations.Add(action);
                y += titleSize.Height + 10;
            }

            //Save the result pdf document
            doc.SaveToFile("AddTableOfContents.pdf");
            doc.Close();
        }
    }
}

C#/VB.NET: Create a Table of Contents (TOC) in PDF

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.

Sometimes we may need to re-encrypt the document whose password has been or is at the risk of being leaked out. This article will show you how to load an encrypted PowerPoint document and modify its password using Spire.Presentation.

Code Snippet:

Step 1: Create an object of Presentation class.

Presentation presentation = new Presentation();

Step 2: Load an encrypted PowerPoint document into the Presentation object.

presentation.LoadFromFile("Encrypted.pptx",FileFormat.Pptx2010, "oldPassword");

Step 3: Remove the encryption.

presentation.RemoveEncryption();

Step 4: Protect the document by setting a new password.

presentation.Protect("newPassword");

Step 5: Save the file.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

Full Code:

[C#]
using Spire.Presentation;
namespace ModifyPassword
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("Encrypted.pptx", FileFormat.Pptx2010, "oldPassword");

            presentation.RemoveEncryption();
            presentation.Protect("newPassword");

            presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

        }
    }
}
[VB.NET]
Imports Spire.Presentation
Namespace ModifyPassword

	Class Program

		Private Shared Sub Main(args As String())
			Dim presentation As New Presentation()
			presentation.LoadFromFile("Encrypted.pptx", FileFormat.Pptx2010, "oldPassword")

			presentation.RemoveEncryption()
			presentation.Protect("newPassword")

			presentation.SaveToFile("result.pptx", FileFormat.Pptx2010)

		End Sub
	End Class
End Namespace

Spire.Presentation as a powerful PowerPoint library, enables developers to create SmartArt, add text to SmartArt and format SmartArt in a flexible way (Reference: How to Create and Format SmartArt in PowerPoint in C#, VB.NET). In this article, we will further introduce how to extract text from SmartArt in PowerPoint in C# and VB.NET by using Spire.Presentation for .NET.

Please look at the appearance of the sample PPT file first:

How to Extract Text from SmartArt in PowerPoint in C#, VB.NET

Detail steps and code snippets are as below:

Step 1: Create a new instance of Presentation class and load the sample PPT file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");

Step 2: Create a new instance of StringBulider class, traverse through all the slides of the PPT file, find the SmartArt shapes, and then extract text from SmartArt shape Nodes and append to the StringBuilder object.

StringBuilder st = new StringBuilder();
for (int i = 0; i < ppt.Slides.Count; i++)
{
    for (int j = 0; j < ppt.Slides[i].Shapes.Count; j++)
    {
        if (ppt.Slides[i].Shapes[j] is ISmartArt)
        {
            ISmartArt smartArt = ppt.Slides[i].Shapes[j] as ISmartArt;
            for (int k = 0; k < smartArt.Nodes.Count; k++)
            {
                st.Append(smartArt.Nodes[k].TextFrame.Text);
            }
        }
    }
}

Step 3: Create a new text file and write the extracted text to the text file.

File.WriteAllText("Result.txt", st.ToString());

The result text file:

How to Extract Text from SmartArt in PowerPoint in C#, VB.NET

Full codes:

[C#]
using System.IO;
using System.Text;
using Spire.Presentation;
using Spire.Presentation.Diagrams;

namespace Extract_text_from_SmartArt_in_PPT
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            StringBuilder st = new StringBuilder();
            for (int i = 0; i < ppt.Slides.Count; i++)
            {
                for (int j = 0; j < ppt.Slides[i].Shapes.Count; j++)
                {
                    if (ppt.Slides[i].Shapes[j] is ISmartArt)
                    {
                        ISmartArt smartArt = ppt.Slides[i].Shapes[j] as ISmartArt;
                        for (int k = 0; k < smartArt.Nodes.Count; k++)
                        {
                            st.Append(smartArt.Nodes[k].TextFrame.Text);
                        }
                    }
                }
            }
            File.WriteAllText("Result.txt", st.ToString());
       }
    }
}
[VB.NET]
Imports System.IO
Imports System.Text
Imports Spire.Presentation
Imports Spire.Presentation.Diagrams

Namespace Extract_text_from_SmartArt_in_PPT
	Class Program
		Private Shared Sub Main(args As String())
			Dim ppt As New Presentation()
			ppt.LoadFromFile("Sample.pptx")

			Dim st As New StringBuilder()
			For i As Integer = 0 To ppt.Slides.Count - 1
				For j As Integer = 0 To ppt.Slides(i).Shapes.Count - 1
					If TypeOf ppt.Slides(i).Shapes(j) Is ISmartArt Then
						Dim smartArt As ISmartArt = TryCast(ppt.Slides(i).Shapes(j), ISmartArt)
						For k As Integer = 0 To smartArt.Nodes.Count - 1							st.Append(smartArt.Nodes(k).TextFrame.Text)
						Next
					End If
				Next
			Next
			File.WriteAllText("Result.txt", st.ToString())
		End Sub
	End Class
End Namespace

Draw right to left text on PDF in C#

2016-06-28 09:07:38 Written by Koohji

With the help of Spire.PDF, developers can easily draw texts on the PDF files in C#. We have already introduced how to draw text in PDF with different styles. Usually the texts are left to right format, for some languages, such as Hebrew, Arabic, etc. the texts are from right to left. Spire.PDF offers a property to enable developers to set RightToLeft as true to draw right to left text on PDF in C#. Here comes to the steps of how to draw the Hebrew texts from right to left.

Step 1: Define the text string in Hebrew:

string value = "וַיֹּאמֶר אֱלֹהִים, יְהִי אוֹר; וַיְהִי-אוֹר.";

Step 2: Create a new PDF document.

PdfDocument doc = new PdfDocument();

Step 3: Add a new page to the PDF document.

PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins());

Step 4: Set the font and position for the text.

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Alef-Regular.ttf", 16f, FontStyle.Bold), true);
RectangleF labelBounds = new RectangleF(20, 20, 400, font.Height);

Step 5: Draw the text and set the value to indicate the text direction mode.

page.Canvas.DrawString(value, font, PdfBrushes.Black, labelBounds, new PdfStringFormat() { RightToLeft = true });

Step 6: Save the document to file.

doc.SaveToFile("result.pdf");

Effective screenshot:

How to draw right to left text on PDF in C#

Full codes:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;


namespace RightToLeftText
{
    class Program
    {
        static void Main(string[] args)
        {
            string value = "וַיֹּאמֶר אֱלֹהִים, יְהִי אוֹר; וַיְהִי-אוֹר.";
            PdfDocument doc = new PdfDocument();

            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins());

            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Alef-Regular.ttf", 16f, FontStyle.Bold), true);

            RectangleF labelBounds = new RectangleF(20, 20, 400, font.Height);
            page.Canvas.DrawString(value, font, PdfBrushes.Black, labelBounds, new PdfStringFormat() { RightToLeft = true });

            labelBounds = new RectangleF(20, 50, 400, font.Height);
            page.Canvas.DrawString(value, font, PdfBrushes.Black, labelBounds, new PdfStringFormat() { RightToLeft = false });

            doc.SaveToFile("result.pdf");
        }
    }
}

When working with spreadsheets, you may find that certain cells contain combined information that need to be split for further sorting, filtering, or analyzing. MS Excel provides the “Text to Columns” feature to help users handle such situation, but manually processing large datasets is tedious and error prone. Using Spire.XLS, a robust .NET library, you can automate splitting data into columns efficiently.

This article will guide you through the process of splitting Excel data into multiple columns with C#, saving you time and ensuring accuracy.

Why Use Spire.XLS for Splitting Excel Data?

  • No Office Dependency: Manipulate Excel files without installing Microsoft Office.
  • Rich Features: Beyond splitting data, Spire.XLS also allows to edit, format, or export split data to other formats.
  • .NET Integration: Seamlessly embed Excel automation into .NET applications.

How to Install the .NET Excel Library?

To follow along with the examples in this article, you'll need to have the Spire.XLS for .NET library installed. The product package can be downloaded from the official website and then imported manually. Or you can install it directly via NuGet:

PM> Install-Package Spire.XLS

Split Excel Data into Multiple Columns with C# (Steps & Code)

With Spire.XLS, you can first retrieve the content in a cell, then split the cell content based on specific delimiter, and finally write the split data into different columns. The detailed steps are as follows:

  • Load Excel and get a worksheet.
    • Create a Workbook object and use its LoadFromFile() method to load an Excel file.
    • Access a specified worksheet through the Workbook.Worksheets[index] property.
  • Retrieve and split cell data.
    • Iterate through each row in the sheet.
    • Access a specified cell and then get its content using the CellRange.Text property.
    • Call the string.Split(params char[] separator) method to split the content based on a specified separator (e.g., comma, space, semicolon, etc.).
  • Write data into multiple columns and save.
    • Iterate through each split data.
    • Write the split data into different columns.
    • Save the modified workbook to a new file using the Workbook.SaveToFile() method.

Below is the sample code:

  • C#
using Spire.Xls;

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

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

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Loop through each row in the worksheet
            for (int i = 0; i < sheet.LastRow; i++)
            {
                // Get the text of the first cell in the current row
                string cellText = sheet.Range[i + 1, 1].Text;

                // Split the text by comma
                string[] splitText = cellText.Split(',');

                // Iterate through each split value
                for (int j = 0; j < splitText.Length; j++)
                {
                    // Write the split data into different columns
                    sheet.Range[i + 1, j + 3].Text = splitText[j];
                }
            }

            // Autofit column widths
            sheet.AllocatedRange.AutoFitColumns();

            // Save the result file
            workbook.SaveToFile("SplitExcelData.xlsx", ExcelVersion.Version2016);
        }
    }
}

Split Excel data in one column into multiple columns

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

Conclusion

Splitting text into columns in Excel using C# streamlines data processing and reduces the risk of errors. With Spire.XLS, you can automate complex tasks while maintaining data integrity, making data management easier.

page 37