.NET (1322)
Children categories
Getting the coordinates of text or an image in a PDF is a useful task that allows precise referencing and manipulation of specific elements within the document. By extracting the coordinates, one can accurately identify the position of text or images on each page. This information proves valuable for tasks like data extraction, text recognition, or highlighting specific areas. This article introduces how to get the coordinate information of text or an image in 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. You can download Spire.PDF for .NET from our website or install it directly through NuGet.
PM> Install-Package Spire.PDF
Get Coordinates of Text in PDF in C#
The PdfTextFinder.Find() method provided by Spire.PDF can help us find all instances of the string to be searched in a searchable PDF document. The coordinate information of a specific instance can be obtained through the PdfTextFragment.Positions property. The following are the step to get the (X, Y) coordinates of the specified text in a PDF using Spire.PDF for .NET.
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Loop through the pages in the document.
- Create a PdfTextFinder object, and get all instances of the specified text from a page using PdfTextFinder.Find() method.
- Loop through the find results and get the coordinate information of a specific result through PdfTextFragment.Positions property.
- C#
using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Collections.Generic;
using System;
using System.Drawing;
namespace GetCoordinatesOfText
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf");
//Loop through all pages
foreach (PdfPageBase page in doc.Pages)
{
//Create a PdfTextFinder object
PdfTextFinder finder = new PdfTextFinder(page);
//Set the find options
PdfTextFindOptions options = new PdfTextFindOptions();
options.Parameter = TextFindParameter.IgnoreCase;
finder.Options = options;
//Find all instances of a specific text
List<PdfTextFragment> fragments = finder.Find("target audience");
//Loop through the instances
foreach (PdfTextFragment fragment in fragments)
{
//Get the position of a specific instance
PointF found = fragment.Positions[0];
Console.WriteLine(found);
}
}
}
}
}

Get Coordinates of an Image in PDF in C#
Spire.PDF provides the PdfImageHelper.GetImagesInfo() method to help us get all image information on a specific page. The coordinate information of a specific image can be obtained through the PdfImageInfo.Bounds property. The following are the steps to get the coordinates of an image in a PDF document using Spire.PDF for .NET.
- Create a PdfDocument object.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specific page through PdfDocument.Pages[index] property.
- Create a PdfImageHelper object, and get all image information from the page using PdfImageHelper.GetImageInfo() method.
- Get the coordinate information of a specific image through PdfImageInfo.Bounds property.
- C#
using Spire.Pdf;
using Spire.Pdf.Utilities;
namespace GetCoordinatesOfImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf");
//Get a specific page
PdfPageBase page = doc.Pages[0];
//Create a PdfImageHelper object
PdfImageHelper helper = new PdfImageHelper();
//Get image information from the page
PdfImageInfo[] images = helper.GetImagesInfo(page);
//Get X,Y coordinates of a specific image
float xPos = images[0].Bounds.X;
float yPos = images[0].Bounds.Y;
Console.WriteLine("The image is located at({0},{1})", xPos, yPos);
}
}
}

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.
Get PDF font information is the process of extracting details about the fonts used in a PDF document. This information typically includes the font name, size, type, color, and other attributes. Knowing these details can help in ensuring consistency, copyright compliance, and aesthetics of the PDF document. In this article, you will learn how to get the font information in PDF 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
Get the Fonts of Specified Text in PDF in C#
With Spire.PDF for .NET, you can find specified text and get its font formatting such as font name, size, style and color through the corresponding properties of the PdfTextFragment class. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specified page using PdfDocument.Pages[] property.
- Create a PdfTextFinder instance.
- Find the specified text using PdfTextFinder.Find() method and return a PdfTextFragment object.
- Create a StringBuilder instance to store information.
- Iterate through all found text.
- Get the found text using PdfTextFragment.Text property.
- Get the font name of the found text using PdfTextFragment.TextStates[0].FontName property.
- Get the font size of the found text using PdfTextFragment.TextStates[0].FontSize property.
- Get the font family of the found text using PdfTextFragment.TextStates[0].FontFamily property.
- Indicate whether the font is bold or faux bold (font style set to fill and stroke) using PdfTextFragment.TextStates[0].IsSimulateBold and PdfTextFragment.TextStates[0].IsItalic properties.
- Get the font color of the found text using PdfTextFragment.TextStates[0].ForegroundColor property.
- Append the font information to the StringBuilder instance using StringBuilder.AppendLine() method.
- Write to a txt file.
- C#
using Spire.Pdf;
using Spire.Pdf.Texts;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
namespace GetTextFont
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("NET Framework.pdf");
// Get the first page
PdfPageBase page = pdf.Pages[0];
// Create a PdfTextFinder instance
PdfTextFinder finds = new PdfTextFinder(page);
// Find specified text on the page
finds.Options.Parameter = TextFindParameter.None;
List<PdfTextFragment> result = finds.Find(".NET Framework");
// Create a StringBuilder instance
StringBuilder str = new StringBuilder();
// Iterate through all found text
foreach (PdfTextFragment find in result)
{
// Get the found text
string text = find.Text;
// Get the font name
string FontName = find.TextStates[0].FontName;
// Get the font size
float FontSize = find.TextStates[0].FontSize;
// Get the font family
string FontFamily = find.TextStates[0].FontFamily;
// Indicate whether the font is bold or italic
bool IsBold = find.TextStates[0].IsBold;
bool IsSimulateBold = find.TextStates[0].IsSimulateBold;
bool IsItalic = find.TextStates[0].IsItalic;
// Get the font color
Color color = find.TextStates[0].ForegroundColor;
// Append the font information to the StringBuilder instance
str.AppendLine(text);
str.AppendLine("FontName: " + FontName);
str.AppendLine("FontSize: " + FontSize);
str.AppendLine("FontFamily: " + FontFamily);
str.AppendLine("IsBold: " + IsBold);
str.AppendLine("IsSimulateBold: " + IsSimulateBold);
str.AppendLine("IsItalic: " + IsItalic);
str.AppendLine("color: " + color);
str.AppendLine(" ");
}
// Write to a txt file
File.WriteAllText("PdfFont.txt", str.ToString());
}
}
}

Get the Used Fonts in PDF in C#
Spire.PDF for .NET also provides the PdfUsedFont class to represent the fonts used in a PDF document. To get the formatting of all used fonts, you can iterate through each font and retrieve its font name, size, type and style using the corresponding properties of the PdfUsedFont class. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get all the fonts used in the PDF file using PdfDocument.UsedFonts property.
- Create a StringBuilder instance to store information.
- Iterate through the used fonts.
- Get the font name using PdfUsedFont.Name property.
- Get the font size using PdfUsedFont.Size property.
- Get the font type using PdfUsedFont.Type property.
- Get the font style using PdfUsedFont.Style property.
- Append the font information to the StringBuilder instance using StringBuilder.AppendLine() method.
- Write to a txt file
- C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;
using System.IO;
using System.Text;
namespace GetPdfFont
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.LoadFromFile("NET Framework.pdf");
// Get the used fonts in the PDF file
PdfUsedFont[] fonts = pdf.UsedFonts;
// Create a StringBuilder instance
StringBuilder str = new StringBuilder();
// Iterate through the used fonts
foreach (PdfUsedFont font in fonts)
{
// Get the font name
string name = font.Name;
// Get the font size
float size = font.Size;
// Get the font type
PdfFontType type = font.Type;
// Get the font style
PdfFontStyle style = font.Style;
// Append the font information to the StringBuilder instance
str.AppendLine("FontName: " + name + " FontSize: " + size + " FontType: " + type + " FontStyle: " + style);
}
// Write to a txt file
File.WriteAllText("PdfFontInfo.txt", str.ToString());
}
}
}

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 demonstrated how to insert textbox to Excel worksheet in C#. Starts from Spire.XLS v7.11.1, we have add a new method of chart.Shapes.AddOval(left,top,right,bottom); to enable developers to add oval shape to excel chart directly. Developers can also add the text contents to the oval shape and format the style for the oval. This article will describe clearly how to insert oval shape to Excel chart in C#.
Step 1: Create a workbook and get the first worksheet from the workbook.
Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0];
Step 2: Add a chart to the worksheet.
Chart chart = sheet.Charts.Add();
Step 3: Add oval shape to Excel chart.
var shape = chart.Shapes.AddOval(20, 60, 500,400);
Step 4: Add the text to the oval shape and set the text alignment on the shape.
shape.Text = "Oval Shape added by Spire.XLS"; shape.HAlignment = CommentHAlignType.Center; shape.VAlignment = CommentVAlignType.Center;
Step 5: Format the color for the oval shape.
((XlsOvalShape)shape).Line.ForeColor = Color.Blue; ((XlsOvalShape)shape).Fill.ForeColor = Color.Green;
Step 6: Save the document to file.
workbook.SaveToFile("Result.xlsx",ExcelVersion.Version2010);
Effective screenshot of Oval shape added to the Excel chart:

Full codes:
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.Shapes;
using System.Drawing;
namespace AddOvalShape
{
class Program
{
static void Main(string[] args)
{
{
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
Chart chart = sheet.Charts.Add();
var shape = chart.Shapes.AddOval(20, 60, 500, 400);
shape.Text = "Oval Shape added by Spire.XLS";
shape.HAlignment = CommentHAlignType.Center;
shape.VAlignment = CommentVAlignType.Center;
((XlsOvalShape)shape).Line.ForeColor = Color.Blue;
((XlsOvalShape)shape).Fill.ForeColor = Color.Green;
workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
}
}
}
}
How to Convert PowerPoint Document to SVG Images in C#, VB.NET
2016-10-24 08:38:01 Written by KoohjiSVG, short for scalable vector graphics, is a XML-based file format used to depict two-dimensional vector graphics. As SVG images are defined in XML text lines, they can be easily searched, indexed, scripted, and supported by most of the up to date web browsers. Therefore, office documents are often converted to SGV images for high fidelity viewing. Following sections will introduce how to convert PowerPoint documents to SVG images using Spire.Presentation in C# and VB.NET.
Code Snippet:
Step 1: Initialize an instance of Presentation class and load a sample PowerPoint document to it.
Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
Step 2: Convert PowerPoint document to byte array and store in a Queue object.
Queue<Byte[]> svgBytes = ppt.SaveToSVG();
Step 3: Initialize an instance of the FileStream class with the specified file path and creation mode. Dequeue the data in the Queue object and write to the stream.
int len = svgBytes.Count;
for (int i = 0; i < len; i++)
{
FileStream fs = new FileStream(string.Format("result" + "{0}.svg", i), FileMode.Create);
byte[] bytes = svgBytes.Dequeue();
fs.Write(bytes, 0, bytes.Length);
}
Output:

Full Code:
using Spire.Presentation;
using System;
using System.Collections.Generic;
using System.IO;
namespace PPTtoSVG
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
Queue<byte[]> svgBytes = ppt.SaveToSVG();
int len = svgBytes.Count;
for (int i = 0; i < len; i++)
{
FileStream fs = new FileStream(string.Format("result" + "{0}.svg", i), FileMode.Create);
byte[] bytes = svgBytes.Dequeue();
fs.Write(bytes, 0, bytes.Length);
ppt.Dispose();
}
}
}
}
Imports Spire.Presentation
Imports System.Collections.Generic
Imports System.IO
Namespace PPTtoSVG
Class Program
Private Shared Sub Main(args As String())
Dim ppt As New Presentation()
ppt.LoadFromFile("C:\Users\Administrator\Desktop\sample.pptx")
Dim svgBytes As Queue(Of [Byte]()) = ppt.SaveToSVG()
Dim len As Integer = svgBytes.Count
For i As Integer = 0 To len - 1
Dim fs As New FileStream(String.Format("result" + "{0}.svg", i), FileMode.Create)
Dim bytes As Byte() = svgBytes.Dequeue()
fs.Write(bytes, 0, bytes.Length)
ppt.Dispose()
Next
End Sub
End Class
End Namespace
SVG, short for Scalable Vector Graphics, is a web-friendly vector image format. SVG has many advantages over other image formats. One of the most significant advantages is resolution independence, which means you can resize SVG images as needed without losing image quality. Sometimes, you may need to convert Excel files to SVG for web viewing. This article will demonstrate how to programmatically convert Excel to SVG in C# and VB.NET 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 an Excel Worksheet to SVG using C# and VB.NET
Spire.XLS provides the Worksheet.SaveToSVGStream() method to convert an Excel worksheet to SVG. The detailed steps are as follows:
- Initialize an instance of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int] property.
- Initialize an instance of the FileStream class.
- Save the worksheet to SVG using Worksheet.ToSVGStream(Stream, int, int, int, int) method.
- C#
- VB.NET
using Spire.Xls;
using System.IO;
namespace ConvertWorksheetToSVG
{
class Program
{
static void Main(string[] args)
{
//Create an instance of Workbook class
Workbook workbook = new Workbook();
//Load an Excel file
workbook.LoadFromFile("Sample1.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Create an instance of FileStream class
FileStream fs = new FileStream("E:\\Program Files\\WorksheetToSVG.svg", FileMode.Create);
//Save the worksheet to SVG
sheet.ToSVGStream(fs, 0, 0, 0, 0);
fs.Flush();
fs.Close();
}
}
}

Convert an Excel Chart Sheet to SVG using C# and VB.NET
A chart sheet is a worksheet that only contains a chart. Spire.XLS allows you to convert a chart sheet to SVG by using the ChartSheet.ToSVGStream() method. The detailed steps are as follows:
- Initialize an instance of the Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific chart sheet by its index through Workbook.Chartsheets[int] property.
- Initialize an instance of the FileStream class.
- Save the chart sheet to SVG using ChartSheet.ToSVGStream(Stream) method.
- C#
- VB.NET
using Spire.Xls;
using System.IO;
namespace ConvertChartSheetToSVG
{
class Program
{
static void Main(string[] args)
{
//Create an instance of Workbook class
Workbook workbook = new Workbook();
//Load an Excel file
workbook.LoadFromFile("Sample2.xlsx");
//Get the first chart sheet
ChartSheet chartSheet = workbook.Chartsheets[0];
//Create an instance of FileStream class
FileStream fs = new FileStream("E:\\ProgramFiles\\ChartSheetToSVG.svg", FileMode.Create);
//Save the chart sheet to SVG
chartSheet.ToSVGStream(fs);
fs.Flush();
fs.Close();
}
}
}

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.
SVG (Scalable Vector Graphics) is an image file format and it has the advantage of be edited and indexed easily. It is widely used for interactivity and animation. Starts from Spire.Doc V5.8, Spire.Doc offers a method doc.SaveToFile() to enable developers to save the word document to SVG file format in C# easily. This article will focus on demonstrate how to convert word document to SVG with the help of Spire.Doc by using a simple line of code in C#.
Firstly, please view the original word document:

Step 1: Create a C# project in visual studio, then add a reference to Spire.Doc.dll and use the following namespace.
using Spire.Doc;
Step 2: Create a word instance and load the source word document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
Step 3: Save the document to SVG file.
doc.SaveToFile("result.svg", FileFormat.SVG);
After running the code, we'll get the effective screenshot of the following result SVG file from word document:

Full codes:
using Spire.Doc;
namespace wordconversion.Case
{
class WordtoSVG
{
public WordtoSVG()
{
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
doc.SaveToFile("result.svg", FileFormat.SVG);
}
}
}
Videos are common elements in PowerPoint, sometimes developers need to extract videos from PowerPoint documents and save them to disk programmatically. Spire.Presentation provides developers many flexible functions to manipulate PowerPoint documents including extract Videos. This article will explain how to achieve this task in C# and VB.NET using Spire.Presentation.
Note: Before start, please download and install Spire.Presentation correctly, after that add a reference to Spire.Presentation.dll in your project.
Detail steps:
Step 1: Instantiate an object of Presentation class and load the sample document.
Presentation presentation = new Presentation(); presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pptx");
Step 2: Loop through all shapes on the slides, find out the videos and then call VideoData.SaveToFile(string fileName) method to save them to disk.
int i = 0;
foreach (ISlide slide in presentation.Slides)
{
foreach (IShape shape in slide.Shapes)
{
if (shape is IVideo)
{
(shape as IVideo).EmbeddedVideoData.SaveToFile(string.Format(@"Video\Video-{0}.mp4",i));
i++;
}
}
}
Below are the extracted videos from the PowerPoint document:

Full code:
using Spire.Presentation;
namespace Extract_Video
{
class Program
{
static void Main(string[] args)
{
Presentation presentation = new Presentation();
presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pptx");
int i = 0;
foreach (ISlide slide in presentation.Slides)
{
foreach (IShape shape in slide.Shapes)
{
if (shape is IVideo)
{
(shape as IVideo).EmbeddedVideoData.SaveToFile(string.Format(@"Video\Video-{0}.mp4",i));
i++;
}
}
}
}
}
}
Imports Spire.Presentation
Namespace Extract_Video
Class Program
Private Shared Sub Main(args As String())
Dim presentation As New Presentation()
presentation.LoadFromFile("C:\Users\Administrator\Desktop\Sample.pptx")
Dim i As Integer = 0
For Each slide As ISlide In presentation.Slides
For Each shape As IShape In slide.Shapes
If TypeOf shape Is IVideo Then
TryCast(shape, IVideo).EmbeddedVideoData.SaveToFile(String.Format("Video\Video-{0}.mp4", i))
i += 1
End If
Next
Next
End Sub
End Class
End Namespace
Required fields force the user to fill in the selected form field. If the user attempts to submit the form while a required field is blank, an error message appears and the empty required form field is highlighted.
Using Spire.PDF, we're able to enforce a form field as "Required" or determine which fields are required in an existing PDF document. This article mainly introduce how to detect the required form fields in C# and VB.NET.
Code Snippet:
Step 1: Initialize an instance of PdfDocument class and load a sample PDF file that contains some form fields.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.pdf");
Step 2: Get all form widgets from the PDF document.
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
Step 3: Traverse the form widgets to find the form field that is required and print all results on console.
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
string fieldName = field.Name;
bool isRequired = field.Required;
if (isRequired)
{
Console.WriteLine(fieldName + " is required.");
}
}
Output:

Full Code:
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
using System;
namespace Detect
{
class Program
{
static void Main(string []args)
{
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.pdf");
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
string fieldName = field.Name;
bool isRequired = field.Required;
if (isRequired)
{
Console.WriteLine(fieldName + " is required.");
}
}
Console.ReadKey();
}
}
}
Imports Spire.Pdf
Imports Spire.Pdf.Fields
Imports Spire.Pdf.Widget
Namespace Detect
Class Program
Private Shared Sub Main(args As String())
Dim doc As New PdfDocument()
doc.LoadFromFile("C: \Users\Administrator\Desktop\PdfFormExample.pdf")
Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget)
For i As Integer = 0 To formWidget.FieldsWidget.List.Count - 1
Dim field As PdfField = TryCast(formWidget.FieldsWidget.List(i), PdfField)
Dim fieldName As String = field.Name
Dim isRequired As Boolean = field.Required
If isRequired Then
Console.WriteLine(fieldName & Convert.ToString(" is required."))
End If
Next
Console.ReadKey()
End Sub
End Class
End Namespace
A pie chart helps show proportions and percentages between categories, by dividing a circle into proportional segments. This article will introduce how to create a pie chart that looks like the below screenshot in PowerPoint document using Spire.Presentation in C#.

Code Snippets:
Step 1: Initialize an instance of Presentation class.
Presentation ppt = new Presentation();
Step 2: Insert a Pie chart to the first slide by calling the AppendChart() method and set the chart title.
RectangleF rect1 = new RectangleF(40, 100, 550, 320); IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.Pie, rect1, false); chart.ChartTitle.TextProperties.Text = "Sales by Quarter"; chart.ChartTitle.TextProperties.IsCentered = true; chart.ChartTitle.Height = 30; chart.HasTitle = true;
Step 3: Define some data.
string[] quarters = new string[] { "1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr" };
int[] sales = new int[] { 210, 320, 180, 500 };
Step 4: Append data to ChartData, which represents a data table where the chart data is stored.
chart.ChartData[0, 0].Text = "Quarters";
chart.ChartData[0, 1].Text = "Sales";
for (int i = 0; i < quarters.Length; ++i)
{
chart.ChartData[i + 1, 0].Value = quarters[i];
chart.ChartData[i + 1, 1].Value = sales[i];
}
Step 5: Set category labels, series label and series data.
chart.Series.SeriesLabel = chart.ChartData["B1", "B1"]; chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"]; chart.Series[0].Values = chart.ChartData["B2", "B5"];
Step 6: Add data points to series and fill each data point with different color.
for (int i = 0; i < chart.Series[0].Values.Count; i++)
{
ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
cdp.Index = i;
chart.Series[0].DataPoints.Add(cdp);
}
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.RosyBrown;
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.LightBlue;
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.LightPink;
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.MediumPurple;
Step 7: Set the data labels to display label value and percentage value.
chart.Series[0].DataLabels.LabelValueVisible = true; chart.Series[0].DataLabels.PercentValueVisible = true;
Step 8: Save the file.
ppt.SaveToFile("PieChart.pptx", FileFormat.Pptx2010);
Full Code:
using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System.Drawing;
namespace CreatePieChartInPowerPoint
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
RectangleF rect1 = new RectangleF(40, 100, 550, 320);
IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.Pie, rect1, false);
chart.ChartTitle.TextProperties.Text = "Sales by Quarter";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;
chart.HasTitle = true;
string[] quarters = new string[] { "1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr" };
int[] sales = new int[] { 210, 320, 180, 500 };
chart.ChartData[0, 0].Text = "Quarters";
chart.ChartData[0, 1].Text = "Sales";
for (int i = 0; i < quarters.Length; ++i)
{
chart.ChartData[i + 1, 0].Value = quarters[i];
chart.ChartData[i + 1, 1].Value = sales[i];
}
chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];
chart.Series[0].Values = chart.ChartData["B2", "B5"];
for (int i = 0; i < chart.Series[0].Values.Count; i++)
{
ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
cdp.Index = i;
chart.Series[0].DataPoints.Add(cdp);
}
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.RosyBrown;
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.LightBlue;
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.LightPink;
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.MediumPurple;
chart.Series[0].DataLabels.LabelValueVisible = true;
chart.Series[0].DataLabels.PercentValueVisible = true;
ppt.SaveToFile("PieChart.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("PieChart.pptx");
}
}
}
Hyperlinks in Word documents are clickable links that allow readers to navigate to a website or another document. While hyperlinks can provide valuable supplemental information, sometimes they can also be distracting or unnecessarily annoying, so you may want to remove them. In this article, you will learn how to remove hyperlinks from a Word document in C# and VB.NET 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
Remove All the Hyperlinks in a Word Document
To delete all hyperlinks in a Word document at once, you'll need to find all the hyperlinks in the document and then create a custom method FlattenHyperlinks() to flatten them. The following are the detailed steps.
- Create a Document object.
- Load a sample Word document using Document.LoadFromFile() method.
- Find all the hyperlinks in the document using custom method FindAllHyperlinks().
- Loop through the hyperlinks and flatten all of them using custom method FlattenHyperlinks().
- Save the result document using Document.SaveToFile() method.
- C#
- VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;
using Spire.Doc.Fields;
namespace removeWordHyperlink
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a sample Word document
doc.LoadFromFile("Hyperlink.docx");
//Find all hyperlinks
List<Field> hyperlinks = FindAllHyperlinks(doc);
//Flatten all hyperlinks
for (int i = hyperlinks.Count - 1; i >= 0; i--)
{
FlattenHyperlinks(hyperlinks[i]);
}
//Save the result document
doc.SaveToFile("RemoveHyperlinks.docx", FileFormat.Docx);
}
//Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
private static List<Field> FindAllHyperlinks(Document document)
{
List<Field> hyperlinks = new List<Field>();
//Iterate through the items in the sections to find all hyperlinks
foreach (Section section in document.Sections)
{
foreach (DocumentObject sec in section.Body.ChildObjects)
{
if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
{
foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
{
if (para.DocumentObjectType == DocumentObjectType.Field)
{
Field field = para as Field;
if (field.Type == FieldType.FieldHyperlink)
{
hyperlinks.Add(field);
}
}
}
}
}
}
return hyperlinks;
}
//Create a method FlattenHyperlinks() to flatten the hyperlink field
private static void FlattenHyperlinks(Field field)
{
int ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
int fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
Paragraph sepOwnerPara = field.Separator.OwnerParagraph;
int sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
int sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
int endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
int endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);
FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);
field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);
for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
{
if (i == sepOwnerParaIndex && i == ownerParaIndex)
{
for (int j = sepIndex; j >= fieldIndex; j--)
{
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
}
else if (i == ownerParaIndex)
{
for (int j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--)
{
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
}
else if (i == sepOwnerParaIndex)
{
for (int j = sepIndex; j >= 0; j--)
{
sepOwnerPara.ChildObjects.RemoveAt(j);
}
}
else
{
field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
}
}
}
//Create a method FormatFieldResultText() to remove the font color and underline format of the hyperlinks
private static void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
{
for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
{
Paragraph para = ownerBody.ChildObjects[i] as Paragraph;
if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
{
for (int j = sepIndex + 1; j < endIndex; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else if (i == sepOwnerParaIndex)
{
for (int j = sepIndex + 1; j < para.ChildObjects.Count; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else if (i == endOwnerParaIndex)
{
for (int j = 0; j < endIndex; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
else
{
for (int j = 0; j < para.ChildObjects.Count; j++)
{
FormatText(para.ChildObjects[j] as TextRange);
}
}
}
}
//Create a method FormatText() to change the color of the text to black and remove the underline
private static void FormatText(TextRange tr)
{
//Set the text color to black
tr.CharacterFormat.TextColor = Color.Black;
//Set the text underline style to none
tr.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
}
}
}

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.