How to keep high quality image when convert XPS to PDF in C#
We have already had an article of showing how to convert the XPS files into PDF file. Starts from Spire.PDF V3.8.68, it newly supports to keep the high quality image on the resulted PDF file from the XPS document. Spire.PDF offers a property of pdf.UseHighQualityImage to set the image quality before loading the original XPS file. This article will focus on demonstrate how to save image with high quality for the conversion from XPS to PDF.
Here comes to the code snippets:
Step 1: Create a PDF instance.
PdfDocument pdf = new PdfDocument();
Step 2: Set the value of UseHighQualityImage as true to use the high quality image when convert XPS to PDF.
pdf.ConvertOptions.SetXpsToPdfOptions(true);
Step 3: Load the XPS document by use either the method of pdf.LoadFromFile() or pdf.LoadFromXPS().
pdf.LoadFromFile("Sample.xps",FileFormat.XPS);
Step 4: Save the document to file.
pdf.SaveToFile("result.pdf");
Effective screenshot of the high quality image after saving XPS as PDF file format:

Full codes:
using Spire.Pdf;
namespace ConvertXPStoPDF
{
class Program
{
static void Main(string[] args)
{
PdfDocument pdf = new PdfDocument();
pdf.ConvertOptions.SetXpsToPdfOptions(true);
pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
//pdf.LoadFromXPS("Sample.xps");
pdf.SaveToFile("result.pdf", FileFormat.PDF);
}
}
}
C#: Get Coordinates of Text or an Image in PDF
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.
C#: Get the Font Information in PDF
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.
C#/VB.NET: Convert PDF to SVG
SVG (Scalable Vector Graphics) is an image file format used for rendering two-dimensional images on the web. Comparing with other image file formats, SVG has many advantages such as supporting interactivity and animation, allowing users to search, index, script, and compress/enlarge images without losing quality. Occasionally, you may need to convert PDF files to SVG file format, and this article will demonstrate how to accomplish this task using Spire.PDF for .NET.
- Convert a PDF File to SVG in C#/VB.NET
- Convert Selected PDF Pages to SVG in C#/VB.NET
- Convert a PDF File to SVG with Custom Width and Height in C#/VB.NET
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Convert a PDF File to SVG in C#/VB.NET
Spire.PDF for .NET offers the PdfDocument.SaveToFile(String, FileFormat) method to convert each page in a PDF file to a single SVG file. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Convert the PDF file to SVG using PdfDocument.SaveToFile(String, FileFormat) method.
- C#
- VB.NET
using Spire.Pdf;
namespace ConvertPDFtoSVG
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF file
document.LoadFromFile("input.pdf");
//Convert PDF to SVG
document.SaveToFile("PDFtoSVG.svg", FileFormat.SVG);
}
}
}

Convert Selected PDF Pages to SVG in C#/VB.NET
The PdfDocument.SaveToFile(String, Int32, Int32, FileFormat) method allows you to convert the specified pages in a PDF file to SVG files. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Convert selected PDF pages to SVG using PdfDocument.SaveToFile(String, Int32, Int32, FileFormat) method.
- C#
- VB.NET
using Spire.Pdf;
namespace PDFPagetoSVG
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF file
doc.LoadFromFile("input.pdf");
//Convert selected PDF pages to SVG
doc.SaveToFile("PDFPagetoSVG.svg", 1, 2, FileFormat.SVG);
}
}
}

Convert a PDF File to SVG with Custom Width and Height in C#/VB.NET
The PdfConvertOptions.SetPdfToSvgOptions() method offered by Spire.PDF for .NET allows you to specify the width and height of output SVG file. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Set PDF convert options using PdfDocument.ConvertOptions property.
- Specify the width and height of output SVG file using PdfConvertOptions.SetPdfToSvgOptions() method.
- Convert the PDF file to SVG using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
namespace PDFtoSVG
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF file
document.LoadFromFile("input.pdf");
//Specify the width and height of output SVG file
PdfToSvgConverter converter = new PdfToSvgConverter(inputFile);
converter.SvgOptions.ScaleX = (float)0.5;
converter.SvgOptions.ScaleY = (float)0.5;
converter.Convert(outputFile);
//Convert PDF to SVG
document.SaveToFile("result.svg", FileFormat.SVG);
}
}
}

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

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Add Page Numbers to a PDF Document
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.
- Add Left-Aligned Page Numbers in the Footer in C#
- Add Center-Aligned Page Numbers in the Footer in C#
- Add Right-Aligned Page Numbers in the Footer in C#
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.

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();
}
}
}

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();
}
}
}

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();
}
}
}

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.
Covert PDF to EMF image file format in C#
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:

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);
}
}
}
}
}
C#/VB.NET: Convert Excel Data to Word Tables with Formatting
If you're creating a written report on a company's monthly expenditures, you might need to include a spreadsheet to show the financial figures and make them easier to read. This article demonstrates how to convert Excel data into a Word table maintaining the formatting in C# and VB.NET using Spire.Office for .NET.
Install Spire.Office for .NET
To begin with, you need to add the DLL files included in the Spire.Office 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.Office
Export Excel Data to a Word Table with Formatting
Below are the steps to convert Excel data to a Word table and keep the formatting using Spire.Office for .NET.
- Create a Workbook object and load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Create a Document object, and add a section to it.
- Add a table using Section.AddTable() method.
- Detect the merged cells in the worksheet and merge the corresponding cells of the Word tale using the custom method MergeCells().
- Get value of a specific Excel cell through CellRange.Value property and add it to a cell of the Word table using TableCell.AddParagraph().AppendText() method.
- Copy the font style and cell style from Excel to the Word table using the custom method CopyStyle().
- Save the document to a Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
namespace ConvertExcelToWord
{
internal class Program
{
static void Main(string[] args)
{
//Load an Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Create a Word document
Document doc = new Document();
Section section = doc.AddSection();
section.PageSetup.Orientation = PageOrientation.Landscape;
//Add a table
Table table = section.AddTable(true);
table.ResetCells(sheet.LastRow, sheet.LastColumn);
//Merge cells
MergeCells(sheet, table);
for (int r = 1; r <= sheet.LastRow; r++)
{
//Set row Height
table.Rows[r - 1].Height = (float)sheet.Rows[r - 1].RowHeight;
for (int c = 1; c <= sheet.LastColumn; c++)
{
CellRange xCell = sheet.Range[r, c];
TableCell wCell = table.Rows[r - 1].Cells[c - 1];
//Export data from Excel to Word table
TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);
//Copy font and cell style from Excel to Word
CopyStyle(textRange, xCell, wCell);
}
}
//Save the document to a Word file
doc.SaveToFile("ExportToWord.docx", Spire.Doc.FileFormat.Docx);
}
//Merge cells if any
private static void MergeCells(Worksheet sheet, Table table)
{
if (sheet.HasMergedCells)
{
//Get merged cell ranges from Excel
CellRange[] ranges = sheet.MergedCells;
//Merge corresponding cells in Word table
for (int i = 0; i < ranges.Length; i++)
{
int startRow = ranges[i].Row;
int startColumn = ranges[i].Column;
int rowCount = ranges[i].RowCount;
int columnCount = ranges[i].ColumnCount;
if (rowCount > 1 && columnCount > 1)
{
for (int j = startRow; j <= startRow + rowCount; j++)
{
table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
}
table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1);
}
if (rowCount > 1 && columnCount == 1)
{
table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1);
}
if (columnCount > 1 && rowCount == 1)
{
table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
}
}
}
}
//Copy cell style of Excel to Word table
private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
{
//Copy font style
wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
//Copy backcolor
wCell.CellFormat.Shading.BackgroundPatternColor = xCell.Style.Color;
//Copy horizontal alignment
switch (xCell.HorizontalAlignment)
{
case HorizontalAlignType.Left:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
break;
case HorizontalAlignType.Center:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
break;
case HorizontalAlignType.Right:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
break;
}
//Copy vertical alignment
switch (xCell.VerticalAlignment)
{
case VerticalAlignType.Bottom:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom;
break;
case VerticalAlignType.Center:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
break;
case VerticalAlignType.Top:
wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top;
break;
}
}
}
}

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.
How to Align a Table in C#
Usually there are three kinds of alignment style for a word table: left aligned, centered and right aligned. On Microsoft word, we can go to table properties to set the alignment for the whole table. Spire.Doc also offers a property table.TableFormat.HorizontalAlignment to enable developers to set the table alignment style easily in C#. This article will demonstrate how to align a table in C#.
Firstly, view the how to align a table for Microsoft word:

Here come to the code snippet of how Spire.Doc align a table.
Step 1: Create a word document and load from file.
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Step 2: Get the first section and two tables from the word document.
Section section = doc.Sections[0]; Table table = section.Tables[0] as Table; Table table1 = section.Tables[1] as Table;
Step 3: Set the different alignment properties for each table.
table.Format.HorizontalAlignment = RowAlignment.Right; table.Format.LeftIndent = 34; table1.Format.HorizontalAlignment = RowAlignment.Left; table1.Format.LeftIndent = 34;
Step 4: Save the document to file:
doc.SaveToFile("result.docx", FileFormat.Docx);
Effective screenshots after align the table format:

Full codes:
using Spire.Doc;
using Spire.Doc.Documents;
namespace AlignTable
{
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Section section = doc.Sections[0];
Table table = section.Tables[0] as Table;
Table table1 = section.Tables[1] as Table;
table.Format.HorizontalAlignment = RowAlignment.Right;
table.Format.LeftIndent = 34;
table1.Format.HorizontalAlignment = RowAlignment.Left;
table1.Format.LeftIndent = 34;
doc.SaveToFile("result.docx", FileFormat.Docx);
}
}
}
How to add report filter to Excel Pivot table in C#
To view the large amount of Excel data's easily, Spire.XLS for .NET supports create Pivot table and add excel table with filters. Spire.XLS also offers a method of pivotTable.ReportFilters.Add(); to enable developers to add the report filter to the pivot table.
This article will show you how to add a report filter to the Excel Pivot table 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 screenshot of excel pivot table.

Step 1: Create a new workbook and load from file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Step 2: Get the PivotTable from the Excel worksheet.
Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets["Pivot Table"].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;
Step 3: Add a filter to the pivot table.
PivotReportFilter filter = new PivotReportFilter("JAN", true);
pivotTable.ReportFilters.Add(filter);
Step 4: Save the document to file and launch to preview it.
workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");
Effective screenshot after add a filter to the pivot table:

Full codes:
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;
namespace AddReportFilter
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets["Pivot Table"].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;
PivotReportFilter filter = new PivotReportFilter("JAN", true);
pivotTable.ReportFilters.Add(filter);
workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");
}
}
}