Sunteți pe pagina 1din 229

Essential Studio

for File Formats


Version - v17.4.0.39 | Release Date - December 17, 2019
Welcome to Syncfusion Essential File Formats Platform.............................................................................. 6
How to best read this user guide .............................................................................................................. 6
Additional help resources ......................................................................................................................... 6
Create a support incident ......................................................................................................................... 6
List of File Format libraries: ...................................................................................................................... 6
Quick Start links: ....................................................................................................................................... 7
System Requirements ................................................................................................................................... 7
Operating Systems ................................................................................................................................ 7
Hardware Environment......................................................................................................................... 7
Development Environment ................................................................................................................... 7
Download Installer ........................................................................................................................................ 7
Download the Trial Version ...................................................................................................................... 7
Free Trial Page....................................................................................................................................... 7
Start Trial Page ...................................................................................................................................... 8
Download the License Version.................................................................................................................. 9
Installation and Upgrade............................................................................................................................... 9
Installation using Web Installer ................................................................................................................ 9
Overview ............................................................................................................................................... 9
Installation .......................................................................................................................................... 10
Uninstallation ...................................................................................................................................... 20
Installation and Uninstallation ............................................................................................................ 25
Installation using Offline Installer ........................................................................................................... 34
Installing with UI ................................................................................................................................. 34
Installing in silent mode ...................................................................................................................... 41
Installation FAQ....................................................................................................................................... 43
Upgrade from one version to another version. ...................................................................................... 43
Upgrade from major version to service pack version ............................................................................. 43
Upgrade from trial version to license version..................................................................................... 43
NuGet Packages .......................................................................................................................................... 43
Installing NuGet Packages ....................................................................................................................... 43
Using NuGet Package Manager .......................................................................................................... 43
Using Package Manager Console ........................................................................................................ 45
DocIO........................................................................................................................................................... 45
How to open a document from stream using DocIO? ........................................................................ 67
How to set OpenType Font Features? ................................................................................................ 69
How to attach a Template to a Word document? .............................................................................. 74
How to insert a DataTable in a Word document? .............................................................................. 74
How to insert a table from HTML string in Word document? ............................................................ 77
How to set table cell width? ............................................................................................................... 77
How to position a table in a Word document? ................................................................................... 79
How to set the text direction to a table in Word document? ............................................................ 79
How to extract the images in the document? .................................................................................... 80
How to remove headers and footers from the document? ............................................................... 82
Which units does Essential DocIO uses for measurement properties such as size, margins, etc, in a
Word document? ................................................................................................................................ 83
Could not find Syncfusion.OfficeChartToImageConverter assembly in .NET 3.5 Framework, does it
mean there is no support for chart conversion in this Framework? .................................................. 84
Can the chart data be refreshed? ....................................................................................................... 84
Is it possible to convert 3D charts to PDF or image? .......................................................................... 84
Is it possible to specify PDF conformance level in Word to PDF conversion? .................................... 84
Migration from Microsoft Office Automation to Essential DocIO ...................................................... 84
How to copy necessary fonts to Linux containers ............................................................................ 107
PDF ............................................................................................................................................................ 107
Performing OCR for an entire document .......................................................................................... 117
Performing OCR with tesseract version 3.05 .................................................................................... 118
Performing OCR for a region of the document ................................................................................. 119
Performing OCR on image................................................................................................................. 120
Performing OCR for large PDF documents........................................................................................ 120
Performing OCR on rotated page of PDF document......................................................................... 121
Layout result from OCR ..................................................................................................................... 122
Native call.......................................................................................................................................... 123
Customizing temp folder................................................................................................................... 125
Best Practices .................................................................................................................................... 126
Troubleshooting ................................................................................................................................ 126
Working with Hyperlinks....................................................................................................................... 127
Working with Web navigation .......................................................................................................... 127
Optimizing embedded font ............................................................................................................... 142
Optimizing page contents ................................................................................................................. 143
Remove metadata information......................................................................................................... 144
Compressing the PDF content........................................................................................................... 144
Compressing images ......................................................................................................................... 146
Working with PDF Conformance........................................................................................................... 148
PDF/A-1b conformance..................................................................................................................... 148
Presentation .............................................................................................................................................. 152
Create a custom LayoutSlide............................................................................................................. 154
Working with Paragraph ....................................................................................................................... 155
Adding Paragraph to slide ................................................................................................................. 155
Decrypting the PowerPoint Presentation ......................................................................................... 168
Write Protection ............................................................................................................................... 169
XlsIO .......................................................................................................................................................... 173
Range Access ..................................................................................................................................... 189
Styles ................................................................................................................................................. 190
AutoFit............................................................................................................................................... 191
Importing DataTable ......................................................................................................................... 191
Data Validation.................................................................................................................................. 192
Known Exceptions Details ..................................................................................................................... 192
ApplicationException ........................................................................................................................ 192
ArgumentException .......................................................................................................................... 193
ArgumentNullException .................................................................................................................... 195
ArgumentOutOfRangeException ...................................................................................................... 195
ExcelWorkbookNotSavedException .................................................................................................. 201
FileNotFoundException ..................................................................................................................... 201
InvalidRangeException ...................................................................................................................... 202
NotSupportedException.................................................................................................................... 202
FAQ Section ........................................................................................................................................... 203
How to open an existing XLSX workbook and save it as XLS? ........................................................... 203
How to open an Excel file from Stream? .......................................................................................... 203
How to save a file to stream? ........................................................................................................... 204
How to create and open Excel Template files by using XlsIO? ......................................................... 205
How to open an Excel 2013 Macro Enabled Template? ................................................................... 206
How to change the grid line color of the Excel sheet? ..................................................................... 206
How to copy and paste the values of the cells that contain only formulas? .................................... 207
How to copy a range from one workbook to another? .................................................................... 208
How to merge several excel files from more than one workbook to a single file? .......................... 209
How to ignore the green error marker in worksheets? .................................................................... 210
How to protect certain cells in a worksheet? ................................................................................... 210
How to set a line break inside a cell? ................................................................................................ 211
How to set or format a Header/Footer? ........................................................................................... 212
How to set print titles? ..................................................................................................................... 212
How to unfreeze the rows and columns in XlsIO? ............................................................................ 214
What is the maximum range of Rows and Columns? ....................................................................... 214
How to use Named Ranges with XlsIO? ............................................................................................ 214
How to add chart labels to scatter points? ....................................................................................... 215
How to create a Chart with a discontinuous range?......................................................................... 216
How to define discontinuous ranges? .............................................................................................. 218
How to format text within a cell? ..................................................................................................... 219
How to hide the summary rows and columns using XlsIO? .............................................................. 220
How to zip files using the Syncfusion.Compression.Zip namespace?............................................... 221
How to zip all the files in subfolders using the Syncfusion.Compression.Zip namespace? .............. 222
Does Essential XlsIO provide support for Client Profile? .................................................................. 226
How to resolve the “File does not contain workbook stream” error in Syncfusion.XlsIO.Base.dll? 226
How to resolve "Excel cannot open the file 'filename.xlsx' because the file format for the file
extension is not valid. Verify that the file has not been corrupted and that the file extension
matches the format of the file" error? ............................................................................................. 226
What happens when an Excel file containing uninstalled fonts is converted to PDF/Image? ......... 227
How to avoid exception when adding worksheets with same name ............................................... 228
Welcome to Syncfusion Essential File Formats Platform How to best read this user guide

Welcome to Syncfusion Essential File Formats Platform


Essential File Formats is a collection of .NET class libraries to create, edit, write, and convert PDF, Excel,
Word, and PowerPoint file formats in .NET Framework [C#, VB.NET], .NET Core, UWP, and Xamarin
applications without Microsoft Office or Adobe dependencies.
How to best read this user guide

 The best way to get started would be to read the “Getting Started” section for the component
you would like to start first. The “Getting Started” and “Assemblies required” sections gives
enough information, so it is recommended to read these sections end-to-end before starting to
write a code. All other information can be referred as needed.
 After learning the basics about the component, integrate the component into your application.
A good starting point is to refer to the code examples in the sample browser and in this user
guide. It is very likely that you can find a code example that resembles your intended usage
scenario.
 Another valuable resource is available in the API reference that provides detailed information on
the object hierarchy as well as the settings available on every object.

Additional help resources


The Knowledge Base section contains responses for common questions asked by the customers. This
would be a good place to search for the topics that are not covered in the User Guide.
Similar to the Knowledge Base, the Forum section also contains responses to the questions that are
asked by other customers.
Create a support incident
If you are unable to find the information you are looking for in the self-help resources mentioned above,
please contact us by creating a support ticket.
List of File Format libraries:
File Format library Description
.NET Class library used to create, read, and write PDF files in .NET Framework
Essential PDF [Windows Forms, WPF, ASP.NET MVC, ASP.NET], .NET Core, UWP and Xamarin
applications.
.NET Class library used to create, read, edit, write, and convert Microsoft Excel
Essential XlsIO files in .NET Framework [Windows Forms, WPF, ASP.NET MVC, ASP.NET], .NET
Core, UWP, and Xamarin applications.
.NET Class library used to create, read, edit, and convert Microsoft Word files in
Essential DocIO .NET Framework [Windows Forms, WPF, ASP.NET MVC, ASP.NET], .NET Core,
UWP, and Xamarin applications.
.NET Class library used to create, read, edit, and convert Microsoft PowerPoint
Essential Presentation (PPTX) files in .NET Framework [Windows Forms, WPF, ASP.NET MVC, ASP.NET],
.NET Core, UWP, and Xamarin applications.

Copyright © 2001 - 2019 Syncfusion Inc. 6


System Requirements Quick Start links:

Quick Start links:


Create a PDF file in C# without Adobe
Create Excel file in C# without Microsoft Office
Create Word file in C# without Microsoft Office
Create PowerPoint file in C# without Microsoft Office

System Requirements
The following topic describes the system requirements needed by Syncfusion File Formats platform.
Operating Systems
Syncfusion File Formats platform can be installed on any of the following operating systems:

 Windows 10
 Windows 8, 8.1
 Windows 7
 Windows Vista
 Windows Server 2008 and later

Hardware Environment

 Processor: x86 or x64


 RAM : 512 MB (minimum), 1 GB (recommended)
 Hard disk: up to 8.5 GB of available space may be required. However, 750 MB free space is
required in boot drive even if you are installing the setup in other drive.

Development Environment
In order to develop applications with Syncfusion File Formats platform, you need to have installed
anyone of the Visual Studio version.

 Microsoft Visual Studio 2005


 Microsoft Visual Studio 2008
 Microsoft Visual Studio 2010
 Microsoft Visual Studio 2012
 Microsoft Visual Studio 2013
 Microsoft Visual Studio 2015
 Microsoft Visual Studio 2017

Download Installer
You can download the installer from Syncfusion.com website.
Download the Trial Version
There are two ways to download our 30-day trial.
Free Trial Page

1. You can evaluate our 30-day free trial from Free Trial page.

Copyright © 2001 - 2019 Syncfusion Inc. 7


Download Installer Download the Trial Version

2. Once you fill the required form or made the login using the your Syncfusion registered account
you can download the trial installer setup in the confirmation page.
3. You can download the latest version trial installer.
4. You can unlock the installer using the unlock key, also you can unlock the installer using the
Syncfusion registered login credential.
5. You can download the trial installer using the Trials & Downloads page under your registered
account at any time before the trial expire. (Refer the below screenshot).

Start Trial Page

1. You can evaluate our 30-day free trial from Start Trial page.
2. You should login using your Syncfusion account to access this page.
3. You can start your trail by clicking on the required product.

Note: If you already using the trail products and it’s not expired, you couldn’t start the trial again for
same product.

4. After you started the trial, you can download the latest version trial installer using the Trials &
Downloads page.
5. In Trials & Downloads page, you can find your current active trial products. Trials, which you
done in both Free Trial Page and Start trial pages are listed here.
6. Use the Download (element 1 in below screenshot) button to download the installer of
respective product.
7. Online installer can be downloaded from this page.
8. No need of unlock key to unlock the online installer.
9. You can unlock the installer using the Syncfusion registered login credential.

Note: You can generate the license key for your active trial products from Trials & Downloads page. This
license key will be mandatory to use our trial products in your application. To know more about License
key, refer this help topic.

Copyright © 2001 - 2019 Syncfusion Inc. 8


Installation and Upgrade Download the License Version

Download the License Version

1. You can find your available licensed products which under your registered Syncfusion account in
License & Downloads page.
2. You can find all the licenses (both active licenses and expired licenses) which are under your
account.
3. You can find the licenses listed based on SKU names.
4. Use the Download (element 1 in below screenshot) button to download the installer of
respective product.
5. Latest version installer will be downloaded from this page.
6. You can navigate to Downloads Older Versions (element 2 in below screenshot) to download
older version installers.
7. From 16.2 version online installer will be downloaded by default, and earlier versions offline
installer will be downloaded.

Note: Online Installer have been introduced from the release version 16.2.

8. You can navigate to More Downloads Options (element 3 in below screenshot) to download
other setups.
9. EXE and Zip format available to download for Windows OS. Both are Offline Installer.
10. No need of unlock key to unlock the online installer.
11. You can unlock the installer using the unlock key for versions earlier to 16.2, also you can unlock
the installer using the Syncfusion registered login credential.

Note: You can generate the license key for your licensed products from License & Downloads page. This
license key will be required only from release version 16.2. To know more about License key, refer this
help topic.

Installation and Upgrade


Installation using Web Installer
Overview
Starting with version 16.2 (2018 Vol 2), Syncfusion provides Web Installer for Essential Studio platforms.
This installer reduces the burden of downloading the setup of larger size. You can just download and
launch the online installer which will be of smaller size and it will downloads and installs the Essential
Studio products you have selected. The Essential Studio Web Installer includes the following platforms.
You can download the latest version Essential Studio Web Installer here .

Copyright © 2001 - 2019 Syncfusion Inc. 9


Installation and Upgrade Installation using Web Installer

Starting with the version 17.3 (2019 Vol 3), Syncfusion provides updated version of Web Installer which
allows both installation and uninstallation of the platforms for that specific version.
Web (Essential JS 2)

 ASP.NET MVC
 ASP.NET Core
 JavaScript

Mobile

 Xamarin
 Flutter

Desktop

 Windows Forms
 WPF
 Universal Windows Platform

FileFormats

 Read and Write Excel, Word, PDF and PowerPoint files

Web (Essential JS 1)

 ASP.NET Web Forms


 ASP.NET MVC
 ASP.NET Core
 JavaScript
 PHP
 JSP

Note: Universal Windows Platform will be installed in Windows 8.1 and later.
Installation
The following procedure illustrates how to install Essential Studio Platform Online Installer setup.

1. Double-click the Syncfusion Essential Studio Platform Online Installer setup file. The Setup
Wizard opens and extracts the package automatically.

Copyright © 2001 - 2019 Syncfusion Inc. 10


Installation and Upgrade Installation using Web Installer

Note: The Setup wizard extracts the syncfusionfileformatswebinstaller_{version}.exe dialog, displaying


the unzip operation of the package.

2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 11


Installation and Upgrade Installation using Web Installer

3. Platform Selection wizard will be displayed. Select the platforms to be installed from the
Available tab. Select Install All checkbox to select all the platforms. Click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 12


Installation and Upgrade Installation using Web Installer

Information: If the required software of the selected platform was not already installed, Additional
Software Required alert will be displayed. However, you can continue the installation and install the
required software later.

Copyright © 2001 - 2019 Syncfusion Inc. 13


Installation and Upgrade Installation using Web Installer

4. Confirmation wizard will be displayed. Here you can view and modify the list of platforms that
will be installed.

Copyright © 2001 - 2019 Syncfusion Inc. 14


Installation and Upgrade Installation using Web Installer

Note: You can check the Estimated size of the Download and Installation by clicking the Download Size
and Installation Size link.

Copyright © 2001 - 2019 Syncfusion Inc. 15


Installation and Upgrade Installation using Web Installer

5. Configuration wizard will be displayed. Here you can change the Download, Install and samples
location. Also, you can change the Additional settings by platform basis. To install using the
default configuration, click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 16


Installation and Upgrade Installation using Web Installer

Information: From version 17.3 (2019 Vol 3), Syncfusion provides option to provide custom download
location.
Note: From the 2018 Volume 2 release, Syncfusion has changed the install and samples location
Default Install location: {ProgramFilesFolder}\Syncfusion\{Platform}\{version}
Default Samples location: C:\Users\Public\Documents\Syncfusion\{platform}\{version}
However, you can change the locations by clicking browse button.

 Select the Install Demos check box to install Syncfusion samples, or leave the check box clear,
when you do not want to install Syncfusion samples.
 Select the Register Syncfusion Assemblies in GAC check box to install the latest Syncfusion
assemblies in GAC, or clear this check box when you do not want to install the latest assemblies
in GAC.
 Select the Configure Syncfusion controls in Visual Studio check box to configure the Syncfusion
controls in the Visual Studio toolbox, or clear this check box when you do not want to configure
the Syncfusion controls in the Visual Studio toolbox during setup installation. Note that you
must also select the Register Syncfusion assemblies in GAC check box when you select this check
box.
 Select the Configure Syncfusion Extensions controls in Visual Studio checkbox to configure the
Syncfusion Extensions in Visual Studio or clear this check box when you do not want to configure
the Syncfusion Extensions in Visual Studio.
 Select the Create Desktop Shortcut checkbox to create the desktop shortcut for Syncfusion
Control Panel.

Copyright © 2001 - 2019 Syncfusion Inc. 17


Installation and Upgrade Installation using Web Installer

6. After reading the License Terms and Conditions, check the I agree to the License Terms and
Privacy Policy check box. Click Next.
7. Login wizard will be displayed. You should enter your Syncfusion Direct-Trac login credentials. If
you don't have Syncfusion Direct-Trac login credentials, then you can click on Create an
Account. Else if you forgot your password, click on Forgot Password to create new password.
Click Install.

Information: The selected platforms will be installed based on your Syncfusion License (Trial or
Licensed).

8. Download and Installation progress will be displayed.

Copyright © 2001 - 2019 Syncfusion Inc. 18


Installation and Upgrade Installation using Web Installer

9. Once the Installation is complete, Summary wizard will be displayed. Here you can check the list
of platforms which are installed successfully and failed. Click Finish to exit the Summary wizard.

Copyright © 2001 - 2019 Syncfusion Inc. 19


Installation and Upgrade Installation using Web Installer

 Click Launch Control Panel to open the Syncfusion Control Panel.

Uninstallation
Till version 17.2, Syncfusion Web Installer had option for installation alone. Starting with the version
17.3 (2019 Vol 3), Syncfusion provides option for uninstalling the platforms of the same version from the
Web Installer application itself. Select the list of the platforms to be uninstalled and Web Installer will
uninstall those platforms one by one.
The following procedure illustrates how to uninstall Essential Studio Platform from Web Installer setup.

1. Double-click the Syncfusion Essential Studio Platform Online Installer setup file. The Setup
Wizard opens and extracts the package automatically.

Copyright © 2001 - 2019 Syncfusion Inc. 20


Installation and Upgrade Installation using Web Installer

2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 21


Installation and Upgrade Installation using Web Installer

3. Platform Selection wizard will be displayed. Select the platforms to be uninstalled from the
Installed tab. Select Uninstall All checkbox to select all the platforms. Click Next.

4. Confirmation wizard will be displayed. Here you can view and modify the list of platforms that
will be uninstalled. Click Uninstall.

Copyright © 2001 - 2019 Syncfusion Inc. 22


Installation and Upgrade Installation using Web Installer

5. Uninstallation progress will be displayed.

Copyright © 2001 - 2019 Syncfusion Inc. 23


Installation and Upgrade Installation using Web Installer

6. Once the Uninstallation is complete, Summary wizard will be displayed. Here you can check the
list of platforms which are uninstalled successfully and failed. Click Finish to exit the Summary
wizard.

Copyright © 2001 - 2019 Syncfusion Inc. 24


Installation and Upgrade Installation using Web Installer

Installation and Uninstallation


Till version 17.2, Syncfusion Web Installer had option for installation alone. Starting with the version
17.3 (2019 Vol 3), Syncfusion provides option for both install and uninstall the platforms of the same
version from the Web Installer application itself.
The following procedure illustrates how to install/uninstall Essential Studio Platform from Web Installer
setup.

1. Double-click the Syncfusion Essential Studio Platform Online Installer setup file. The Setup
Wizard opens and extracts the package automatically.

Copyright © 2001 - 2019 Syncfusion Inc. 25


Installation and Upgrade Installation using Web Installer

2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 26


Installation and Upgrade Installation using Web Installer

3. Platform Selection wizard will be displayed. Select the platforms to be installed from the
Available tab and platforms to be uninstalled from the Installed tab. Click Next.

Available

Installed

Copyright © 2001 - 2019 Syncfusion Inc. 27


Installation and Upgrade Installation using Web Installer

4. Confirmation wizard will be displayed. Here you can view and modify the list of platforms that
will be installed/uninstalled.

Copyright © 2001 - 2019 Syncfusion Inc. 28


Installation and Upgrade Installation using Web Installer

Note: You can check the Estimated size of the Download and Installation by clicking the Download Size
and Installation Size link.

Copyright © 2001 - 2019 Syncfusion Inc. 29


Installation and Upgrade Installation using Web Installer

5. Configuration wizard will be displayed. Here you can change the Download, Install and samples
location. Also, you can change the Additional settings by platform basis. To install using the
default configuration, click Next.

Copyright © 2001 - 2019 Syncfusion Inc. 30


Installation and Upgrade Installation using Web Installer

Information: From version 17.3 (2019 Vol 3), Syncfusion provides option to provide custom download
location.

6. After reading the License Terms and Conditions, check the I agree to the License Terms and
Privacy Policy check box. Click Next.
7. Login wizard will be displayed. You should enter your Syncfusion Direct-Trac login credentials. If
you don't have Syncfusion Direct-Trac login credentials, then you can click on Create an
Account. Else if you forgot your password, click on Forgot Password to create new password.
Click Install.

Copyright © 2001 - 2019 Syncfusion Inc. 31


Installation and Upgrade Installation using Web Installer

Information: The selected platforms will be installed based on your Syncfusion License (Trial or
Licensed).

8. Download, Installation and Uninstallation progress will be displayed.

Copyright © 2001 - 2019 Syncfusion Inc. 32


Installation and Upgrade Installation using Web Installer

9. Once the Installation is complete, Summary wizard will be displayed. Here you can check the list
of platforms which are installed/uninstalled successfully and failed. Click Finish to exit the
Summary wizard.

Copyright © 2001 - 2019 Syncfusion Inc. 33


Installation and Upgrade Installation using Offline Installer

 Click Launch Control Panel to open the Syncfusion Control Panel.

Installation using Offline Installer


Installing with UI
The following procedure illustrates how to install Essential Studio File Formats platform.

1. Close all the running Visual Studio instances.


2. Double-click the Syncfusion File Formats platform Setup file. The Setup Wizard opens and
extracts the package automatically.

Copyright © 2001 - 2019 Syncfusion Inc. 34


Installation and Upgrade Installation using Offline Installer

Note: The Setup wizard extracts the syncfusionessentialfileformats_(version).exe dialog, displaying the
unzip operation of the package.

3. You have two options to unlock the Syncfusion setup:

 Login To Install
 Use Unlock Key

Login To Install
You should enter your Syncfusion Direct-Trac login credentials. If you don't have Syncfusion Direct-Trac
login credentials, then you can click on Sign Up to a create new account. Else if you forgot your
password, click on Reset Password to create new password. Here Email address and Password is
validated and the Platform Selection window opens.

Copyright © 2001 - 2019 Syncfusion Inc. 35


Installation and Upgrade Installation using Offline Installer

Use Unlock Key


You should use the Syncfusion License/Trial key. Trial key is valid for 30 days and the installer won't
accept the expired trial key. Licensed customer can generate key from here.

Copyright © 2001 - 2019 Syncfusion Inc. 36


Installation and Upgrade Installation using Offline Installer

4. After reading the License Terms and Conditions, check the I agree to the License Terms and
Conditions check box.

5. Click Next. Select the Installation, Samples Folder and Advanced Options screen opens. To install
in the displayed default location, click Install

Copyright © 2001 - 2019 Syncfusion Inc. 37


Installation and Upgrade Installation using Offline Installer

Note: From the 2018 Volume 2 release, Syncfusion has changed the install and samples location
Default Install location: {ProgramFilesFolder}\Syncfusion\{Platform}\{version}
Default Samples location: C:\Users\Public\Documents\Syncfusion\{platform}\{version}
However, you can change the locations by clicking browse button.

 Select the Install Syncfusion Samples check box to install Syncfusion samples, or leave the check
box clear, when you do not want to install Syncfusion samples.
 Select the Register Syncfusion Assemblies in GAC check box to install the latest Syncfusion
assemblies in GAC, or clear this check box when you do not want to install the latest assemblies
in GAC.

Copyright © 2001 - 2019 Syncfusion Inc. 38


Installation and Upgrade Installation using Offline Installer

 Select the Uninstall the previously installed Syncfusion assemblies from GAC check box to
uninstall the previously installed Syncfusion assemblies from GAC, or clear this check box to
maintain the previously installed assemblies.
 Select the Configure Syncfusion controls in Visual Studio Toolbox check box to configure the
Syncfusion controls in the Visual Studio toolbox, or clear this check box when you do not want
to configure the Syncfusion controls in the Visual Studio toolbox during setup installation. Note
that you must also select the Register Syncfusion assemblies in GAC check box when you select
this check box.
 Select the Install Syncfusion Extensions checkbox to configure the Syncfusion Extensions in
Visual Studio or clear this check box when you do not want to configure the Syncfusion
Extensions in Visual Studio.

6. Click Install.

Copyright © 2001 - 2019 Syncfusion Inc. 39


Installation and Upgrade Installation using Offline Installer

7. The Completed screen is displayed once the File Formats platform is installed.

Copyright © 2001 - 2019 Syncfusion Inc. 40


Installation and Upgrade Installation using Offline Installer

8. Select the Run Syncfusion Control Panel check box to launch the Syncfusion Control Panel after
installing.

9. Click Finish. Syncfusion File Formats platform is installed in your system and the Syncfusion
Essential Studio Syncfusion Control Panel is launched automatically.

Installing in silent mode


The Syncfusion Essential Studio Platform Installer supports installing/uninstalling the setup through
Command Line. The following sections illustrate this ability.

Copyright © 2001 - 2019 Syncfusion Inc. 41


Installation and Upgrade Installation using Offline Installer

Command Line Installation


Follow the steps below to install through Command Line in Silent mode.

1. Double-click the Syncfusion Essential Studio platform setup file. The Setup Wizard opens and
extracts the package automatically.
2. The syncfusionessentialfileformats_(version).exe file is extracted into the Temp folder.
3. Run %temp%. The Temp folder will open. The syncfusionessentialfileformats_(version).exe file is
available in one of the folders.
4. Copy the extracted syncfusionessentialfileformats_(version).exe file in local drive.
5. Cancel the Wizard.
6. Open the Command Prompt in administrator mode and pass the following arguments.

Arguments: “Setup file path\SyncfusionEssentialStudio(platform)_(version).exe” /Install silent


/PIDKEY:“(product unlock key)” [/log “{Log file path}”] [/InstallPath:{Location to install}]
[/InstallSamples:{true/false}] [/InstallAssemblies:{true/false}] [/UninstallExistAssemblies:{true/false}]
[/InstallToolbox:{true/false}]
Note: [..] – Arguments inside the square brackets are optional.
Example: “D:\Temp\syncfusionessentialfileformatsx.x.x.x.exe” /Install silent /PIDKEY:“product unlock
key” /log “C:\Temp\EssentialStudioPlatform.log” /InstallPath:C:\Syncfusion\x.x.x.x /InstallSamples:true
/InstallAssemblies:true /UninstallExistAssemblies:true /InstallToolbox:true

7. Setup is installed.

Note: x.x.x.x needs to be replaced with the Essential Studio version and the Product Unlock Key needs
to be replaced with the Unlock Key for that version.
Command Line Uninstallation
Syncfusion Essential Studio supports uninstalling the setup through Command Line in Silent mode. The
following steps illustrate this.

1. When you do not have the extracted setup (syncfusionessentialfileformats_(version).exe) then


follow the steps from 2 to 7.
2. Double-click the Syncfusion Essential Studio platform setup file. The Setup Wizard opens and
extracts the package automatically.
3. The syncfusionessentialfileformats_(version).exe file is extracted into the Temp folder.
4. Run %temp%. The Temp folder will open. The syncfusionessentialfileformats_(version).exe file is
available in one of the folders.
5. Copy the syncfusionessentialfileformats_(version).exe file in local drive.
6. Cancel the Wizard.
7. Open the Command Prompt in administrator mode and pass the following arguments.

Arguments: “Copied setup file path\syncfusionessentialfileformats_(version).exe” /uninstall silent


Example: “D:\Temp\syncfusionessentialfileformats_x.x.x.x.exe" /uninstall silent

8. Setup is uninstalled.

Copyright © 2001 - 2019 Syncfusion Inc. 42


NuGet Packages Installation FAQ

Note: x.x.x.x needs to be replaced with the Essential Studio version installed in your machine.
Installation FAQ
Refer this topic for more information regarding the issues related to installation.
Upgrade from one version to another version.
You can upgrade to the latest version by downloading and installing the platforms you require from this
link.
Upgrade from major version to service pack version
Syncfusion provides a new Volume release once in every three months which has exciting new features.
For that Volume release, there may be one or two Service Pack releases. The issues in the Volume
release will be addressed in the Service Pack releases. You can download and install the latest Service
Pack setup here.
It is not required to install the Volume release setup before installing the Service Pack release setup. As
Volume and Service Packs releases works independently, you can directly install the latest Service Pack
setup which contains major issue fixes.
Upgrade from trial version to license version
To upgrade from trial version, there are two possible solutions.

 Uninstall the trial version and install the fully licensed build from the License & Downloads
section of our website.
 Replace the currently used trial license key with a paid license key that can be generated from
the License & Downloads section of our website.

NuGet Packages
NuGet can be used to automatically add files and references to your Visual Studio projects. You can use
the Syncfusion NuGet packages without installing the Essential Studio or platform installation to
development with the Syncfusion controls. From v16.2.0.46 (2018 Volume 2 Service Pack 1) onwards, all
the Syncfusion components are available as NuGet packages at nuget.org.
Note: The Syncfusion Xamarin NuGet packages are published in NuGet.org from v15.4.0.17. Starting
from v17.1.0.32 (2018 Volume 1), Syncfusion will no longer publish NuGet packages at
nuget.syncfusion.com.
Installing NuGet Packages
Using NuGet Package Manager
The NuGet Package Manager can be used to search and install NuGet packages in the Visual Studio
solution or project:
1. Right-click the project or solution in the Solution Explorer tab, and choose Manage NuGet Packages…

Copyright © 2001 - 2019 Syncfusion Inc. 43


NuGet Packages Installing NuGet Packages

Alternatively, click Tools menu, NuGet Package Manager | Manage NuGet Packages for Solution...
2. By default, the NuGet.org package is selected in the Package source drop-down. If NuGet.org is not
configured in your Visual Studio, refer to the Microsoft docs to configure NuGet.org feed URL in your
Visual Studio.

3. The Syncfusion NuGet Packages are listed the available package in the source feed URL. Search and
install the required packages in your application, by clicking Install button.

Copyright © 2001 - 2019 Syncfusion Inc. 44


DocIO Installing NuGet Packages

Note: The Syncfusion NuGet packages are published in public NuGet.org from v16.2.0.46. So, If you
need to Install earlier version of 16.2.0.46 Syncfusion NuGet packages, configure Syncfusion private feed
URL.
Using Package Manager Console
To reference the Syncfusion component using the Package Manager Console as NuGet packages, follow
the below steps.
1. On the Tools menu, select NuGet Package Manager, and then Package Manager Console. 2. Run the
following NuGet installation commands.

DocIO
C#
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;

VB.NET
Imports Syncfusion.DocIO
Imports Syncfusion.DocIO.DLS

UWP

C#
//Opens an existing document from file system through constructor of
WordDocument class
WordDocument document = new WordDocument(fileName);

VB.NET
'Opens an existing document from file system through constructor of
WordDocument class
Dim document As New WordDocument(fileName)

UWP

C#
//Opens an existing document from file system through constructor of
WordDocument class
WordDocument document = new WordDocument(@"TestDocument.docx");
//Processes the body contents for each section in the Word document
foreach (WSection section in document.Sections)
{
//Accesses the Body of section where all the contents in document are apart
WTextBody sectionBody = section.Body;
IterateTextBody(sectionBody);
WHeadersFooters headersFooters = section.HeadersFooters;

Copyright © 2001 - 2019 Syncfusion Inc. 45


DocIO Installing NuGet Packages

//Consider that OddHeader and OddFooter are applied to this document


//Iterates through the TextBody of OddHeader and OddFooter
IterateTextBody(headersFooters.OddHeader);
IterateTextBody(headersFooters.OddFooter);
}
//Saves and closes the document instance
document.Save("Result.docx");
document.Close();

VB.NET
'Opens an existing document from file system through constructor of
WordDocument class
Dim document As New WordDocument("TestDocument.docx")
'Processes the body contents for each section in the Word document
For Each section As WSection In document.Sections
'Accesses the Body of section where all the contents in document are apart
Dim sectionBody As WTextBody = section.Body
IterateTextBody(sectionBody)
Dim headersFooters As WHeadersFooters = section.HeadersFooters
'Consider that OddHeader and OddFooter are applied to this document
'Iterates through the text body of OddHeader and OddFooter
IterateTextBody(headersFooters.OddHeader)
IterateTextBody(headersFooters.OddFooter)
Next
'Saves and closes the document instance
document.Save("Result.docx")
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Appends the text to the created paragraph
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.");
//Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to created section

Copyright © 2001 - 2019 Syncfusion Inc. 46


DocIO Installing NuGet Packages

Dim paragraph As IWParagraph = section.AddParagraph()


'Appends the text to the created paragraph
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.")
‘Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text to the paragraph
paragraph.AppendText("Adding new paragraph to the document");
//Saves the Word document
document.Save("Sample.docx", FormatType.Docx);
//Closes the document
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text to the paragraph
paragraph.AppendText("Adding new paragraph to the document")
'Saves the Word document
document.Save("Sample.docx", FormatType.Docx)
'Closes the document
document.Close()

UWP

C#
//Creates an instance of WordDocument class
WordDocument document = new WordDocument();
//Adds a section into Word document
IWSection section = document.AddSection();
//Adds a new paragraph into Word document and appends text into paragraph
IWTextRange textRange = section.AddParagraph().AppendText("Price Details");
textRange.CharacterFormat.FontName = "Arial";

Copyright © 2001 - 2019 Syncfusion Inc. 47


DocIO Installing NuGet Packages

textRange.CharacterFormat.FontSize = 12;
textRange.CharacterFormat.Bold = true;
section.AddParagraph();
//Adds a new table into Word document
IWTable table = section.AddTable();
//Specifies the total number of rows & columns
table.ResetCells(3, 2);
//Accesses the instance of the cell (first row, first cell) and adds the
content into cell
textRange = table[0, 0].AddParagraph().AppendText("Item");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 12;
textRange.CharacterFormat.Bold = true;
//Accesses the instance of the cell (first row, second cell) and adds the
content into cell
textRange = table[0, 1].AddParagraph().AppendText("Price($)");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 12;
textRange.CharacterFormat.Bold = true;
//Accesses the instance of the cell (second row, first cell) and adds the
content into cell
textRange = table[1, 0].AddParagraph().AppendText("Apple");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 10;
//Accesses the instance of the cell (second row, second cell) and adds the
content into cell
textRange = table[1, 1].AddParagraph().AppendText("50");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 10;
//Accesses the instance of the cell (third row, first cell) and adds the
content into cell
textRange = table[2, 0].AddParagraph().AppendText("Orange");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 10;
//Accesses the instance of the cell (third row, second cell) and adds the
content into cell
textRange = table[2, 1].AddParagraph().AppendText("30");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 10;
//Saves the document in the given name and format
document.Save("Table.docx", FormatType.Docx);
//Releases the resources occupied by WordDocument instance
document.Close();

VB.NET
'Creates an instance of WordDocument class
Dim document As New WordDocument()
'Adds a section into Word document
Dim section As IWSection = document.AddSection()
'Adds a new paragraph into Word document and appends text into paragraph
Dim textRange As IWTextRange = section.AddParagraph().AppendText("Price
Details")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 12
textRange.CharacterFormat.Bold = True

Copyright © 2001 - 2019 Syncfusion Inc. 48


DocIO Installing NuGet Packages

section.AddParagraph()
'Adds a new table into Word document
Dim table As IWTable = section.AddTable()
'Specifies the total number of rows and columns
table.ResetCells(3, 2)
'Accesses the instance of the cell (first row, first cell) and adds the
content into cell
textRange = table(0, 0).AddParagraph().AppendText("Item")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 12
textRange.CharacterFormat.Bold = True
'Accesses the instance of the cell (first row, second cell) and adds the
content into cell
textRange = table(0, 1).AddParagraph().AppendText("Price($)")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 12
textRange.CharacterFormat.Bold = True
'Accesses the instance of the cell (second row, first cell) and adds the
content into cell
textRange = table(1, 0).AddParagraph().AppendText("Apple")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 10
'Accesses the instance of the cell (second row, second cell) and adds the
content into cell
textRange = table(1, 1).AddParagraph().AppendText("50")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 10
'Accesses the instance of the cell (third row, first cell) and adds the
content into cell
textRange = table(2, 0).AddParagraph().AppendText("Orange")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 10
'Accesses the instance of the cell (third row, second cell) and adds the
content into cell
textRange = table(2, 1).AddParagraph().AppendText("30")
textRange.CharacterFormat.FontName = "Arial"
textRange.CharacterFormat.FontSize = 10
'Saves the document in the given name and format
document.Save("Table.docx", FormatType.Docx)
'Releases the resources occupied by WordDocument instance
document.Close()

UWP

C#
//Creates an instance of WordDocument class (Empty Word Document)
WordDocument document = new WordDocument();
//Adds a new section into the Word Document
IWSection section = document.AddSection();
//Adds a new paragraph into Word document and appends text into paragraph
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("Northwind Database");
paragraph.ParagraphFormat.HorizontalAlignment =
Syncfusion.DocIO.DLS.HorizontalAlignment.Center;

Copyright © 2001 - 2019 Syncfusion Inc. 49


DocIO Installing NuGet Packages

//Adds a paragraph into section


paragraph = section.AddParagraph();
//Adds a new bookmark start into paragraph with name "Northwind"
paragraph.AppendBookmarkStart("Northwind");
//Adds a text between the bookmark start and end into paragraph
paragraph.AppendText("The Northwind sample database (Northwind.mdb) is
included with all versions of Access. It provides data you can experiment
with and database objects that demonstrate features you might want to
implement in your own databases.");
//Adds a new bookmark end into paragraph with name " Northwind "
paragraph.AppendBookmarkEnd("Northwind");
//Adds a text after the bookmark end
paragraph.AppendText(" Using Northwind, you can become familiar with how a
relational database is structured and how the database objects work together
to help you enter, store, manipulate, and print your data.");
//Saves the document in the given name and format
document.Save("Bookmarks.docx", FormatType.Docx);
//Releases the resources occupied by WordDocument instance
document.Close();

VB.NET
'Creates an instance of WordDocument class (Empty Word Document)
Dim document As New WordDocument()
'Adds a new section into the Word Document
Dim section As IWSection = document.AddSection()
'Adds a new paragraph into Word document and appends text into paragraph
Dim paragraph As IWParagraph = section.AddParagraph()
paragraph.AppendText("Northwind Database")
paragraph.ParagraphFormat.HorizontalAlignment =
Syncfusion.DocIO.DLS.HorizontalAlignment.Center
'Adds a paragraph into section
paragraph = section.AddParagraph()
'Adds a new bookmark start into paragraph with name "Northwind"
paragraph.AppendBookmarkStart("Northwind")
'Adds a text between the bookmark start and end into paragraph
paragraph.AppendText("The Northwind sample database (Northwind.mdb) is
included with all versions of Access. It provides data you can experiment
with and database objects that demonstrate features you might want to
implement in your own databases.")
'Adds a new bookmark end into paragraph with name " Northwind "
paragraph.AppendBookmarkEnd("Northwind")
'Adds a text after the bookmark end
paragraph.AppendText(" Using Northwind, you can become familiar with how a
relational database is structured and how the database objects work together
to help you enter, store, manipulate, and print your data.")
'Saves the document in the given name and format
document.Save("Bookmarks.docx", FormatType.Docx)
'Releases the resources occupied by WordDocument instance
document.Close()

UWP

C#

Copyright © 2001 - 2019 Syncfusion Inc. 50


DocIO Installing NuGet Packages

//Creates an instance of WordDocument class (Empty Word Document)


WordDocument document = new WordDocument();
//Adds a new section into the Word Document
IWSection section = document.AddSection();
//Adds a new paragraph into Word document and appends text into paragraph
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("Today's Date: ");
//Adds the new Date field in Word document with field name and its type
WField field = paragraph.AppendField("Date", FieldType.FieldDate) as WField;
//Field code used to describe how to display the date
field.FieldCode = @"DATE \@" + "\"MMMM d, yyyy\"";
//Saves the document in the given name and format
document.Save("Sample.docx", FormatType.Docx);
//Releases the resources occupied by WordDocument instance
document.Close();

VB.NET
'Creates an instance of WordDocument class (Empty Word Document)
Dim document As New WordDocument()
'Adds a new section into the Word Document
Dim section As IWSection = document.AddSection()
'Adds a new paragraph into Word document and appends text into paragraph
Dim paragraph As IWParagraph = section.AddParagraph()
paragraph.AppendText("Today's Date: ")
'Adds the new Date field in Word document with field name and its type
Dim field As WField = TryCast(paragraph.AppendField("Date",
FieldType.FieldDate), WField)
'Field code used to describe how to display the date
field.FieldCode = "DATE \@" + """MMMM d, yyyy"""
'Saves the document in the given name and format
document.Save("Sample.docx", FormatType.Docx)
'Releases the resources occupied by WordDocument instance
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
WParagraph paragraph = section.AddParagraph() as WParagraph;
//Adds new shape to the document
Shape rectangle = paragraph.AppendShape(AutoShapeType.RoundedRectangle, 150,
100);
//Sets position for shape
rectangle.VerticalPosition = 72;
rectangle.HorizontalPosition = 72;
paragraph = section.AddParagraph() as WParagraph;
//Adds textbody contents to the shape
paragraph = rectangle.TextBody.AddParagraph() as WParagraph;

Copyright © 2001 - 2019 Syncfusion Inc. 51


DocIO Installing NuGet Packages

IWTextRange text = paragraph.AppendText("This text is in rounded rectangle


shape");
text.CharacterFormat.TextColor = Color.Green;
text.CharacterFormat.Bold = true;
//Adds another shape to the document
paragraph = section.AddParagraph()as WParagraph;
paragraph.AppendBreak(BreakType.LineBreak);
Shape pentagon = paragraph.AppendShape(AutoShapeType.Pentagon, 100, 100);
paragraph = pentagon.TextBody.AddParagraph()as WParagraph;
paragraph.AppendText("This text is in pentagon shape");
pentagon.HorizontalPosition = 72;
pentagon.VerticalPosition = 200;
//Saves the Word document
document.Save("Sample.docx", FormatType.Docx);
//Closes the document
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As WParagraph = TryCast(section.AddParagraph(), WParagraph)
'Adds new shape to the document
Dim rectangle As Shape =
paragraph.AppendShape(AutoShapeType.RoundedRectangle, 150, 100)
'Sets position for shape
rectangle.VerticalPosition = 72
rectangle.HorizontalPosition = 72
paragraph = TryCast(section.AddParagraph(), WParagraph)
'Adds textbody contents to the shape
paragraph = TryCast(rectangle.TextBody.AddParagraph(), WParagraph)
Dim text As IWTextRange = paragraph.AppendText("This text is in rounded
rectangle shape")
text.CharacterFormat.TextColor = Color.Green
text.CharacterFormat.Bold = True
'Adds another shape to the document
paragraph = TryCast(section.AddParagraph(), WParagraph)
paragraph.AppendBreak(BreakType.LineBreak)
Dim pentagon As Shape = paragraph.AppendShape(AutoShapeType.Pentagon, 100,
100)
paragraph = TryCast(pentagon.TextBody.AddParagraph(), WParagraph)
paragraph.AppendText("This text is in pentagon shape")
pentagon.HorizontalPosition = 72
pentagon.VerticalPosition = 200
'Saves the Word document
document.Save("Sample.docx", FormatType.Docx)
'Closes the document
document.Close()

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 52


DocIO Installing NuGet Packages

C#
//Creates an instance of a WordDocument
WordDocument document = new WordDocument();
//Adds a section and a paragraph in the document
document.EnsureMinimal();
//Appends merge field to the last paragraph.
document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField);
//Saves and closes the WordDocument instance.
document.Save("Template.docx");
document.Close();

VB.NET
'Creates an instance of a WordDocument
Dim document As WordDocument = New WordDocument
'Adds a section and a paragraph in the document
document.EnsureMinimal()
'Appends merge field to the last paragraph.
document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField)
'Saves and closes the WordDocument instance.
document.Save("Template.docx")
document.Close()

UWP

C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Finds the first occurrence of a particular text in the document
TextSelection textSelection = document.Find("as graphical contents", false,
true);
//Gets the found text as single text range
WTextRange textRange = textSelection.GetAsOneRange();
//Modifies the text
textRange.Text = "Replaced text";
//Sets highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow;
//Finds the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, "paragraph",
true, false);
//Gets the found text as single text range
WTextRange range = textSelection.GetAsOneRange();
//Sets bold formatting
range.CharacterFormat.Bold = true;
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)

Copyright © 2001 - 2019 Syncfusion Inc. 53


DocIO Installing NuGet Packages

'Find the first occurrence of a particular text in the document


Dim textSelection As TextSelection = document.Find("as graphical contents",
False, True)
'Gets the found text as single text range
Dim textRange As WTextRange = textSelection.GetAsOneRange()
'Modifies the text
textRange.Text = "Replaced text"
'Sets highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow
'Finds the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, "paragraph",
True, False)
'Gets the found text as single text range
Dim range As WTextRange = textSelection.GetAsOneRange()
'Sets bold formatting
range.CharacterFormat.Bold = True
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds the section into the Word document
IWSection section = document.AddSection();
string paraText = "AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.";
//Adds the paragraph into the created section
IWParagraph paragraph = section.AddParagraph();
//Appends the TOC field with LowerHeadingLevel and UpperHeadingLevel to
determines the TOC entries
paragraph.AppendTOC(1, 3);
//Adds the section into the Word document
section = document.AddSection();
//Adds the paragraph into the created section
paragraph = section.AddParagraph();
//Adds the text for the headings
paragraph.AppendText("First Chapter");
//Sets a built-in heading style.
paragraph.ApplyStyle(BuiltinStyle.Heading1);
//Adds the text into the paragraph
section.AddParagraph().AppendText(paraText);
//Adds the section into the Word document
section = document.AddSection();
//Adds the paragraph into the created section
paragraph = section.AddParagraph();
//Adds the text for the headings
paragraph.AppendText("Second Chapter");
//Sets a built-in heading style.
paragraph.ApplyStyle(BuiltinStyle.Heading2);
//Adds the text into the paragraph

Copyright © 2001 - 2019 Syncfusion Inc. 54


DocIO Installing NuGet Packages

section.AddParagraph().AppendText(paraText);
//Adds the section into the Word document
section = document.AddSection();
//Adds the paragraph into the created section
paragraph = section.AddParagraph();
//Adds the text into the headings
paragraph.AppendText("Third Chapter");
//Sets a built-in heading style
paragraph.ApplyStyle(BuiltinStyle.Heading3);
//Adds the text into the paragraph.
section.AddParagraph().AppendText(paraText);
//Updates the table of contents
document.UpdateTableOfContents();
//Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds the section into the Word document
Dim section As IWSection = document.AddSection()
Dim paraText As String = "AdventureWorks Cycles, the fictitious company on
which the AdventureWorks sample databases are based, is a large,
multinational manufacturing company."
'Adds the paragraph into the created section
Dim paragraph As IWParagraph = section.AddParagraph()
'Appends the TOC field with LowerHeadingLevel and UpperHeadingLevel to
determines the TOC entries
paragraph.AppendTOC(1, 3)
'Adds the section into the Word document
section = document.AddSection()
'Adds the paragraph into the created section
paragraph = section.AddParagraph()
'Adds the text for the headings
paragraph.AppendText("First Chapter")
'Sets a built-in heading style
paragraph.ApplyStyle(BuiltinStyle.Heading1)
'Adds the text into the paragraph.
section.AddParagraph().AppendText(paraText)
'Adds the section into the Word document
section = document.AddSection()
'Adds the paragraph into the created section
paragraph = section.AddParagraph()
'Adds the text for the headings
paragraph.AppendText("Second Chapter")
'Sets a built-in heading style
paragraph.ApplyStyle(BuiltinStyle.Heading2)
'Adds the text into the paragraph
section.AddParagraph().AppendText(paraText)
'Adds the section into the Word document
section = document.AddSection()
'Adds the paragraph into the created section
paragraph = section.AddParagraph()
'Adds the text into the headings

Copyright © 2001 - 2019 Syncfusion Inc. 55


DocIO Installing NuGet Packages

paragraph.AppendText("Third Chapter")
'Sets a built-in heading style
paragraph.ApplyStyle(BuiltinStyle.Heading3)
'Adds the text into the paragraph
section.AddParagraph().AppendText(paraText)
'Updates the table of contents
document.UpdateTableOfContents()
‘Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds a section and a paragraph in the document
document.EnsureMinimal();
IWParagraph paragraph = document.LastParagraph;
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.");
//Creates a new text watermark
TextWatermark textWatermark = new TextWatermark();
//Sets the created watermark to the document
document.Watermark = textWatermark;
//Sets the text watermark font size
textWatermark.Size = 72;
//Sets the text watermark layout to Horizontal
textWatermark.Layout = WatermarkLayout.Horizontal;
textWatermark.Semitransparent = false;
//Sets the text watermark text color
textWatermark.Color = Color.Black;
//Sets the text to text watermark text
textWatermark.Text = "TextWatermark";
document.Save("TextWatermark.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds a section and a paragraph in the document
document.EnsureMinimal()
Dim paragraph As IWParagraph = document.LastParagraph
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.")
'Creates a new text watermark
Dim textWatermark As New TextWatermark()
'Sets the text watermark to the document
document.Watermark = textWatermark
'Sets the text watermark font size

Copyright © 2001 - 2019 Syncfusion Inc. 56


DocIO Installing NuGet Packages

textWatermark.Size = 72
'Sets the text watermark layout to Horizontal
textWatermark.Layout = WatermarkLayout.Horizontal
textWatermark.Semitransparent = False
'Sets the text watermark text color
textWatermark.Color = Color.Black
'Sets the text to the text watermark
textWatermark.Text = "TextWatermark"
document.Save("TextWatermark.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds a section and a paragraph in the document
document.EnsureMinimal();
IWParagraph paragraph = document.LastParagraph;
//Appends text to the paragraph
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.");
//Adds comment to a paragraph
WComment comment = paragraph.AppendComment("comment test");
//Specifies the author of the comment
comment.Format.User = "Peter";
//Specifies the initial of the author
comment.Format.UserInitials = "St";
//Set the date and time for comment
comment.Format.DateTime = DateTime.Now;
//Saves and closes the Word document
document.Save("Comment.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds a section and a paragraph in the document
document.EnsureMinimal()
Dim paragraph As IWParagraph = document.LastParagraph
'Appends text to the paragraph
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.")
'Adds comment to a paragraph
Dim comment As WComment = paragraph.AppendComment("comment test")
'Specifies the author of the comment
comment.Format.User = "Peter"
'Specifies the initial of the author
comment.Format.UserInitials = "St"
'Saves and closes the Word document

Copyright © 2001 - 2019 Syncfusion Inc. 57


DocIO Installing NuGet Packages

document.Save("Comment.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
WParagraph paragraph = section.AddParagraph() as WParagraph;
paragraph.AppendText("Gender\t");
//Appends new Checkbox
WCheckBox checkbox = paragraph.AppendCheckBox();
checkbox.Checked = false;
//Sets Checkbox size
checkbox.CheckBoxSize = 10;
checkbox.CalculateOnExit = true;
//Sets help text
checkbox.Help = "Help text";
paragraph.AppendText("Male\t");
checkbox = paragraph.AppendCheckBox();
checkbox.Checked = false;
checkbox.CheckBoxSize = 10;
checkbox.CalculateOnExit = true;
paragraph.AppendText("Female");
//Saves the Word document
document.Save("Checkbox.docx", FormatType.Docx);
//Closes the document
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As WParagraph = TryCast(section.AddParagraph(), WParagraph)
paragraph.AppendText("Gender" & vbTab)
'Appends new Checkbox
Dim checkbox As WCheckBox = paragraph.AppendCheckBox()
checkbox.Checked = False
'Sets Checkbox size
checkbox.CheckBoxSize = 10
checkbox.CalculateOnExit = True
'Sets help text
checkbox.Help = "Help text"
paragraph.AppendText("Male" & vbTab)
checkbox = paragraph.AppendCheckBox()
checkbox.Checked = False
checkbox.CheckBoxSize = 10

Copyright © 2001 - 2019 Syncfusion Inc. 58


DocIO Installing NuGet Packages

checkbox.CalculateOnExit = True
paragraph.AppendText("Female")
'Saves the Word document
document.Save("Checkbox.docx", FormatType.Docx)
'Closes the document
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds section to the document
IWSection sec = document.AddSection();
//Adds paragraph to the section
IWParagraph paragraph = sec.AddParagraph();
//Creates and Appends chart to the paragraph
WChart chart = paragraph.AppendChart(446, 270);
//Sets chart type
chart.ChartType = OfficeChartType.Pie;
//Sets chart title
chart.ChartTitle = "Best Selling Products";
chart.ChartTitleArea.FontName = "Calibri";
chart.ChartTitleArea.Size = 14;
//Sets data for chart
chart.ChartData.SetValue(1, 1, "");
chart.ChartData.SetValue(1, 2, "Sales");
chart.ChartData.SetValue(2, 1, "Phyllis Lapin");
chart.ChartData.SetValue(2, 2, 141.396);
chart.ChartData.SetValue(3, 1, "Stanley Hudson");
chart.ChartData.SetValue(3, 2, 80.368);
chart.ChartData.SetValue(4, 1, "Bernard Shah");
chart.ChartData.SetValue(4, 2, 71.155);
chart.ChartData.SetValue(5, 1, "Patricia Lincoln");
chart.ChartData.SetValue(5, 2, 47.234);
chart.ChartData.SetValue(6, 1, "Camembert Pierrot");
chart.ChartData.SetValue(6, 2, 46.825);
chart.ChartData.SetValue(7, 1, "Thomas Hardy");
chart.ChartData.SetValue(7, 2, 42.593);
chart.ChartData.SetValue(8, 1, "Hanna Moos");
chart.ChartData.SetValue(8, 2, 41.819);
chart.ChartData.SetValue(9, 1, "Alice Mutton");
chart.ChartData.SetValue(9, 2, 32.698);
chart.ChartData.SetValue(10, 1, "Christina Berglund");
chart.ChartData.SetValue(10, 2, 29.171);
chart.ChartData.SetValue(11, 1, "Elizabeth Lincoln");
chart.ChartData.SetValue(11, 2, 25.696);
//Creates a new chart series with the name “Sales”
IOfficeChartSerie pieSeries = chart.Series.Add("Sales");
pieSeries.Values = chart.ChartData[2, 2, 11, 2];
//Sets data label
pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position =
OfficeDataLabelPosition.Outside;

Copyright © 2001 - 2019 Syncfusion Inc. 59


DocIO Installing NuGet Packages

//Sets background color


chart.ChartArea.Fill.ForeColor = Color.FromArgb(242, 242, 242);
chart.PlotArea.Fill.ForeColor = Color.FromArgb(242, 242, 242);
chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None;
//Sets category labels
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 11, 1];
//Saves the document
document.Save("Sample.docx", FormatType.Docx);
//Closes the document
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds section to the document
Dim sec As IWSection = document.AddSection()
'Adds paragraph to the section
Dim paragraph As IWParagraph = sec.AddParagraph()
'Creates and Appends chart to the paragraph
Dim chart As WChart = paragraph.AppendChart(446, 270)
'Sets chart type
chart.ChartType = OfficeChartType.Pie
'Sets chart title
chart.ChartTitle = "Best Selling Products"
chart.ChartTitleArea.FontName = "Calibri"
chart.ChartTitleArea.Size = 14
'Sets data for chart
chart.ChartData.SetValue(1, 1, "")
chart.ChartData.SetValue(1, 2, "Sales")
chart.ChartData.SetValue(2, 1, "Phyllis Lapin")
chart.ChartData.SetValue(2, 2, 141.396)
chart.ChartData.SetValue(3, 1, "Stanley Hudson")
chart.ChartData.SetValue(3, 2, 80.368)
chart.ChartData.SetValue(4, 1, "Bernard Shah")
chart.ChartData.SetValue(4, 2, 71.155)
chart.ChartData.SetValue(5, 1, "Patricia Lincoln")
chart.ChartData.SetValue(5, 2, 47.234)
chart.ChartData.SetValue(6, 1, "Camembert Pierrot")
chart.ChartData.SetValue(6, 2, 46.825)
chart.ChartData.SetValue(7, 1, "Thomas Hardy")
chart.ChartData.SetValue(7, 2, 42.593)
chart.ChartData.SetValue(8, 1, "Hanna Moos")
chart.ChartData.SetValue(8, 2, 41.819)
chart.ChartData.SetValue(9, 1, "Alice Mutton")
chart.ChartData.SetValue(9, 2, 32.698)
chart.ChartData.SetValue(10, 1, "Christina Berglund")
chart.ChartData.SetValue(10, 2, 29.171)
chart.ChartData.SetValue(11, 1, "Elizabeth Lincoln")
chart.ChartData.SetValue(11, 2, 25.696)
'Creates a new chart series with the name “Sales”
Dim pieSeries As IOfficeChartSerie = chart.Series.Add("Sales")
pieSeries.Values = chart.ChartData(2, 2, 11, 2)
'Sets data label
pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsValue = True

Copyright © 2001 - 2019 Syncfusion Inc. 60


DocIO Installing NuGet Packages

pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position =
OfficeDataLabelPosition.Outside
'Sets background color
chart.ChartArea.Fill.ForeColor = Color.FromArgb(242, 242, 242)
chart.PlotArea.Fill.ForeColor = Color.FromArgb(242, 242, 242)
chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None
'Sets category labels
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData(2, 1, 11, 1)
'Saves the document
document.Save("Sample.docx", FormatType.Docx)
'Closes the document
document.Close()

UWP

C#
//Opens an input Word document
WordDocument document = new WordDocument("Template.docx");
//Encrypts the Word document with a password
document.EncryptDocument("password");
//Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Opens an input Word document
Dim document As New WordDocument("Template.docx")
'Encrypts the Word document with a password
document.EncryptDocument("password")
‘Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Creates a section
IWSection section = document.AddSection();
//Adds a paragraph to a section
IWParagraph paragraph = section.AddParagraph();
//Appends the text to paragraph
paragraph.AppendText("Working with footnotes");
//Formats the text
paragraph.ApplyStyle(BuiltinStyle.Heading1);
//Adds a paragraph to a section
paragraph = section.AddParagraph();
//Appends the footnotes

Copyright © 2001 - 2019 Syncfusion Inc. 61


DocIO Installing NuGet Packages

WFootnote footnote = (WFootnote)


paragraph.AppendFootnote(Syncfusion.DocIO.FootnoteType.Footnote);
//Sets the footnote character format
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Inserts the text into the paragraph
paragraph.AppendText("Sample content for footnotes").CharacterFormat.Bold =
true;
//Adds footnote text
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.");
//Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Creates a section
Dim section As IWSection = document.AddSection()
'Adds a paragraph to a section
Dim paragraph As IWParagraph = section.AddParagraph()
'Appends the text to paragraph
paragraph.AppendText("Working with footnotes")
'Formats the text
paragraph.ApplyStyle(BuiltinStyle.Heading1)
'Adds a paragraph to a section
paragraph = section.AddParagraph()
'Appends the footnotes
Dim footnote As WFootnote =
DirectCast(paragraph.AppendFootnote(Syncfusion.DocIO.FootnoteType.Footnote),
WFootnote)
'Sets the footnote character format
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript
'Inserts the text into the paragraph
paragraph.AppendText("Sample content for footnotes").CharacterFormat.Bold =
True
'Adds footnote text
paragraph = footnote.TextBody.AddParagraph()
paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which
the AdventureWorks sample databases are based, is a large, multinational
manufacturing company.")
‘Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Loads the macro-enabled template
WordDocument document = new WordDocument("Template.dotm");

Copyright © 2001 - 2019 Syncfusion Inc. 62


DocIO Installing NuGet Packages

//Gets the table


DataTable table = GetDataTable();
//Executes Mail Merge with groups
document.MailMerge.ExecuteGroup(table);
//Saves and closes the document
document.Save("Sample.docm", FormatType.Word2013Docm);
document.Close();

VB.NET
'Loads the macro-enabled template
Dim document As New WordDocument("Template.dotm")
'Gets the table
Dim table As DataTable = GetDataTable()
'Executes Mail Merge with groups
document.MailMerge.ExecuteGroup(table)
'Saves and closes the document
document.Save("Sample.docm", FormatType.Word2013Docm)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
WTextBody textBody = section.Body;
//Adds block content control into Word document
BlockContentControl blockContentControl =
textBody.AddBlockContentControl(ContentControlType.RichText) as
BlockContentControl;
//Adds new paragraph in the block content control
WParagraph paragraph = blockContentControl.TextBody.AddParagraph() as
WParagraph;
//Adds new text to the paragraph
paragraph.AppendText("Block content control");
//Adds new table to the block content control
WTable table = blockContentControl.TextBody.AddTable() as WTable;
//Specifies the total number of rows and columns
table.ResetCells(2, 3);
//Adds new paragraph to the block content control
paragraph = blockContentControl.TextBody.AddParagraph() as WParagraph;
//Adds image to the paragraph
paragraph.AppendPicture(Image.FromFile("Image.png"));
//Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As WordDocument = New WordDocument

Copyright © 2001 - 2019 Syncfusion Inc. 63


DocIO Installing NuGet Packages

'Adds new section to the document


Dim section As IWSection = document.AddSection
Dim textBody As WTextBody = section.Body
'Adds block content control into Word document
Dim blockContentControl As BlockContentControl =
CType(textBody.AddBlockContentControl(ContentControlType.RichText),
BlockContentControl)
'Adds new paragraph in the block content control
Dim paragraph As WParagraph =
CType(blockContentControl.TextBody.AddParagraph, WParagraph)
'Adds new text to the paragraph
paragraph.AppendText("Block content control")
'Adds new table to the block content control
Dim table As WTable = CType(blockContentControl.TextBody.AddTable, WTable)
'Specifies the total number of rows and columns
table.ResetCells(2, 3)
'Adds new paragraph to the block content control
paragraph = CType(blockContentControl.TextBody.AddParagraph, WParagraph)
'Adds image to the paragraph
paragraph.AppendPicture(Image.FromFile("Image.png"))
'Saves and closes the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds one section and one paragraph to the document
document.EnsureMinimal();
//Appends a new mathematical equation to the paragraph
WMath math = document.LastParagraph.AppendMath();
//Adds a new math
IOfficeMath officeMath = math.MathParagraph.Maths.Add();
//Adds an accent equation
IOfficeMathAccent mathAccent =
officeMath.Functions.Add(MathFunctionType.Accent) as IOfficeMathAccent;
//Sets the accent character
mathAccent.AccentCharacter = "̆";
//Adds the run element for accent
IOfficeMathRunElement officeMathRunElement =
mathAccent.Equation.Functions.Add(MathFunctionType.RunElement) as
IOfficeMathRunElement;
officeMathRunElement.Item = new WTextRange(document);
WTextRange textRange = officeMathRunElement.Item as WTextRange;
//Sets text for accent equation
textRange.Text = "a";
//Applies character formatting for text range
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.Italic = true;
//Saves the Word document
document.Save("Sample.docx", FormatType.Docx);
//Closes the document

Copyright © 2001 - 2019 Syncfusion Inc. 64


DocIO Installing NuGet Packages

document.Close();

VB.NET
'Creates a new Word document
Dim document As WordDocument = New WordDocument
'Adds one section and one paragraph to the document
document.EnsureMinimal()
'Appends a new mathematical equation to the paragraph
Dim math As WMath = document.LastParagraph.AppendMath
'Adds a new math
Dim officeMath As IOfficeMath = math.MathParagraph.Maths.Add
'Adds an accent equation
Dim mathAccent As IOfficeMathAccent =
CType(officeMath.Functions.Add(MathFunctionType.Accent), IOfficeMathAccent)
'Sets the accent character
mathAccent.AccentCharacter = ""
Dim officeMathRunElement As IOfficeMathRunElement =
CType(mathAccent.Equation.Functions.Add(MathFunctionType.RunElement),
IOfficeMathRunElement)
officeMathRunElement.Item = New WTextRange(document)
Dim textRange As WTextRange = CType(officeMathRunElement.Item, WTextRange)
'Sets text for accent equation
textRange.Text = "a"
'Applies character formatting for text range
textRange.CharacterFormat.Bold = True
textRange.CharacterFormat.Italic = True
'Saves the Word document
document.Save("Sample.docx", FormatType.Docx)
'Closes the document
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Appends text to the paragraph
IWTextRange text = paragraph.AppendText("This sample illustrates how to
track the changes made to the word document. ");
//Sets font name and size for text
text.CharacterFormat.FontName = "Times New Roman";
text.CharacterFormat.FontSize = 14;
text = paragraph.AppendText("This track changes is useful in shared
environment.");
text.CharacterFormat.FontSize = 12;
//Turns on the track changes option
document.TrackChanges = true;
//Saves and closes the document

Copyright © 2001 - 2019 Syncfusion Inc. 65


DocIO Installing NuGet Packages

document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Appends text to the paragraph
Dim text As IWTextRange = paragraph.AppendText("This sample illustrates how
to track the changes made to the word document. ")
'Sets font name and size for text
text.CharacterFormat.FontName = "Times New Roman"
text.CharacterFormat.FontSize = 14
text = paragraph.AppendText("This track changes is useful in shared
environment.")
text.CharacterFormat.FontSize = 12
'Turns on the track changes option
document.TrackChanges = True
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

UWP

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Creates built-in style and modifies its properties
Style style = Style.CreateBuiltinStyle(BuiltinStyle.Heading1, document) as
Style;
style.CharacterFormat.Italic = true;
style.CharacterFormat.TextColor = Color.DarkGreen;
//Adds it to the styles collection
document.Styles.Add(style);
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
IWTextRange text = paragraph.AppendText("A built-in style is modified and is
applied to this paragraph.");
//Applies the new style to paragraph
paragraph.ApplyStyle(style.Name);
//Saves the Word document
document.Save("Sample.docx", FormatType.Docx);
//Closes the document
document.Close();

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 66


DocIO Installing NuGet Packages

'Creates a new Word document


Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Creates built-in style and modifies its properties
Dim style__1 As Style =
TryCast(Style.CreateBuiltinStyle(BuiltinStyle.Heading1, document), Style)
style__1.CharacterFormat.Italic = True
style__1.CharacterFormat.TextColor = Color.DarkGreen
'Adds it to the styles collection
document.Styles.Add(style__1)
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
Dim text As IWTextRange = paragraph.AppendText("A built-in style is modified
and is applied to this paragraph.")
'Applies the new style to paragraph
paragraph.ApplyStyle(style__1.Name)
'Saves the Word document
document.Save("Sample.docx", FormatType.Docx)
'Closes the document
document.Close()

How to open a document from stream using DocIO?


A document can be opened as stream by using HttpWebResponse. This stream does not support seek
operation and so the contents should be read manually to get the position and length of the stream. The
following code illustrates how to load the document from stream.
C#
//Gets the document as stream
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://www.swiftview.com/tech/letterlega
l5.doc");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
//Converts it to byte array
byte[] buffer = ReadFully(stream, 32768);
//Stores bytes into the memory stream.
MemoryStream ms = new MemoryStream();
ms.Write(buffer, 0, buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
stream.Close();
//Creates a new document.
WordDocument document = new WordDocument();
//Opens the template document from the MemoryStream.
document.Open(ms, FormatType.Doc);
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Gets the document as stream

Copyright © 2001 - 2019 Syncfusion Inc. 67


DocIO Installing NuGet Packages

Dim request As HttpWebRequest =


DirectCast(WebRequest.Create("https://www.swiftview.com/tech/letterlegal5.do
c"), HttpWebRequest)
Dim response As HttpWebResponse = DirectCast(request.GetResponse(),
HttpWebResponse)
Dim stream As Stream = response.GetResponseStream()
'Converts it to byte array
Dim buffer As Byte() = ReadFully(stream, 32768)
'Stores bytes into the memory stream.
Dim ms As New MemoryStream()
ms.Write(buffer, 0, buffer.Length)
ms.Seek(0, SeekOrigin.Begin)
stream.Close()
'Creates a new document.
Dim document As New WordDocument ()
'Opens the template document from the MemoryStream.
document.Open(ms, FormatType.Doc)
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code illustrates the method used to read the stream and convert the stream to bytes.
C#
public static byte[] ReadFully(Stream stream, int initialLength)
{
//When an unhelpful initial length has been passed, just use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
//After reaching the end of the buffer, check and see whether you can find
any information.
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
//End of stream? Then, you are done.
if (nextByte == -1)
{
return buffer;
}
//Resize the buffer, put in the byte you have just read, and continue.
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}

Copyright © 2001 - 2019 Syncfusion Inc. 68


DocIO Installing NuGet Packages

//Buffer is now too big. Shrink it.


byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}

VB.NET
Public Shared Function ReadFully(stream As Stream, initialLength As Integer)
As Byte()
'When an unhelpful initial length has been passed, just use 32K.
If initialLength < 1 Then
initialLength = 32768
End If
Dim buffer As Byte() = New Byte(initialLength - 1) {}
Dim read As Integer = 0
Dim chunk As Integer
chunk = stream.Read(buffer, read, buffer.Length - read)
While (chunk > 0)
read += chunk
'After reaching the end of the buffer, check and see whether you can find
any information.
If read = buffer.Length Then
Dim nextByte As Integer = stream.ReadByte()
'End of stream? Then, you are done.
If nextByte = -1 Then
Return buffer
End If
'Resize the buffer, put in the byte you have just read, and continue.
Dim newBuffer As Byte() = New Byte(buffer.Length * 2 - 1) {}
Array.Copy(buffer, newBuffer, buffer.Length)
newBuffer(read) = CByte(nextByte)
buffer = newBuffer
read += 1
End If
End While
'Buffer is now too big. Shrink it.
Dim ret As Byte() = New Byte(read - 1) {}
Array.Copy(buffer, ret, read)
Return ret
End Function

How to set OpenType Font Features?


The Open type features provide special effects for the text. This feature is specific to Word 2010 and
later version documents. The OpenType features includes the following:

 Ligatures – combination of characters, written as glyph


 Use Contextual Alternates – combination of letters based on surrounding characters
 Number spacing – specifies number width
 Number forms – specifies number height
 Stylistic sets – specifies the look of the text, based on the font used

The following code illustrates how to set ligature types for text.

Copyright © 2001 - 2019 Syncfusion Inc. 69


DocIO Installing NuGet Packages

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text
IWTextRange text = paragraph.AppendText("Text to describe discretional
ligatures");
//Sets ligature type
text.CharacterFormat.Ligatures = LigatureType.Discretional;
text.CharacterFormat.FontName = "Arial";
paragraph = section.AddParagraph();
text = paragraph.AppendText("Text to describe contextual ligatures");
text.CharacterFormat.Ligatures = LigatureType.Contextual;
text.CharacterFormat.FontName = "Arial";
paragraph = section.AddParagraph();
text = paragraph.AppendText("Text to describe historical ligatures");
text.CharacterFormat.Ligatures = LigatureType.Historical;
text.CharacterFormat.FontName = "Arial";
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text
Dim text As IWTextRange = paragraph.AppendText("Text to describe
discretional ligatures")
'Sets ligature type as Discretional
text.CharacterFormat.Ligatures = LigatureType.Discretional
text.CharacterFormat.FontName = "Arial"
paragraph = section.AddParagraph()
text = paragraph.AppendText("Text to describe contextual ligatures")
'Sets ligature type as Contextual
text.CharacterFormat.Ligatures = LigatureType.Contextual
text.CharacterFormat.FontName = "Arial"
paragraph = section.AddParagraph()
text = paragraph.AppendText("Text to describe historical ligatures")
'Sets ligature type as Historical
text.CharacterFormat.Ligatures = LigatureType.Historical
text.CharacterFormat.FontName = "Arial"
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code example illustrates how to set contextual alternates.

Copyright © 2001 - 2019 Syncfusion Inc. 70


DocIO Installing NuGet Packages

C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text
IWTextRange text = paragraph.AppendText("Text to describe contextual
alternates");
text.CharacterFormat.FontName = "Segoe Script";
//Sets contextual alternates
text.CharacterFormat.UseContextualAlternates = true;
paragraph = section.AddParagraph();
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text
Dim text As IWTextRange = paragraph.AppendText("Text to describe contextual
alternates")
text.CharacterFormat.FontName = "Segoe Script"
'Sets contextual alternates
text.CharacterFormat.UseContextualAlternates = True
paragraph = section.AddParagraph()
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code example illustrates how to set number spacing.


C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text
IWTextRange text = paragraph.AppendText("Numbers to describe tabular number
spacing 0123456789");
text.CharacterFormat.FontName = "Calibri";
//Sets number spacing
text.CharacterFormat.NumberSpacing = NumberSpacingType.Tabular;
paragraph = section.AddParagraph();

Copyright © 2001 - 2019 Syncfusion Inc. 71


DocIO Installing NuGet Packages

text = paragraph.AppendText("Numbers to describe proportional number spacing


0123456789");
text.CharacterFormat.FontName = "Calibri";
//Sets number spacing
text.CharacterFormat.NumberSpacing = NumberSpacingType.Proportional;
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text
Dim text As IWTextRange = paragraph.AppendText("Numbers to describe tabular
number spacing 0123456789")
text.CharacterFormat.FontName = "Calibri"
'Sets number spacing
text.CharacterFormat.NumberSpacing = NumberSpacingType.Tabular
paragraph = section.AddParagraph()
text = paragraph.AppendText("Numbers to describe proportional number spacing
0123456789")
text.CharacterFormat.FontName = "Calibri"
'Sets number spacing
text.CharacterFormat.NumberSpacing = NumberSpacingType.Proportional
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code example illustrates how to set number style.


C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text
IWTextRange text = paragraph.AppendText("Numbers to describe oldstyle number
form 0123456789");
text.CharacterFormat.FontName = "Calibri";
//Sets number style
text.CharacterFormat.NumberForm = NumberFormType.OldStyle;
paragraph = section.AddParagraph();
text = paragraph.AppendText("Numbers to describe lining number form
0123456789");
text.CharacterFormat.FontName = "Calibri";
//Sets number style
text.CharacterFormat.NumberForm = NumberFormType.Lining;
//Saves and closes the document

Copyright © 2001 - 2019 Syncfusion Inc. 72


DocIO Installing NuGet Packages

document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document
Dim document As New WordDocument()
'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text
Dim text As IWTextRange = paragraph.AppendText("Numbers to describe oldstyle
number form 0123456789")
text.CharacterFormat.FontName = "Calibri"
'Sets number style
text.CharacterFormat.NumberForm = NumberFormType.OldStyle
paragraph = section.AddParagraph()
text = paragraph.AppendText("Numbers to describe lining number form
0123456789")
text.CharacterFormat.FontName = "Calibri"
'Sets number style
text.CharacterFormat.NumberForm = NumberFormType.Lining
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code example illustrates how to set different styles for the text.
C#
//Creates a new Word document
WordDocument document = new WordDocument();
//Adds new section to the document
IWSection section = document.AddSection();
//Adds new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Adds new text
IWTextRange text = paragraph.AppendText("Text to describe stylistic sets");
text.CharacterFormat.FontName = "Gabriola";
//Sets stylistic set
text.CharacterFormat.StylisticSet = StylisticSetType.StylisticSet06;
paragraph = section.AddParagraph();
//Adds new text
text = paragraph.AppendText("Text to describe stylistic sets");
text.CharacterFormat.FontName = "Gabriola";
//Sets stylistic set
text.CharacterFormat.StylisticSet = StylisticSetType.StylisticSet15;
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates a new Word document

Copyright © 2001 - 2019 Syncfusion Inc. 73


DocIO Installing NuGet Packages

Dim document As New WordDocument()


'Adds new section to the document
Dim section As IWSection = document.AddSection()
'Adds new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Adds new text
Dim text As IWTextRange = paragraph.AppendText("Text to describe stylistic
sets")
text.CharacterFormat.FontName = "Gabriola"
'Sets stylistic set
text.CharacterFormat.StylisticSet = StylisticSetType.StylisticSet06
paragraph = section.AddParagraph()
'Adds new text
text = paragraph.AppendText("Text to describe stylistic sets")
text.CharacterFormat.FontName = "Gabriola"
'Sets stylistic set
text.CharacterFormat.StylisticSet = StylisticSetType.StylisticSet15
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

How to attach a Template to a Word document?


The following code illustrates how to set the template for the document.
C#
//Loads a source document
WordDocument document = new WordDocument("Template.docx");
//Attaches the template document to the source document
document.AttachedTemplate.Path = @"D:\Data\Template.docx";
//Updates the styles of the document from the attached template each time
the document is opened
document.UpdateStylesOnOpen = true;
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads a source document
Dim document As New WordDocument("Template.docx")
'Attaches the template document to the source document
document.AttachedTemplate.Path = "D:\Data\Template.docx"
'Updates the styles of the document from the attached template each time the
document is opened
document.UpdateStylesOnOpen = True
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

How to insert a DataTable in a Word document?


You can create new table in a Word document and copy the contents from data table. The following
code illustrates how to insert a data table as table in a Word document.

Copyright © 2001 - 2019 Syncfusion Inc. 74


DocIO Installing NuGet Packages

C#
//Creates new Word document
WordDocument document = new WordDocument();
//Creates new data set and data table
DataSet dataset = new DataSet();
GetDataTable(dataset);
DataTable datatable = new DataTable();
datatable = dataset.Tables[0];
//Adds new section
IWSection section = document.AddSection();
//Adds new table
IWTable table = section.AddTable();
//Adds new row to the table
WTableRow row = table.AddRow();
foreach (DataColumn datacolumn in datatable.Columns)
{
//Sets the column names for the table from the data table column names and
cell width
WTableCell cell = row.AddCell();
cell.AddParagraph().AppendText(datacolumn.ColumnName);
cell.Width = 150;
}
//Iterates through data table rows
foreach (DataRow datarow in datatable.Rows)
{
//Adds new row to the table
row = table.AddRow(true, false);
foreach (object datacolumn in datarow.ItemArray)
{
//Adds new cell
WTableCell cell = row.AddCell();
//Adds contents from the data table to the table cell
cell.AddParagraph().AppendText(datacolumn.ToString());
}
}
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates new Word document
Dim document As New WordDocument()
'Creates new data set and data table
Dim dataset As New DataSet()
GetDataTable(dataset)
Dim datatable As New DataTable()
datatable = dataset.Tables(0)
'Adds new section
Dim section As IWSection = document.AddSection()
'Adds new table
Dim table As IWTable = section.AddTable()
'Adds new row to the table
Dim row As WTableRow = table.AddRow()
For Each datacolumn As DataColumn In datatable.Columns

Copyright © 2001 - 2019 Syncfusion Inc. 75


DocIO Installing NuGet Packages

'Sets the column names for the table from the data table column names and
cell width
Dim cell As WTableCell = row.AddCell()
cell.AddParagraph().AppendText(datacolumn.ColumnName)
cell.Width = 150
Next
'Iterates through data table rows
For Each datarow As DataRow In datatable.Rows
'Adds new row to the table
row = table.AddRow(True, False)
For Each datacolumn As Object In datarow.ItemArray
'Adds new cell
Dim cell As WTableCell = row.AddCell()
'Adds contents from the data table to the table cell
cell.AddParagraph().AppendText(datacolumn.ToString())
Next
Next
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code illustrates the method to get data table.


C#
private void GetDataTable(DataSet dataset)
{
// List of syncfusion products.
string[] products = { "DocIO", "PDF", "XlsIO" };
// Adds new Tables to the data set.
DataRow row;
dataset.Tables.Add();
// Adds fields to the Products table.
dataset.Tables[0].TableName = "Products";
dataset.Tables[0].Columns.Add("ProductName");
dataset.Tables[0].Columns.Add("Binary");
dataset.Tables[0].Columns.Add("Source");
// Inserts values to the tables.
foreach (string product in products)
{
row = dataset.Tables["Products"].NewRow();
row["ProductName"] = string.Concat("Essential ", product);
row["Binary"] = "$895.00";
row["Source"] = "$1,295.00";
dataset.Tables["Products"].Rows.Add(row);
}
}

VB.NET
Private Sub GetDataTable(dataset As DataSet)
'List of syncfusion products.
Dim products As String() = {"DocIO", "PDF", "XlsIO"}
'Adds new Tables to the data set.
Dim row As DataRow
dataset.Tables.Add()

Copyright © 2001 - 2019 Syncfusion Inc. 76


DocIO Installing NuGet Packages

'Adds fields to the Products table.


dataset.Tables(0).TableName = "Products"
dataset.Tables(0).Columns.Add("ProductName")
dataset.Tables(0).Columns.Add("Binary")
dataset.Tables(0).Columns.Add("Source")
'Inserts values to the tables.
For Each product As String In products
row = dataset.Tables("Products").NewRow()
row("ProductName") = String.Concat("Essential ", product)
row("Binary") = "$895.00"
row("Source") = "$1,295.00"
dataset.Tables("Products").Rows.Add(row)
Next
End Sub

How to insert a table from HTML string in Word document?


An HTML string can be inserted to the Word document at text body or paragraph. The following code
illustrates how to insert a table to the document from the HTML string.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx");
//Gets the text body
WTextBody textbody = document.Sections[0].Body;
//Html string that represents table with two rows and two columns
string htmlString = " <table border='1'><tr><td><p>First Row First
Cell</p></td><td><p>First Row Second Cell</p></td></tr><tr><td><p>Second Row
First Cell</p></td><td><p>Second Row Second Cell</p></td></tr></table> ";
//Inserts the string to the text body
textbody.InsertXHTML(htmlString);
//Saves and closes the document
document.Save("Sample.docx");
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
'Gets the text body
Dim textbody As WTextBody = document.Sections(0).Body
'Html string that represents table with two rows and two columns
Dim htmlString As String = " <table border='1'><tr><td><p>First Row First
Cell</p></td><td><p>First Row Second Cell</p></td></tr><tr><td><p>Second Row
First Cell</p></td><td><p>Second Row Second Cell</p></td></tr></table> "
'Inserts the string to the text body
textbody.InsertXHTML(htmlString)
'Saves and closes the document
document.Save("Sample.docx")
document.Close()

How to set table cell width?


Each cell in the table can have its own width. The following code illustrates how to set the width of the
cell.

Copyright © 2001 - 2019 Syncfusion Inc. 77


DocIO Installing NuGet Packages

C#
//Creates new word document
WordDocument document = new WordDocument("Template.docx");
//Gets the text body of first section
WTextBody textbody = document.Sections[0].Body;
//Gets the table
IWTable table = textbody.Tables[0];
//Iterates through table rows
foreach (WTableRow row in table.Rows)
{
//Sets width for cells
for (int i = 0; i < row.Cells.Count; i++)
{
WTableCell cell = row.Cells[i];
if (i % 2 == 0)
//Sets width as 100 for cells in even column
cell.Width = 100;
else
//Sets width as 150 for cell in odd column
cell.Width = 150;
}
}
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Creates new word document
Dim document As New WordDocument("Template.docx")
'Gets the text body of first section
Dim textbody As WTextBody = document.Sections(0).Body
'Gets the table
Dim table As IWTable = textbody.Tables(0)
'Iterates through table rows
For Each row As WTableRow In table.Rows
'Sets width for cells
For i As Integer = 0 To row.Cells.Count - 1
Dim cell As WTableCell = row.Cells(i)
If i Mod 2 = 0 Then
'Sets width as 100 for cells in even column
cell.Width = 100
Else
'Sets width as 150 for cell in odd column
cell.Width = 150
End If
Next
Next
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

Copyright © 2001 - 2019 Syncfusion Inc. 78


DocIO Installing NuGet Packages

How to position a table in a Word document?


You can position a table in a Word document by setting position properties. The following code
illustrates how to set position properties for a table.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx");
//Gets the text body of first section
WTextBody textbody = document.Sections[0].Body;
//Gets the table
IWTable table = textbody.Tables[0];
//Sets the horizontal and vertical position for table
table.TableFormat.Positioning.HorizPosition = 40;
table.TableFormat.Positioning.VertPosition = 100;
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
'Gets the text body of first section
Dim textbody As WTextBody = document.Sections(0).Body
'Gets the table
Dim table As IWTable = textbody.Tables(0)
'Sets the horizontal and vertical position for table
table.TableFormat.Positioning.HorizPosition = 40
table.TableFormat.Positioning.VertPosition = 100
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

How to set the text direction to a table in Word document?


The contents of the table cell can be in vertical or horizontal direction. Each cell content can have
different text direction. The following code illustrates how to set the text direction for the text in the
table.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx");
//Gets the text body of first section
WTextBody textbody = document.Sections[0].Body;
//Gets the table
IWTable table = textbody.Tables[0];
//Iterates through table rows
foreach (WTableRow row in table.Rows)
{
foreach (WTableCell cell in row.Cells)
{
//Sets the text direction for the contents
cell.CellFormat.TextDirection = Syncfusion.DocIO.DLS.TextDirection.Vertical;
}

Copyright © 2001 - 2019 Syncfusion Inc. 79


DocIO Installing NuGet Packages

}
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
'Gets the text body of first section
Dim textbody As WTextBody = document.Sections(0).Body
'Gets the table
Dim table As IWTable = textbody.Tables(0)
'Iterates through table rows
For Each row As WTableRow In table.Rows
For Each cell As WTableCell In row.Cells
'Sets the text direction for the contents
cell.CellFormat.TextDirection = Syncfusion.DocIO.DLS.TextDirection.Vertical
Next
Next
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

How to extract the images in the document?


The following code illustrates how to extract the images in the document.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx");
WTextBody textbody = document.Sections[0].Body;
Image image;
int i = 1;
//Iterates through the paragraphs
foreach (WParagraph paragraph in textbody.Paragraphs)
{
//Iterates through the paragraph items
foreach (ParagraphItem item in paragraph.ChildEntities)
{
//Gets the picture and saves it into specified location
switch (item.EntityType)
{
case EntityType.Picture:
WPicture picture = item as WPicture;
image = picture.Image;
image.Save(@"D:\Data\Image" + i + ".jpeg", ImageFormat.Jpeg);
i++;
break;
default:
break;
}
}
}
//Closes the document
document.Close();

Copyright © 2001 - 2019 Syncfusion Inc. 80


DocIO Installing NuGet Packages

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
Dim textbody As WTextBody = document.Sections(0).Body
Dim image As Image
Dim i As Integer = 1
'Iterates through the paragraphs
For Each paragraph As WParagraph In textbody.Paragraphs
'Iterates through the paragraph items
For Each item As ParagraphItem In paragraph.ChildEntities
'Gets the picture and saves it into specified location
Select Case item.EntityType
Case EntityType.Picture
Dim picture As WPicture = TryCast(item, WPicture)
image = picture.Image
image.Save("D:\Data\Image" & i & ".jpeg", ImageFormat.Jpeg)
i += 1
Exit Select
Case Else
Exit Select
End Select
Next
Next
'Close the document
document.Close()

The images in the document can be extracted into a specific location when exporting it to HTML file. The
following code illustrates how to extract images.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx");
//Sets the location to extract images
document.SaveOptions.HtmlExportImagesFolder = @"D:\Data\";
//Saves the document as html file
HTMLExport export = new HTMLExport();
export.SaveAsXhtml(document, "Template.html");
//Closes the document
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
'Sets the location to extract images
document.SaveOptions.HtmlExportImagesFolder = "D:\Data\"
'Saves the document as html file
Dim export As New HTMLExport()
export.SaveAsXhtml(document, "Template.html")
'Closes the document
document.Close()

Copyright © 2001 - 2019 Syncfusion Inc. 81


DocIO Installing NuGet Packages

How to remove headers and footers from the document?


The following code illustrates how to remove the header contents from the document.
C#
//Loads the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Iterates through the sections
foreach (WSection section in document.Sections)
{
HeaderFooter header;
//Gets even footer of current section
header = section.HeadersFooters[HeaderFooterType.EvenHeader];
//Removes even footer
header.ChildEntities.Clear();
//Gets odd footer of current section
header = section.HeadersFooters[HeaderFooterType.OddHeader];
//Removes odd footer
header.ChildEntities.Clear();
//Gets first page footer
header = section.HeadersFooters[HeaderFooterType.FirstPageHeader];
//Removes first page footer
header.ChildEntities.Clear();
}
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Iterates through the sections
For Each section As WSection In document.Sections
Dim header As HeaderFooter
'Gets even footer of current section
header = section.HeadersFooters(HeaderFooterType.EvenHeader)
'Removes even footer
header.ChildEntities.Clear()
'Gets odd footer of current section
header = section.HeadersFooters(HeaderFooterType.OddHeader)
'Removes odd footer
header.ChildEntities.Clear()
'Gets first page footer
header = section.HeadersFooters(HeaderFooterType.FirstPageHeader)
'Removes first page footer
header.ChildEntities.Clear()
Next
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

The following code illustrates how to remove the footer contents from the document.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 82


DocIO Installing NuGet Packages

//Loads the template document


WordDocument document = new WordDocument("Template.docx");
//Iterates through the sections
foreach (WSection section in document.Sections)
{
HeaderFooter footer;
//Gets even footer of current section
footer = section.HeadersFooters[HeaderFooterType.EvenFooter];
//Removes even footer
footer.ChildEntities.Clear();
//Gets odd footer of current section
footer = section.HeadersFooters[HeaderFooterType.OddFooter];
//Removes odd footer
footer.ChildEntities.Clear();
//Gets first page footer
footer = section.HeadersFooters[HeaderFooterType.FirstPageFooter];
//Removes first page footer
footer.ChildEntities.Clear();
}
//Saves and closes the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the template document
Dim document As New WordDocument("Template.docx")
'Iterates through the sections
For Each section As WSection In document.Sections
Dim footer As HeaderFooter
'Gets even footer of current section
footer = section.HeadersFooters(HeaderFooterType.EvenFooter)
'Removes even footer
footer.ChildEntities.Clear()
'Gets odd footer of current section
footer = section.HeadersFooters(HeaderFooterType.OddFooter)
'Removes odd footer
footer.ChildEntities.Clear()
'Gets first page footer
footer = section.HeadersFooters(HeaderFooterType.FirstPageFooter)
'Removes first page footer
footer.ChildEntities.Clear()
Next
'Saves and closes the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()

Which units does Essential DocIO uses for measurement properties such as size, margins, etc, in
a Word document?
Essential DocIO library uses Points for measurement properties in a Word document.

Copyright © 2001 - 2019 Syncfusion Inc. 83


DocIO Installing NuGet Packages

Could not find Syncfusion.OfficeChartToImageConverter assembly in .NET 3.5 Framework, does it


mean there is no support for chart conversion in this Framework?
Yes, OfficeChartToImageConverter assembly is not supported in .NET 3.5 Framework and it is available
in .NET 4.0 Framework.
Can the chart data be refreshed?
Yes, Essential DocIO supports refreshing the chart data. For more details, refer Working with charts
Is it possible to convert 3D charts to PDF or image?
Current version of the DocIO library does not provide support for converting 3D charts to PDF or image
format.
Is it possible to specify PDF conformance level in Word to PDF conversion?
Yes, you can specify the PDF conformance level in Word to PDF conversion. For more details, refer PDF
Conformance
Migration from Microsoft Office Automation to Essential DocIO
Mail merge
The Mail merge feature can be used to generate reports and letters in Microsoft Word. The following
code examples show how to generate an employee report from an MDB data source by using Office
Automation and DocIO.
Using Microsoft Office Automation
Office Automation performs the Mail merge by executing a SQL query on the Word document. The
output of the Mail merge can be sent to a new Word document. Alternatively, it can be sent to a printer,
a fax machine, or forwarded to an e-mail address.
C#
using word = Microsoft.Office.Interop.Word;
------------
//Initializes objects.
object nullobject = Missing.Value;
object filepath = "Sample.docx";
object sqlStmt = "SELECT * FROM [Employees]";
string sDBPath = "Northwind.mdb";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Performs Mail Merge.
document.MailMerge.OpenDataSource(sDBPath, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref sqlStmt, ref nullobject,
ref nullobject, ref nullobject);
document.MailMerge.Execute(ref nullobject);
//Sends output of Mail Merge to a new document.

Copyright © 2001 - 2019 Syncfusion Inc. 84


DocIO Installing NuGet Packages

document.MailMerge.Destination =
word.WdMailMergeDestination.wdSendToNewDocument;
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
-------------
'Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filepath As Object = "Sample.docx"
Dim sqlStmt As Object = "SELECT * FROM [Employees]"
Dim sDBPath As String = "Northwind.mdb"
'Starts the Word application.
Dim wordApp As New word.Application()
'Opens the Word document.
Dim document As word.Document = wordApp.Documents.Open(filepath, nullobject,
nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Performs Mail Merge.
document.MailMerge.OpenDataSource(sDBPath, nullobject, nullobject,
nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
sqlStmt, nullobject, nullobject, nullobject)
document.MailMerge.Execute(nullobject)
'Sends output of Mail Merge to a new document.
document.MailMerge.Destination =
word.WdMailMergeDestination.wdSendToNewDocument
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO
DocIO performs Mail merge by using the following methods:

 Execute
 ExecuteGroup
 ExecuteNestedGroup

The following code example performs Mail merge by using the Execute method.
C#
string dataBase = "Northwind.mdb";
//Opens existing template.
WordDocument doc = new WordDocument("Template.docx", FormatType.Docx);
//Gets Data from the Database.

Copyright © 2001 - 2019 Syncfusion Inc. 85


DocIO Installing NuGet Packages

OleDbConnection conn = new


OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase);
conn.Open();
//Populates the data table.
DataTable table = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from employees",
conn);
adapter.Fill(table);
adapter.Dispose();
//Performs Mail Merge.
doc.MailMerge.Execute(table);
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();

VB.NET
Dim dataBase As String = "Northwind.mdb"
‘Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx")
‘Creates database connection.
Dim conn As OleDbConnection = New
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase)
conn.Open()
‘Populates data table.
Dim table As DataTable = New DataTable()
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter("select * from
employees", conn)
adapter.Fill(table)
adapter.Dispose()
‘Performs Mail Merge.
doc.MailMerge.Execute(table)
‘Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
doc.Close()

Note:
For more information on Mail merge using DocIO, you can refer to online documentation link:
MailMerge
Find and Replace
This section illustrates how to perform a simple find and replace operation in a Word document by using
Microsoft Office Automation and DocIO.
Using Microsoft Office Automation
The following code example illustrates how to search for a word in a Word document, replace it with
another word and save the document under a new name.
C#
using word = Microsoft.Office.Interop.Word;
---------

Copyright © 2001 - 2019 Syncfusion Inc. 86


DocIO Installing NuGet Packages

//Initializes objects.
object nullobject = Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object item = word.WdGoToItem.wdGoToPage;
object whichItem = word.WdGoToDirection.wdGoToFirst;
object replaceAll = word.WdReplace.wdReplaceAll;
object forward = true;
object matchAllWord = true;
object matchCase = false;
object originalText = "Hello";
object replaceText = "World";
object save = true;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref
nullobject, ref nullobject,
ref nullobject, ref nullobject,ref nullobject, ref nullobject, ref
nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject,
ref nullobject);
wordApp.Visible = false;
//Searches and replaces text.
document.GoTo(ref item, ref whichItem, ref nullobject, ref nullobject);
foreach (word.Range rng in document.StoryRanges)
{
rng.Find.Execute(ref originalText, ref matchCase, ref matchAllWord, ref
nullobject, ref nullobject,
ref nullobject, ref forward,ref nullobject, ref nullobject, ref replaceText,
ref replaceAll,
ref nullobject, ref nullobject, ref nullobject, ref nullobject);
}
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject,
ref nullobject, ref nullobject, refnullobject, ref nullobject,
ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
‘Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filePath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim item As Object = word.WdGoToItem.wdGoToPage
Dim whichItem As Object = word.WdGoToDirection.wdGoToFirst

Copyright © 2001 - 2019 Syncfusion Inc. 87


DocIO Installing NuGet Packages

Dim replaceAll As Object = word.WdReplace.wdReplaceAll


Dim forward As Object = True
Dim matchAllWord As Object = True
Dim matchCase As Object = False
Dim originalText As Object = "Hello"
Dim replaceText As Object = "World"
Dim save As Object = True
Dim falseObj As Object = False
‘Starts the Word application.
Dim wordApp As word.Application = New word.Application()
‘Opens the Word document.
Dim doc As word.Document = wordApp.Documents.Open(filePath, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, falseobj, nullobject, nullobject,
nullobject, nullobject)
wordApp.Visible = False
‘Searches and replaces text.
doc.GoTo(item, whichItem, nullobject, nullobject)
For Each rng As word.Range In doc.StoryRanges
rng.Find.Execute(originalText, matchCase, matchAllWord, nullobject,
nullobject, nullobject, forward, nullobject, nullobject, replaceText,
replaceAll, nullobject, nullobject, nullobject, nullobject)
Next
‘Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject)
‘Closes the document.
doc.Close(nullobject, nullobject, nullobject)
‘Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO
The following code example illustrates how to perform a simple find and replace operation by using
DocIO.
C#
//Opens the Word document.
WordDocument document = new WordDocument("Template.docx",FormatType.Docx);
//Defines replacement text.
string replaceText = "World";
//Performs replace.
document.Replace(new Regex("Hello"), replaceText);
//Saves the document.
document.Save("Sample.docx", FormatType.Docx);
//Closes the document.
document.Close();

VB.NET
‘Opens the Word document.
Dim document As WordDocument = New WordDocument("Template.docx")
‘Defines text to be replaced.
Dim replaceText As String = "World"

Copyright © 2001 - 2019 Syncfusion Inc. 88


DocIO Installing NuGet Packages

‘Performs replace.
document.Replace(New Regex("Hello"), replaceText)
‘Saves the document.
document.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
document.Close()

Note: For more information on performing the find and replace operation using DocIO, you can refer to
online documentation link:
Find and Replace
Bookmarks
Bookmarks identify the location of text in a Word document that you can name and identify for future
reference.
Using Microsoft Office Automation
The following code example illustrates how to insert a bookmark for a range of text by using Office
Automation.
C#
using word = Microsoft.Office.Interop.Word;
---------
//Initializes objects.
object nullobject = Missing.Value;
object newFilePath = "Sample.docx";
//Starts a Word application.
Microsoft.Office.Interop.Word.Application wordApp = new
Microsoft.Office.Interop.Word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref
nullobject);
Microsoft.Office.Interop.Word.Document document = wordApp.ActiveDocument;
//Adds a paragraph to the document.
Microsoft.Office.Interop.Word.Paragraph oPara1;
oPara1 = document.Content.Paragraphs.Add(ref nullobject);
oPara1.Range.Text = "Bookmark with one word selected";
//Defines start and end positions of bookmark range.
object start = oPara1.Range.Text.IndexOf("word");
object end = oPara1.Range.Text.LastIndexOf(" ");
object rng = document.Range(ref start, ref end);
//Adds bookmark.
document.Bookmarks.Add("one_word", ref rng);
//Saves document and quits application.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

Copyright © 2001 - 2019 Syncfusion Inc. 89


DocIO Installing NuGet Packages

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
‘Initializes objects.
Dim nullobject As Object = Missing.Value
Dim newFilePath As Object = "Sample.docx"
‘Starts a Word application.
Dim wordApp As word.Application = New word.Application()
‘Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
‘Adds a paragraph to the document.
Dim oPara As word.Paragraph
oPara = doc.Content.Paragraphs.Add(nullobject)
oPara.Range.Text = "Bookmark with one word selected"
‘Defines the start and end positions of bookmark range.
Dim startobj As Object = oPara.Range.Text.IndexOf("word")
Dim endobj As Object = oPara.Range.Text.LastIndexOf(" ")
Dim rng As Object = doc.Range(startobj, endobj)
‘Adds bookmark.
doc.Bookmarks.Add("one_word", rng)
‘Saves document.
doc.SaveAs(newFilePath)
‘Closes document.
doc.Close(nullobject, nullobject, nullobject)
‘Quits application.
wordApp.Quit()

Using DocIO
The following code example illustrates how to insert the bookmark by using DocIO. Here, the
AppendBookmarkStart() and AppendBookmarkEnd() methods are used to add the bookmark.
C#
//Creates a new Word document.
WordDocument doc = new WordDocument();
//Adds new section
IWSection section = doc.AddSection();
//Adds new paragraph
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("Simple Bookmark");
paragraph = section.AddParagraph();
paragraph.AppendText("Bookmark with one ");
//Inserts bookmark.
paragraph.AppendBookmarkStart("one_word");
paragraph.AppendText("word");
paragraph.AppendBookmarkEnd("one_word");
paragraph.AppendText(" selected");
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 90


DocIO Installing NuGet Packages

‘Creates a new Word document.


Dim doc As WordDocument = New WordDocument()
‘Adds new section
Dim section As IWSection = doc.AddSection()
‘Adds new paragraph
Dim paragraph As IWParagraph = section.AddParagraph()
paragraph.AppendText("Simple Bookmark")
paragraph = section.AddParagraph()
paragraph.AppendText("Bookmark with one ")
‘Inserts bookmark.
paragraph.AppendBookmarkStart("one_word")
paragraph.AppendText("word")
paragraph.AppendBookmarkEnd("one_word")
paragraph.AppendText(" selected")
‘Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
doc.Close()

Page Numbers
Page numbers can be added to the Word document in headers or footers.
Using Microsoft Office Automation
The following code example illustrates how page numbers can be inserted to the footer of the Word
document by adding a page number field.
C#
using word = Microsoft.Office.Interop.Word;
---------
//Initializes objects.
object filepath = "Sample.docx";
object nullobject = Missing.Value;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
document.Activate();
//Seeks the page footer.
wordApp.ActiveWindow.ActivePane.View.SeekView =
Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
//Formats the footer.
wordApp.Selection.Paragraphs.Alignment =
word.WdParagraphAlignment.wdAlignParagraphCenter;
wordApp.ActiveWindow.Selection.Font.Name = "Arial";
wordApp.ActiveWindow.Selection.Font.Size = 8;
//Adds page numbers in the footer.
Object CurrentPage = word.WdFieldType.wdFieldPage;
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range, ref
CurrentPage, ref nullobject, ref nullobject);
//Saves the document.

Copyright © 2001 - 2019 Syncfusion Inc. 91


DocIO Installing NuGet Packages

document.Save();
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
‘Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filePath As Object = "Sample.docx"
Dim falseobj As Object = False
‘Starts the application.
Dim wordApp As word.Application = New word.Application()
‘Adds a new Word document.
Dim document As word.Document = wordApp.Documents.Open(filePath, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, falseobj, nullobject, nullobject,
nullobject, nullobject)
wordApp.Visible = False
document.Activate()
‘Seeks the page footer.
wordApp.ActiveWindow.ActivePane.View.SeekView =
word.WdSeekView.wdSeekCurrentPageFooter
‘Formats the footer.
wordApp.Selection.Paragraphs.Alignment =
word.WdParagraphAlignment.wdAlignParagraphCenter
wordApp.ActiveWindow.Selection.Font.Name = "Arial"
wordApp.ActiveWindow.Selection.Font.Size = 8
‘Adds page numbers in the footer.
Dim CurrentPage As Object = word.WdFieldType.wdFieldPage
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range,
CurrentPage, nullobject, nullobject)
‘Saves the document.
document.Save()
‘Closes the document.
document.Close(nullobject, nullobject, nullobject)
‘Quits application.
wordApp.Quit()

Using DocIO
The following code example illustrates how page numbers are inserted to the footer of the Word
document by using DocIO.
C#
//Opens the Word document.
WordDocument doc = new WordDocument("Template.docx", FormatType.Docx);
//Iterates through sections
foreach (WSection sec in doc.Sections)
{
IWParagraph para = sec.AddParagraph();
//Appends page field to the paragraph

Copyright © 2001 - 2019 Syncfusion Inc. 92


DocIO Installing NuGet Packages

para.AppendField("footer", FieldType.FieldPage);
para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
sec.PageSetup.PageNumberStyle = PageNumberStyle.Arabic;
//Adds paragraph to footer
sec.HeadersFooters.Footer.Paragraphs.Add(para);
}
//Saves the document.
doc.Save("Sample.docx",FormatType.Docx);
//Closes the document.
doc.Close();

VB.NET
‘Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx", FormatType.Docx)
‘Iterates through sections
For Each sec As WSection In doc.Sections
Dim para As IWParagraph = sec.AddParagraph()
‘Appends page field to the paragraph
para.AppendField("footer", FieldType.FieldPage)
para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center
sec.PageSetup.PageNumberStyle = PageNumberStyle.Arabic
‘Adds paragraph to footer
sec.HeadersFooters.Footer.Paragraphs.Add(para)
Next
‘Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
doc.Close()

Document Watermarks
Watermarks are text or pictures that appear behind document text.
Using Microsoft Office Automation
The following code example illustrates how to insert a text watermark as a shape by using Office
Automation.
C#
using word = Microsoft.Office.Interop.Word;
---------
//Initializes objects.
object nullobject = Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref
nullobject);
word.Document document = wordApp.ActiveDocument;
//Seeks the current page header.
wordApp.ActiveWindow.ActivePane.View.SeekView =
word.WdSeekView.wdSeekCurrentPageHeader;
//Inserts watermark.

Copyright © 2001 - 2019 Syncfusion Inc. 93


DocIO Installing NuGet Packages

word.Shape watermark =
wordApp.Selection.HeaderFooter.Shapes.AddTextEffect(Microsoft.Office.Core.Ms
oPresetTextEffect.msoTextEffect1,
"Watermark", "Arial", (float)48, Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, ref nullobject);
//Sets watermark properties.
watermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
watermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
watermark.Fill.Solid();
watermark.Fill.ForeColor.RGB = (Int32)word.WdColor.wdColorGray30;
//Sets focus back to the document.
wordApp.ActiveWindow.ActivePane.View.SeekView =
word.WdSeekView.wdSeekMainDocument;
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
Initializes objects.
Dim nullobject As Object = Missing.Value
Dim newFilePath As Object = "Sample.docx"
‘Starts the application.
Dim wordApp As word.Application = New word.Application()
‘Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
‘Seeks the current page header.
wordApp.ActiveWindow.ActivePane.View.SeekView =
word.WdSeekView.wdSeekCurrentPageHeader
‘Adds text watermark to the document.
Dim watermark As word.Shape =
wordApp.Selection.HeaderFooter.Shapes.AddTextEffect(Microsoft.Office.Core.Ms
oPresetTextEffect.msoTextEffect1,"Watermark", "Arial", 48,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, nullobject)
‘Sets watermark properties.
watermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue
watermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse
watermark.Fill.Solid()
watermark.Fill.ForeColor.RGB = CType(word.WdColor.wdColorGray30, Integer)
‘Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject)
‘Closes the document.
doc.Close(nullobject, nullobject, nullobject)

Copyright © 2001 - 2019 Syncfusion Inc. 94


DocIO Installing NuGet Packages

‘Quits application.
wordApp.Quit()

Using DocIO
DocIO enables you to add a text watermark and a picture watermark to a Word document. The
following code example shows how to insert the picture watermark to the Word document.
C#
//Creates a new Word document.
WordDocument doc = new WordDocument();
doc.EnsureMinimal();
//Adds picture watermark to the document.
PictureWatermark picWatermark = new PictureWatermark();
picWatermark.Scaling = 120f;
picWatermark.Washout = true;
doc.Watermark = picWatermark;
picWatermark.Picture = Image.FromFile(ImagesPath + "Water lilies.jpg");
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();

VB.NET
‘Creates a new Word document.
Dim doc As WordDocument = New WordDocument()
doc.EnsureMinimal()
‘Adds picture watermark to the document.
Dim picWatermark As PictureWatermark = New PictureWatermark()
picWatermark.Scaling = 120f
picWatermark.Washout = True
doc.Watermark = picWatermark
picWatermark.Picture = Image.FromFile(ImagesPath and "Water lilies.jpg")
‘Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
doc.Close()

Note: For more information on adding watermarks to a Word document using DocIO, refer to the
online documentation link:
Applying Watermark
Headers and Footers
The headers and footers can be inserted with text, graphics, and any other information that is contained
in the document.
Using Microsoft Office Automation
The following code example illustrates how to add headers and footers to a Word document. In this
example, page numbers are inserted to the header and a text is inserted to the footer.
C#
using word = Microsoft.Office.Interop.Word;

Copyright © 2001 - 2019 Syncfusion Inc. 95


DocIO Installing NuGet Packages

---------
//Initializes objects.
object nullobject = Missing.Value;
object filePath = "Template.docx";
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filePath, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Adds header and footer to each section in the document.
foreach (word.Section section in document.Sections)
{
object fieldEmpty = word.WdFieldType.wdFieldPage;
object autoText = "AUTOTEXT \"Page X of Y\" ";
object preserveFormatting = true;
//Footer.
section.Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text =
"Internal";
section.Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragr
aphFormat.Alignment =
word.WdParagraphAlignment.wdAlignParagraphLeft;
//Header.
section.Headers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields
.Add(section.Headers[
word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,reffieldEmpty, ref
autoText, ref preserveFormatting);
section.Headers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Paragr
aphFormat.Alignment =
word.WdParagraphAlignment.wdAlignParagraphRight;
}
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filePath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
'Starts the application.
Dim wordApp As word.Application = New word.Application()

Copyright © 2001 - 2019 Syncfusion Inc. 96


DocIO Installing NuGet Packages

'Opens the document.


Dim document As word.Document = wordApp.Documents.Open(filePath, nullobject,
nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Adds header and footer to each section in the document.
For Each section As word.Section In document.Sections
Dim fieldEmpty As Object = word.WdFieldType.wdFieldPage
'Footer.
section.Footers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text =
"Internal"
section.Footers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Paragr
aphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft
'Header.
section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Fields
.Add(section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range,
fieldEmpty, nullobject, nullobject)
section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Paragr
aphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphRight
Next
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit()

Using DocIO
You can set the header and footer by using the HeadersFooters property in the Word document section.
To access a particular header/footer, you can use the following properties of WHeadersFooters class:

 FirstPageHeader
 FirstPageFooter
 OddHeader
 OddFooter
 EvenHeader
 EvenFooter

C#
//Opens a Word document.
WordDocument doc = new WordDocument("Template.docx");
//Adds header and footer to each section in the document.
foreach (WSection sec in doc.Sections)
{
//Header.
WParagraph para = new WParagraph(doc);
para.AppendField("page", FieldType.FieldPage);
para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Right;
sec.HeadersFooters.Header.Paragraphs.Add(para);
//Footer.

Copyright © 2001 - 2019 Syncfusion Inc. 97


DocIO Installing NuGet Packages

WParagraph para1 = new WParagraph(doc);


para1.AppendText("Internal");
para1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
sec.HeadersFooters.Footer.Paragraphs.Add(para1);
}
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();

VB.NET
‘Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx")
‘Adds header and footer to each section in the document.
For Each sec As WSection In doc.Sections
‘Header.
Dim para As WParagraph = New WParagraph(doc)
para.AppendField("page", FieldType.FieldPage)
para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Right
sec.HeadersFooters.Header.Paragraphs.Add(para)
‘Footer.
Dim para1 As WParagraph = New WParagraph(doc)
para1.AppendText("Internal")
para1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left
sec.HeadersFooters.Footer.Paragraphs.Add(para1)
Next
‘Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
‘Closes the document.
doc.Close()

Character Formatting
Character formatting defines the appearance of the text in a Word document. This section illustrates
how to apply character level formatting to the Word document.
Using Microsoft Office Automation
The following code example illustrates how to apply the character formatting to the Word document by
using the Range properties.
C#
using word = Microsoft.Office.Interop.Word
----------------
//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
object falseObj = false;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref
nullobject);
word.Document doc = wordApp.ActiveDocument;
//Defines the range for formatting.

Copyright © 2001 - 2019 Syncfusion Inc. 98


DocIO Installing NuGet Packages

object start = 0;
object end = 0;
word.Range rng = doc.Range(ref start, ref end);
rng.Text = "New Text";
rng.Font.Name = "Arial";
rng.Font.Size = 14;
//Saves the document.
doc.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
doc.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
----------------
‘Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
Dim falseObj As Object = False
‘Starts the Word application.
Dim wordApp As word.Application = New word.Application()
‘Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
‘Defines the range for formatting.
Dim start As Object = 0
Dim endobj As Object = 0
Dim rng As word.Range = doc.Range(start, endobj)
rng.Text = "New Text"
rng.Font.Name = "Arial"
rng.Font.Size = 14
‘Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject)
‘Closes the document.
doc.Close(nullobject, nullobject, nullobject)
‘Quits the application.
wordApp.Quit()

Tables
Tables are used to organize information and to display the information in rows and columns. You can
also add images or even other tables to the table.
Using Microsoft Office Automation
The following code example illustrates how to insert a table to a Word document, where the table
contains three rows and two columns.

Copyright © 2001 - 2019 Syncfusion Inc. 99


DocIO Installing NuGet Packages

C#
using word = Microsoft.Office.Interop.Word;
---------
//Initializes the objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref
nullobject);
word.Document document = wordApp.ActiveDocument;
//Inserts the table.
object start = 0;
object end = 0;
word.Range tableLocation = document.Range(ref start, ref end);
document.Tables.Add(tableLocation, 3, 2, ref nullobject, ref nullobject);
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
---------
'Initializes the objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
'Starts the Word application.
Dim wordApp As New word.Application()
'Creates a new document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim document As word.Document = wordApp.ActiveDocument
'Inserts the table.
Dim start As Object = 0
Dim [end] As Object = 0
Dim tableLocation As word.Range = document.Range(start, [end])
document.Tables.Add(tableLocation, 3, 2, nullobject, nullobject)
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Copyright © 2001 - 2019 Syncfusion Inc. 100


DocIO Installing NuGet Packages

Using DocIO
The following code example shows how to insert an empty table to a Word document. The ResetCells()
method is used to specify the number of rows and columns in a table.
C#
//Creates a new Word document.
WordDocument document = new WordDocument();
IWSection section = document.AddSection();
//Adds a table to the document.
IWTable table = section.AddTable();
table.ResetCells(3, 2);
//Saves the document.
document.Save("Sample.docx",FormatType.Docx);
//Closes the document.
document.Close();

VB.NET
'Creates a new Word document.
Dim document As New WordDocument()
Dim section As IWSection = document.AddSection()
'Adds a table to the document.
Dim table As IWTable = section.AddTable()
table.ResetCells(3, 2)
'Saves the document.
document.Save("Sample.docx",FormatType.Docx);
'Closes the document.
document.Close()

Note: For more information on creating tables using DocIO, refer to online documentation link:
Working with Tables
Comments
Comments are used to include additional information to a paragraph or text in a Word document.
Comments can be added or modified whenever needed and deleted when the comment has served its
purpose.
Adding Comments using Microsoft Office Automation
The following code example illustrates how to add comments to a Word document. You need to define
the range of text where the comment is to be added.
C#
using word = Microsoft.Office.Interop.Word;
---------
//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref
nullobject);

Copyright © 2001 - 2019 Syncfusion Inc. 101


DocIO Installing NuGet Packages

word.Document doc = wordApp.ActiveDocument;


//Inserts text to the Word document.
object start = 0;
object end = 0;
word.Range rng = doc.Range(ref start, ref end);
rng.Text = "New Text";
//Adds comment to the inserted text.
object text = "Comment goes here";
doc.Comments.Add(rng, ref text);
//Saves the document.
doc.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
doc.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
Imports word = Microsoft.Office.Interop.Word
---------
‘Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
‘Starts the Word application.
Dim wordApp As word.Application = New word.Application()
‘Creates a new document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
‘Inserts text to the Word document.
Dim startobj As Object = 0
Dim endobj As Object = 0
Dim rng As word.Range = doc.Range(startobj, endobj)
rng.Text = "New Text"
‘Adds comment to the inserted text.
Dim text As Object = "Comment goes here"
doc.Comments.Add(rng, text)
‘Saves the document and quits application.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject,
nullobject, nullobject, nullobject, nullobject, nullobject)
‘Closes the document.
doc.Close(nullobject, nullobject, nullobject)
‘Quits the application.
wordApp.Quit()

Adding Comments Using DocIO


You can insert comments to a paragraph or text in a Word document by using DocIO. The following code
example shows how to insert comments to a Word document.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 102


DocIO Installing NuGet Packages

//Creates a new Word document.


WordDocument doc = new WordDocument();
IWSection section = doc.AddSection();
//Adds a paragraph to the document.
IWParagraph para = section.AddParagraph();
para.AppendText("New Text");
//Adds comment to the paragraph.
para.AppendComment("Comment goes here");
//Saves the document.
doc.Save("Sample.doc", FormatType.Doc);

VB.NET
‘Creates a new Word document.
Dim doc As WordDocument = New WordDocument()
Dim section As IWSection = doc.AddSection()
‘Adds a paragraph to the document.
Dim para As IWParagraph = section.AddParagraph()
para.AppendText("New Text")
para.AppendComment("Comment goes here")
‘Saves the document.
doc.Save("Sample.doc", FormatType.Doc)

Note: For more information on working with the comments using DocIO, you can refer to the online
documentation link:
Working with Comments
Document Protection
You can protect your Word documents with or without a password from anyone accidentally or
deliberately modifying the Word documents. You can specify the protection type for preserving the
Word documents.
Using Microsoft Office Automation
WdProtectionType is used to specify the protection type of the Word document.
C#
//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object noReset = false;
object password = System.String.Empty;
object useIRM = false;
object enforceStyleLock = false;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document to be protected.
word.Document document = wordApp.Documents.Open(ref filepath, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;

Copyright © 2001 - 2019 Syncfusion Inc. 103


DocIO Installing NuGet Packages

//Sets "Allow only Comments" protection to Word document.


document.Protect(word.WdProtectionType.wdAllowOnlyComments, ref noReset, ref
password, ref useIRM, ref enforceStyleLock);
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filepath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim noReset As Object = False
Dim password As Object = System.[String].Empty
Dim useIRM As Object = False
Dim enforceStyleLock As Object = False
'Starts the Word application.
Dim wordApp As New Word.Application()
'Opens the Word document that is to be protected.
Dim document As Word.Document = wordApp.Documents.Open(filepath, nullobject,
nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Sets "Allow only Comments" protection to Word document.
document.Protect(Word.WdProtectionType.wdAllowOnlyComments, noReset,
password, useIRM, enforceStyleLock)
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO
DocIO uses ProtectionType property to specify the protection type of the Word document. This property
uses the following values:

 AllowOnlyComments: Allows only comments to be added to the document.


 AllowOnlyFormFields: Allows content to be added to the document through form fields only.
 AllowOnlyRevisions: Allows only revisions to be made to the existing content.
 AllowOnlyReading: All kinds of editing are restricted here and it makes the Word document as
read-only document.

Copyright © 2001 - 2019 Syncfusion Inc. 104


DocIO Installing NuGet Packages

 NoProtection: Does not protect the document.

C#
//Loads the existing Word document by using DocIO instance
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Sets "Allow only Comments" protection to Word document.
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyComments;
//Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the existing Word document by using DocIO instance
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Sets "Allow only Comments" protection to Word document.
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyComments
'Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx)
document.Close()

Refer to the online documentation link for more details about the ways to protect the Word documents
by using DocIO:
Protecting word document from editing
Table of Contents
Table of contents can be generated by applying the heading styles to text in a Word document. To
create the table of contents in Microsoft Word, click Table of Contents from the Table of Contents group
on the References tab.
Using Microsoft Office Automation
The following code example shows how to insert and update table of contents in a Word document.
C#
//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object trueobj = true;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref
nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject);
wordApp.Visible = false;
//Defines the range for TOC in the document.
object tocstart = 0;
object tocend = 0;
word.Range rngToc = document.Range(ref tocstart, ref tocend);

Copyright © 2001 - 2019 Syncfusion Inc. 105


DocIO Installing NuGet Packages

//Adds TOC.
word.TableOfContents tableOfContents = document.TablesOfContents.Add(rngToc,
ref trueobj, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref trueobj, ref trueobj, ref trueobj, ref trueobj, ref
trueobj, ref trueobj);
//Updates TOC.
tableOfContents.Update();
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref
nullobject, ref nullobject, ref nullobject,
ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);

VB.NET
'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filepath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim trueobj As Object = True
'Starts the Word application.
Dim wordApp As New Word.Application()
'Opens the Word document.
Dim document As Word.Document = wordApp.Documents.Open(filepath, nullobject,
nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Defines the range for TOC in the document.
Dim tocstart As Object = 0
Dim tocend As Object = 0
Dim rngToc As Word.Range = document.Range(tocstart, tocend)
'Adds TOC.
Dim tableOfContents As Word.TableOfContents =
document.TablesOfContents.Add(rngToc, trueobj, nullobject, nullobject,
nullobject, nullobject, _
trueobj, trueobj, trueobj, trueobj, trueobj, trueobj)
'Updates TOC.
tableOfContents.Update()
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject,
nullobject, _
nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, _
nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Copyright © 2001 - 2019 Syncfusion Inc. 106


PDF Installing NuGet Packages

Using DocIO
The following code example illustrates how to insert and update the table of contents in a Word
document by using DocIO.
C#
//Loads the existing Word document by using DocIO instance
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
IWSection section = document.Sections[0];
//Appends TOC to the first paragraph of the document.
WParagraph paragraph = new WParagraph(document);
TableOfContent tableOfContents = paragraph.AppendTOC(1, 3);
section.Paragraphs.Insert(0, paragraph);
//Updates table of contents.
document.UpdateTableOfContents();
//Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx);
document.Close();

VB.NET
'Loads the existing Word document by using DocIO instance
Dim document As New WordDocument("Template.docx", FormatType.Docx)
Dim section As IWSection = document.Sections(0)
'Appends TOC to the first paragraph of the document.
Dim paragraph As New WParagraph(document)
Dim tableOfContents As TableOfContent = paragraph.AppendTOC(1, 3)
section.Paragraphs.Insert(0, paragraph)
'Updates table of contents.
document.UpdateTableOfContents()
'Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx)
document.Close()

Refer to the online documentation link for more information about adding the table of contents to the
Word document by using DocIO:
Working with table of contents
How to copy necessary fonts to Linux containers
The fonts present in the location(in Docker container) "/usr/local/share/fonts/" is used for conversion.
By default, there will be limited number of fonts available in the container.
You should copy necessary fonts to this location "/usr/local/share/fonts/" before conversion.
Use the following code example to copy fonts to containers.
DOCKERFILE

PDF
C#
using Syncfusion.Pdf;

Copyright © 2001 - 2019 Syncfusion Inc. 107


PDF Installing NuGet Packages

using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;

VB.NET
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid

UWP

C#
//Open an existing document from file system
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Input.pdf");

VB.NET
'Open an existing document from file system
Dim loadedDocument As New PdfLoadedDocument("Input.pdf")

UWP

C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
// Set the page size.
document.PageSettings.Size = PdfPageSize.A4;
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0,
0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Set the page size.
document.PageSettings.Size = PdfPageSize.A4

Copyright © 2001 - 2019 Syncfusion Inc. 108


PDF Installing NuGet Packages

'Add a page to the document.


Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
'Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0,
0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)

UWP

C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Create a solid brush.
PdfBrush brush = new PdfSolidBrush(Color.Black);
//Set the font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14);
//Draw the text.
graphics.DrawString("Hello world!", font, brush, new PointF(20, 20));
//Save the document.
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Create a solid brush.
Dim brush As PdfBrush = New PdfSolidBrush(Color.Black)
'Set the font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 14)
'Draw the text.
graphics.DrawString("Hello world!", font, brush, New PointF(20, 20))
'Save the document.
document.Save("Output.pdf")
document.Close(True)

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 109


PDF Installing NuGet Packages

C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0,
0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the standard font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
'Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0,
0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)

UWP

C#
//Create a new PDF document
PdfDocument doc = new PdfDocument();
//Add a page to the document
PdfPage page = doc.Pages.Add();
//Create PDF graphics for the page
PdfGraphics graphics = page.Graphics;
//Load the image from the disk
PdfBitmap image = new PdfBitmap("Autumn Leaves.jpg");
//Draw the image
graphics.DrawImage(image, 0, 0);
//Save the document
doc.Save("Output.pdf");
//Close the document

Copyright © 2001 - 2019 Syncfusion Inc. 110


PDF Installing NuGet Packages

doc.Close(true);

VB.NET
'Create a new PDF document
Dim doc As New PdfDocument()
'Add a page to the document
Dim page As PdfPage = doc.Pages.Add()
'Create PDF graphics for the page
Dim graphics As PdfGraphics = page.Graphics
'Load the image from the disk
Dim image As New PdfBitmap("Autumn Leaves.jpg")
'Draw the image
graphics.DrawImage(image, 0, 0)
'Save the document
doc.Save("Output.pdf")
'Close the document
doc.Close(True)

UWP

C#
//Create a new PDF document
PdfDocument doc = new PdfDocument();
//Add a page to the document
PdfPage page = doc.Pages.Add();
//Create PDF graphics for the page
PdfGraphics graphics = page.Graphics;
//Create new PDF solid brush
PdfSolidBrush brush = new PdfSolidBrush(Color.Red);
//Draw ellipse on the page
graphics.DrawEllipse(brush, new RectangleF(0, 0, 200, 100));
//Save the PDF document
doc.Save("SolidBrush.pdf");
//Close the instance of PdfDocument
doc.Close(true);

VB.NET
'Create a new PDF document
Dim doc As PdfDocument = New PdfDocument
'Add a page to the document
Dim page As PdfPage = doc.Pages.Add
'Create PDF graphics for the page
Dim graphics As PdfGraphics = page.Graphics
'Create new PDF solid brush
Dim brush As PdfSolidBrush = New PdfSolidBrush(Color.Red)
'Draw ellipse on the page
graphics.DrawEllipse(brush, New RectangleF(0, 0, 200, 100))
'Save the PDF document
doc.Save("SolidBrush.pdf")
'Close the instance of PdfDocument
doc.Close(True)

Copyright © 2001 - 2019 Syncfusion Inc. 111


PDF Installing NuGet Packages

UWP

C#
//Create a new PDF document.
PdfDocument doc = new PdfDocument();
//Add a page.
PdfPage page = doc.Pages.Add();
// Create a PdfLightTable.
PdfLightTable pdfLightTable = new PdfLightTable();
// Initialize DataTable to assign as DateSource to the light table.
DataTable table = new DataTable();
//Include columns to the DataTable.
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Columns.Add("Sex");
//Include rows to the DataTable.
table.Rows.Add(new string[] { "abc", "21", "Male" });
//Assign data source.
pdfLightTable.DataSource = table;
//Draw PdfLightTable.
pdfLightTable.Draw(page, new PointF(0, 0));
//Save the document.
doc.Save("Output.pdf");
//Close the document
doc.Close(true);

VB.NET
'Create a new PDF document.
Dim doc As New PdfDocument()
'Add a page.
Dim page As PdfPage = doc.Pages.Add()
' Create a PdfLightTable.
Dim pdfLightTable As New PdfLightTable()
' Initialize DataTable to assign as DateSource to the light table.
Dim table As New DataTable()
'Include columns to the DataTable.
table.Columns.Add("Name")
table.Columns.Add("Age")
table.Columns.Add("Sex")
'Include rows to the DataTable.
table.Rows.Add(New String() {"abc", "21", "Male"})
'Assign data source.
pdfLightTable.DataSource = table
'Draw PdfLightTable.
pdfLightTable.Draw(page, New PointF(0, 0))
'Save the document.
doc.Save("Output.pdf")
'Close the document
doc.Close(True)

Copyright © 2001 - 2019 Syncfusion Inc. 112


PDF Installing NuGet Packages

UWP

C#
using Syncfusion.Pdf;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocToPDFConverter;

VB.NET
Imports Syncfusion.Pdf
Imports Syncfusion.DocIO.DLS
Imports Syncfusion.DocToPDFConverter

ASP.NET CORE

C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a new page to the PDF document.
PdfPage page = document.Pages.Add();
//Create a textbox field and add the properties.
PdfTextBoxField textBoxField = new PdfTextBoxField(page, "FirstName");
textBoxField.Bounds = new RectangleF(0, 0, 100, 20);
textBoxField.ToolTip = "First Name";
//Add the form field to the document.
document.Form.Fields.Add(textBoxField);
//Save the document.
document.Save("Form.pdf");
//close the document
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As PdfDocument = New PdfDocument()
'Add a new page to the PDF document.
Dim page As PdfPage = document.Pages.Add()
'Create a textbox field and add the properties.
Dim textBoxField As PdfTextBoxField = New PdfTextBoxField(page, "FirstName")
textBoxField.Bounds = New RectangleF(0, 0, 100, 20)
textBoxField.ToolTip = "First Name"
'Add the form field to the document.
document.Form.Fields.Add(textBoxField)
'Save the document.
document.Save("Form.pdf")
'close the document
document.Close(True)

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 113


PDF Installing NuGet Packages

C#
//Create a new PDF XFA document
PdfXfaDocument document = new PdfXfaDocument();
//Add a new XFA page
PdfXfaPage xfaPage = document.Pages.Add();
//Create a new PDF XFA form
PdfXfaForm mainForm = new
PdfXfaForm("subform1",xfaPage,xfaPage.GetClientSize ().Width);
//Create a text element and add the properties
PdfXfaTextElement textElement = new PdfXfaTextElement("Hello World!");
//Add the field to the XFA form
mainForm.Fields.Add(textElement);
//Add the XFA form to the document
document.XfaForm = mainForm;
//Save the document
document.Save("XfaForm.pdf", PdfXfaType.Dynamic);
//Close the document
document.Close();

VB.NET
'Create a new PDF XFA document
Dim document As New PdfXfaDocument()
'Add a new XFA page
Dim xfaPage As PdfXfaPage = document.Pages.Add()
'Create a new PDF XFA form
Dim mainForm As New
PdfXfaForm("subform1",xfaPage,xfaPage.GetClientSize().Width)
'Create a text element and add the properties
Dim textElement As New PdfXfaTextElement("Hello World!")
'Add the field to the XFA form
mainForm.Fields.Add(textElement)
'Add the XFA form to the document
document.XfaForm = mainForm
'Save the document
document.Save("XfaForm.pdf", PdfXfaType.Dynamic)
'Close the document
document.Close()

UWP

C#
//Creates a new PDF document
PdfDocument finalDoc = new PdfDocument();
// Creates a string array of source files to be merged.
string[] source = { "file1.pdf", "file2.pdf" };
// Merges PDFDocument.
PdfDocument.Merge(finalDoc, source);
//Saves the final document
finalDoc.Save("Sample.pdf");
//Closes the document

Copyright © 2001 - 2019 Syncfusion Inc. 114


PDF Installing NuGet Packages

finalDoc.Close(true);

VB.NET
'Creates a new PDF document
Dim finalDoc As New PdfDocument()
' Creates a string array of source files to be merged.
Dim source As String() = {"file1.pdf", "file2.pdf"}
' Merges PDFDocument.
PdfDocument.Merge(finalDoc, source)
'Saves the final document
finalDoc.Save("Sample.pdf")
'Closes the document
finalDoc.Close(True)

UWP

C#
//Load an existing PDF.
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(fileName);
//Load the first page.
PdfPageBase page = loadedDocument.Pages[0];
//Extract text from first page.
string extractedText = page.ExtractText();
//Close the document
loadedDocument.Close(true);

VB.NET
'Load an existing PDF.
Dim loadedDocument As New PdfLoadedDocument(fileName)
'Load the first page.
Dim page As PdfPageBase = loadedDocument.Pages(0)
'Extract the text from first page.
Dim extractedText As String = page.ExtractText()
'close the document.
loadedDocument.Close(True)

UWP

C#
//Load an existing PDF
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(fileName);
//Load the first page
PdfPageBase pageBase = loadedDocument.Pages[0];
//Extract images from first page
Image[] extractedImages = pageBase.ExtractImages();
//Close the document
loadedDocument.Close(true);

Copyright © 2001 - 2019 Syncfusion Inc. 115


PDF Installing NuGet Packages

VB.NET
'Load an existing PDF
Dim loadedDocument As New PdfLoadedDocument(fileName)
'Load the first page
Dim pageBase As PdfPageBase = loadedDocument.Pages(0)
'Extract images from first page
Dim extractedImages As Image() = pageBase.ExtractImages()
'Close the document
loadedDocument.Close(True)

UWP

C#
using Syncfusion.Pdf;
using Syncfusion.HtmlConverter;

VB.NET
Imports Syncfusion.Pdf
Imports Syncfusion.HtmlConverter

ASP.NET CORE

C#
//Load an existing Word document
WordDocument wordDocument = new WordDocument("Template.docx",
FormatType.Docx);
//Initialize chart to image converter for converting charts during Word to
pdf conversion
wordDocument.ChartToImageConverter = new ChartToImageConverter();
//Create an instance of DocToPDFConverter
DocToPDFConverter converter = new DocToPDFConverter();
//Convert Word document into PDF document
PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument);
//Save the PDF file
pdfDocument.Save("WordtoPDF.pdf");
//Close the instance of document objects
pdfDocument.Close(true);
wordDocument.Close();

VB.NET
'Load an existing Word document
Dim wordDocument As New WordDocument("Template.docx", FormatType.Docx)
'Initialize chart to image converter for converting charts during Word to
pdf conversion
wordDocument.ChartToImageConverter = New ChartToImageConverter()

Copyright © 2001 - 2019 Syncfusion Inc. 116


PDF Installing NuGet Packages

'Create an instance of DocToPDFConverter


Dim converter As New DocToPDFConverter()
'Convert Word document into PDF document
Dim pdfDocument As PdfDocument = converter.ConvertToPDF(wordDocument)
'Save the PDF file
pdfDocument.Save("WordtoPDF.pdf")
'Close the instance of document objects
pdfDocument.Close(True)
wordDocument.Close()

ASP.NET CORE

C#
OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\")

VB.NET
Dim processor As New OCRProcessor("TesseractBinaries\")

 Place the Tesseract language data {E.g eng.traineddata} in the local system and provide a path
to the OCR processor

C#
OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\");
processor.PerformOCR(lDoc, @"TessData\");

VB.NET
Dim processor As New OCRProcessor("TesseractBinaries\")
processor.PerformOCR(lDoc, "TessData\")

You can also download the language packages from below link
https://github.com/tesseract-ocr/tessdata
Note: From 16.1.0.24 OCR is not a part of Essential Studio and is available as separate package (OCR
Processor) under the Add-On section in the below link https://www.syncfusion.com/downloads/latest-
version.
Note: PDF supports OCR only in Windows Forms, WPF, ASP.NET and ASP.NET MVC platforms.
Performing OCR for an entire document
You can perform OCR on PDF document with the help of OCRProcessor Class. Refer the below code
snippet for the same.
C#
//Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))

Copyright © 2001 - 2019 Syncfusion Inc. 117


PDF Installing NuGet Packages

{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, @"TessData\");
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

VB.NET
'Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, "TessData\")
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(True)
End Using

Note: The PerformOCR method returns only the text OCRed by OCRProcessor. Other existing text in the
PDF page won’t be returned in this method. Please check text extraction feature for this.
Performing OCR with tesseract version 3.05
You can perform OCR using the tesseract version 3.05. The TesseractVersion property is used to switch
the tesseract version between 3.02 and 3.05. By default, OCR works with tesseract version 3.02.
You must use the pre built Syncfusion tesseract version 3.05 in the sample to run the OCR properly. The
tesseract binaries are shipping with Syncfusion NuGet package, use the following link to download the
NuGet package.
https://www.nuget.org/packages/Syncfusion.OCRProcessor.Base
The following sample code snippet demonstrates the OCR processor with Tesseract3.05 for PDF
documents.
C#
using (OCRProcessor processor = new OCRProcessor(@"Tesseract3.05Binaries \")
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Set tesseract OCR Engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_05;
//Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property

Copyright © 2001 - 2019 Syncfusion Inc. 118


PDF Installing NuGet Packages

processor.PerformOCR(lDoc, @"TessData\", true);


//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

VB.NET
Using processor As New OCRProcessor("Tesseract3.05Binaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Set tesseract OCR engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_05
'Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property
processor.PerformOCR(lDoc, "TessData\", True)
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(True)
End Using

Performing OCR for a region of the document


You can perform OCR on particular region or several regions of a PDF page with the help of PageRegion
class. Refer the below code snippet for the same.
C#
//Initialize the OCR processor by providing the path of the tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
RectangleF rect = new RectangleF(0, 100, 950, 150);
//Assign rectangles to the page
List<PageRegion> pageRegions = new List<PageRegion>();
PageRegion region = new PageRegion();
region.PageIndex = 1;
region.PageRegions = new RectangleF[] { rect };
pageRegions.Add(region);
processor.Settings.Regions = pageRegions;
//Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, @"TessData\");
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 119


PDF Installing NuGet Packages

'Initialize the OCR processor by providing the path of the tesseract


binaries(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
Dim rect As New RectangleF(0, 100, 950, 150)
'Assign rectangles to the page
Dim pageRegions As New List(Of PageRegion)()
Dim region As New PageRegion()
region.PageIndex = 1
region.PageRegions = New RectangleF() {rect}
pageRegions.Add(region)
processor.Settings.Regions = pageRegions
'Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, "TessData\")
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(True)

Performing OCR on image


You can perform OCR on an image also. Refer the below code snippets for the same.
C#
//Initialize the OCR processor by providing the path of the tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//loading the input image
Bitmap image = new Bitmap("input.jpeg");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Process OCR by providing the bitmap image, data dictionary and language
string ocrText= processor.PerformOCR(image, @"TessData\");
}

VB.NET
'Initialize the OCR processor by providing the path of the tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'loading the input image
Dim image As New Bitmap("input.jpeg")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Process OCR by providing the bitmap image, data dictionary and language
Dim ocrText As String = processor.PerformOCR(image, "TessData\")
End Using

Performing OCR for large PDF documents


You can optimize the memory to perform OCR for large PDF documents by enabling the
isMemoryOptimized property in PerformOCR method of OCRProcessor class. Optimization will be

Copyright © 2001 - 2019 Syncfusion Inc. 120


PDF Installing NuGet Packages

effective only with Multithreading environment or PDF document with more images. This is
demonstrated in the following code sample.
C#
//Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//Load a PDF document.
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process.
processor.Settings.Language = Languages.English;
//Process OCR by providing the PDF document, Tesseract data and enable
isMemoryOptimized property
processor.PerformOCR(lDoc, @"TessData\",true);
//Save the OCR processed PDF document in the disk.
lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

VB.NET
'Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document.
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process.
processor.Settings.Language = Languages.English
'Process OCR by providing the PDF document and Tesseract data enable
isMemoryOptimized property.
processor.PerformOCR(lDoc, "TessData\", True)
'Save the OCR processed PDF document in the disk.
lDoc.Save("Sample.pdf")
lDoc.Close(True)
End Using

Performing OCR on rotated page of PDF document


You can perform OCR on the rotated page of a PDF document. Refer to the following code snippet for
the same.
C#
//Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Set OCR page auto detection rotation
processor.Settings.AutoDetectRotation = true;
//Process OCR by providing the PDF document
processor.PerformOCR(lDoc, @"TessData\");

Copyright © 2001 - 2019 Syncfusion Inc. 121


PDF Installing NuGet Packages

//Save the OCR processed PDF document in the disk


lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

VB.NET
'Initialize the OCR processor by providing the path of tesseract
binaries(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document.
Dim lDoc As PdfLoadedDocument = New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Set OCR page auto detection rotation
processor.Settings.AutoDetectRotation = true
'Process OCR by providing the PDF document
processor.PerformOCR(lDoc, "TessData\")
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(true)
End Using

Layout result from OCR


You can get the OCRed text and its bounds from a scanned PDF document by using the OCRLayoutResult
Class. Refer to the following code snippet.
C#
//Initialize the OCR processor by providing the path of tesseract binaries
(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Initializes OCR layout result
OCRLayoutResult result;
//Process OCR by providing the PDF document, Tesseract data, and layout
result
processor.PerformOCR(lDoc, @"TessData\", out result);
//Get OCRed line collection from first page
OCRLineCollection lines = result.Pages[0].Lines;
//Get each OCRed line and its bounds
foreach(Line line in lines)
{
string text = line.Text;
RectangleF bounds = line.Rectangle;
}
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
//Close the document
lDoc.Close(true);
}

Copyright © 2001 - 2019 Syncfusion Inc. 122


PDF Installing NuGet Packages

VB.NET
'Initialize the OCR processor by providing the path of tesseract binaries
(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Initializes OCR layout result
Dim result As OCRLayoutResult
'Process OCR by providing the PDF document, Tesseract data, and layout
result
processor.PerformOCR(lDoc, "TessData\", result)
'Get OCRed line collection from first page
Dim lines As OCRLineCollection = result.Pages(0).Lines
'Get each OCRed line and its bounds
For Each line As Line In lines
Dim text As String = line.Text
Dim bounds As RectangleF = line.Rectangle
Next
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
'Close the document
lDoc.Close(True)
End Using

Native call
Enable native call will not launch any temporary process for OCR processing, instead it will invoke the
native calls.
Tesseract 3.02
Tesseract 3.02 supports only 32-bit version. By default, this property will be disabled.
Note: Enable native call will not work in 64-bit in Tesseract 3.02 version. Instead a temporary process
will be launched for OCR processing.
The following sample code snippet demonstrates the OCR processor with native call support of tesseract
3.02.
C#
using (OCRProcessor processor = new OCRProcessor(@"Tesseract3.02Binaries\")
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Set tesseract OCR Engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_02;
//Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property
processor.PerformOCR(lDoc, @"TessData\", true);
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");

Copyright © 2001 - 2019 Syncfusion Inc. 123


PDF Installing NuGet Packages

lDoc.Close(true);
}

VB.NET
Using processor As New OCRProcessor("Tesseract3.02Binaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Set tesseract OCR engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_02
'Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property
processor.PerformOCR(lDoc, "TessData\", True)
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(True)
End Using

Tesseract 3.05
Tesseract 3.05 supports the native call for both x86 and x64 architectures.By default, the x86 tesseract
binaries are available with NuGet package or the tesseract installer.
You can download the x64 supporting tesseract binaries from the following link.
Tesseract 64-bit binaries
Note: This 64-bit binaries are required only when the native call property is enabled.
Make sure to provide the 64-bit binaries path while using in the 64-bit environment.
The following sample code snippet demonstrates the OCR processor with native call support of tesseract
3.05.
C#
using (OCRProcessor processor = new OCRProcessor(@" Tesseract3.05Binaries
\")
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Set tesseract OCR engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_05;
//Set enable native call
processor.Settings.EnableNativeCall = true;
//Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property
processor.PerformOCR(lDoc, @"TessData\", true);
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
lDoc.Close(true);
}

Copyright © 2001 - 2019 Syncfusion Inc. 124


PDF Installing NuGet Packages

VB.NET
Using processor As New OCRProcessor("Tesseract3.05Binaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Set tesseract OCR engine
processor.Settings.TesseractVersion = TesseractVersion.Version3_05
'Set enable native call
processor.Settings.EnableNativeCall = True
'Process OCR by providing the PDF document and tesseract data, and enabling
the isMemoryOptimized property
processor.PerformOCR(lDoc,"TessData\", True)
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
lDoc.Close(True)
End Using

Customizing temp folder


While performing OCR on an existing scanned PDF document, the OCR Processor will create temporary
files (.temp, .tiff, .txt) and the files are deleted after the process is completed. You can change this
temporary files folder location using the TempFolder property available in the OCRSettings Instance.
Refer to the following code snippet.
C#
//Initialize the OCR processor by providing the path of tesseract binaries
(SyncfusionTesseract.dll and liblept168.dll)
using (OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\"))
{
//Load a PDF document
PdfLoadedDocument lDoc = new PdfLoadedDocument("Input.pdf");
//Set OCR language to process
processor.Settings.Language = Languages.English;
//Set custom temp file path location
processor.Settings.TempFolder = "D:/Temp/";
//Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, @"TessData\");
//Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf");
//Close the document
lDoc.Close(true);
}

VB.NET
'Initialize the OCR processor by providing the path of tesseract binaries
(SyncfusionTesseract.dll and liblept168.dll)
Using processor As New OCRProcessor("TesseractBinaries\")
'Load a PDF document
Dim lDoc As New PdfLoadedDocument("Input.pdf")
'Set OCR language to process
processor.Settings.Language = Languages.English
'Set custom temp file path location

Copyright © 2001 - 2019 Syncfusion Inc. 125


PDF Installing NuGet Packages

processor.Settings.TempFolder = "D:/Temp/"
'Process OCR by providing the PDF document and Tesseract data
processor.PerformOCR(lDoc, "TessData\")
'Save the OCR processed PDF document in the disk
lDoc.Save("Sample.pdf")
'Close the document
lDoc.Close(True)
End Using

Best Practices
You can improve the accuracy of the OCR process by choosing the correct compression method when
converting the scanned paper to a TIFF image and then to a PDF document.

 Use (zip) lossless compression for color or gray-scale images.


 Use CCITT Group 4 or JBIG2 (lossless) compression for monochrome images. This ensures that
optical character recognition works on the highest-quality image, thereby improving the OCR
accuracy. This is especially useful in low-resolution scans.
 In addition, rotated images and skewed images can also affect the accuracy and readability of
the OCR process.

Tesseract works best with text when at least 300 dots per inch (DPI) are used, so it is beneficial to
resize images.
For more details regarding quality improvement, refer to the following link:
https://github.com/tesseract-ocr/tesseract/wiki/ImproveQuality
You can set the different performance level to the OCRProcessor using Performance enumeration.

 Rapid – high speed OCR performance and provide normal OCR accuracy
 Fast – provides moderate OCR processing speed and accuracy
 Slow – Slow OCR performance and provide best OCR accuracy.

Refer below code snippet to set the performance of the OCR.


C#
OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\")
//set the OCR performance
processor.Settings.Performance = Performance.Fast;

VB.NET
Dim processor As New OCRProcessor("TesseractBinaries\")
'Set the OCR performance
processor.Settings.Performance = Performance.Fast

Troubleshooting
Issue: You can get the exception “Tesseract has not been initialized” while performing OCR process.
Solution 1: To resolve this, make sure the path of the Tesseract binaries and Tesseract data are properly
provided as shown below.

Copyright © 2001 - 2019 Syncfusion Inc. 126


PDF Working with Hyperlinks

C#
//'TesseractBinaries – path of the folder containing SyncfusionTesseract.dll
and liblept168.dll
OCRProcessor processor = new OCRProcessor(@"TesseractBinaries\");
//TessData – path of the folder containing the language pack
processor.PerformOCR(lDoc, @"TessData\");

VB.NET
'TesseractBinaries – path of the folder containing SyncfusionTesseract.dll
and liblept168.dll
Dim processor As New OCRProcessor("TesseractBinaries\")
'TessData – path of the folder containing the language pack
processor.PerformOCR(lDoc, "TessData\")

Solution 2: Make sure that your data file version is 3.02, since the OCR processor is built with Tesseract
version 3.02.
Issue: OCR processor doesn’t process languages other than English.
Solution: Essential PDF supports all the languages supported by Tesseract engine.
The dictionary packs for the languages can be downloaded from the following online location:
https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-302
It is also mandatory to change the corresponding language code in the OCRProcessor.Settings.Language
property. For example, to perform optical character recognition in German, the property should be set
as processor.Settings.Language = "deu";
The following link contains the complete set of languages supported by Tesseract and their language
codes.
https://github.com/tesseract-ocr/tesseract/blob/master/doc/tesseract.1.asc#languages
Working with Hyperlinks
In PDF, hyperlinks can be added to allow the users to navigate to another part of PDF file, web page or
any other external content. Essential PDF provides support for all these types of hyperlink.
Working with Web navigation
You can navigate to specified URL from a PDF document by using the PdfTextWebLink class.
Please refer the below code snippet for navigating to the web page.
C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create the font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12f);
//Create the Text Web Link.
PdfTextWebLink textLink = new PdfTextWebLink();
//Set the hyperlink
textLink.Url = "http://www.syncfusion.com";

Copyright © 2001 - 2019 Syncfusion Inc. 127


PDF Working with Hyperlinks

//Set the link text


textLink.Text = "Syncfusion .NET components and controls";
//Set the font
textLink.Font = font;
//Draw the hyperlink in PDF page
textLink.DrawTextWebLink(page, new PointF(10, 40));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create the font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 12.0F)
'Create the Text Web Link.
Dim textLink As New PdfTextWebLink()
'Add the hyperlink
textLink.Url = "http://www.syncfusion.com"
'Set the link text
textLink.Text = "Syncfusion .NET components and controls"
'Set the font
textLink.Font = font
'Draw the hyperlink in PDF page
textLink.DrawTextWebLink(loadedPage.Graphics, New PointF(10, 40))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)

UWP

C#
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add a page to the PDF document.
PdfPage pdfPage = pdfDocument.Pages.Add();
//Create a PDF Template.
PdfTemplate template = new PdfTemplate(100, 50);
//Draw a rectangle on the template graphics
template.Graphics.DrawRectangle(PdfBrushes.BurlyWood, new
System.Drawing.RectangleF(0, 0, 100, 50));
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14);
PdfBrush brush = new PdfSolidBrush(Color.Black);
//Draw a string using the graphics of the template.
template.Graphics.DrawString("Hello World", font, brush, 5, 5);
//Draw the template on the page graphics of the document.
pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty);
//Save the document.

Copyright © 2001 - 2019 Syncfusion Inc. 128


PDF Working with Hyperlinks

pdfDocument.Save("Output.pdf");
//close the document
pdfDocument.Close(true);

VB.NET
'Create a new PDF document.
Dim pdfDocument As New PdfDocument()
'Add a page to the PDF document.
Dim pdfPage As PdfPage = pdfDocument.Pages.Add()
'Create a PDF Template.
Dim template As New PdfTemplate(100, 50)
'Draw a rectangle on the template graphics.
template.Graphics.DrawRectangle(PdfBrushes.BurlyWood, New
System.Drawing.RectangleF(0, 0, 100, 50))
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 14)
Dim brush As PdfBrush = New PdfSolidBrush(Color.Black)
'Draw a string using the graphics of the template.
template.Graphics.DrawString("Hello World", font, brush, 5, 5)
'Draw the template on the page graphics of the document.
pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty)
'Save the document.
pdfDocument.Save("Output.pdf")
'close the document
pdfDocument.Close(True)

UWP

C#
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add a page to the PDF document
PdfPage pdfPage = pdfDocument.Pages.Add();
//Create a header and draw the image.
RectangleF bounds = new RectangleF(0, 0,
pdfDocument.Pages[0].GetClientSize().Width, 50);
PdfPageTemplateElement header = new PdfPageTemplateElement(bounds);
PdfImage image = new PdfBitmap(@"Logo.png");
//Draw the image in the header.
header.Graphics.DrawImage(image, new PointF(0, 0), new SizeF(100, 50));
//Add the header at the top.
pdfDocument.Template.Top = header;
//Create a Page template that can be used as footer.
PdfPageTemplateElement footer = new PdfPageTemplateElement(bounds);
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
PdfBrush brush = new PdfSolidBrush(Color.Black);
//Create page number field.
PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);
//Create page count field.
PdfPageCountField count = new PdfPageCountField(font, brush);
//Add the fields in composite fields.
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page
{0} of {1}", pageNumber, count);

Copyright © 2001 - 2019 Syncfusion Inc. 129


PDF Working with Hyperlinks

compositeField.Bounds = footer.Bounds;
//Draw the composite field in footer.
compositeField.Draw(footer.Graphics, new PointF(470, 40));
//Add the footer template at the bottom.
pdfDocument.Template.Bottom = footer;
//Save and close the document.
pdfDocument.Save("Output.pdf");
pdfDocument.Close(true);

VB.NET
'Create a new PDF document.
Dim pdfDocument As New PdfDocument()
'Add a page to the PDF document.
Dim pdfPage As PdfPage = pdfDocument.Pages.Add()
'Create a header and draw the image.
Dim bounds As New RectangleF(0, 0,
pdfDocument.Pages(0).GetClientSize().Width, 50)
Dim header As New PdfPageTemplateElement(bounds)
Dim image As PdfImage = New PdfBitmap("Logo.jpg")
'Draw the image in the Header.
header.Graphics.DrawImage(image, New PointF(0, 0), New SizeF(100, 50))
'Add the header at the top.
pdfDocument.Template.Top = header
'Create a page template that can be used as footer.
Dim footer As New PdfPageTemplateElement(bounds)
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 7)
Dim brush As PdfBrush = New PdfSolidBrush(Color.Black)
'Create page number field.
Dim pageNumber As New PdfPageNumberField(font, brush)
'Create page count field.
Dim count As New PdfPageCountField(font, brush)
'Add the fields in composite fields.
Dim compositeField As New PdfCompositeField(font, brush, "Page {0} of {1}",
pageNumber, count)
compositeField.Bounds = footer.Bounds
'Draw the composite field in footer.
compositeField.Draw(footer.Graphics, New PointF(470, 40))
'Add the footer template at the bottom.
pdfDocument.Template.Bottom = footer
'Save and close the document.
pdfDocument.Save("Output.pdf")
pdfDocument.Close(True)

UWP

C#
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a page to the document
PdfPage page = document.Pages.Add();
//Initialize PdfPen to draw the polygon
PdfPen pen = new PdfPen(PdfBrushes.Brown, 10f);

Copyright © 2001 - 2019 Syncfusion Inc. 130


PDF Working with Hyperlinks

//Initialize PdfLinearGradientBrush for drawing the polygon


PdfLinearGradientBrush brush = new PdfLinearGradientBrush(new PointF(10,
100), new PointF(100, 200), new PdfColor(Color.Red), new
PdfColor(Color.Green));
//Create the polygon points
PointF p1 = new PointF(10, 100);
PointF p2 = new PointF(10, 200);
PointF p3 = new PointF(100, 100);
PointF p4 = new PointF(100, 200);
PointF p5 = new PointF(55, 150);
PointF[] points = { p1, p2, p3, p4, p5 };
//Draw the polygon on PDF document
page.Graphics.DrawPolygon(pen, brush, points);
//Save the PDF document
document.Save("Output.pdf");
//Close the instance of PdfDocument
document.Close(true);

VB.NET
'Create a new PDF document
Dim document As PdfDocument = New PdfDocument
'Add a page to the document
Dim page As PdfPage = document.Pages.Add
'Initialize PdfPen to draw the polygon
Dim pen As PdfPen = New PdfPen(PdfBrushes.Brown, 10.0F)
'Initialize PdfLinearGradientBrush for drawing the polygon
Dim brush As PdfLinearGradientBrush = New PdfLinearGradientBrush(New
PointF(10, 100), New PointF(100, 200), New PdfColor(Color.Red), New
PdfColor(Color.Green))
'Create the polygon points
Dim p1 As PointF = New PointF(10, 100)
Dim p2 As PointF = New PointF(10, 200)
Dim p3 As PointF = New PointF(100, 100)
Dim p4 As PointF = New PointF(100, 200)
Dim p5 As PointF = New PointF(55, 150)
Dim points As PointF() = {p1, p2, p3, p4, p5}
'Draw the polygon on PDF document
page.Graphics.DrawPolygon(pen, brush, points)
'Save the PDF document
document.Save("Output.pdf")
'Close the instance of PdfDocument
document.Close(True)

UWP

C#
//Creates a new document.
PdfDocument document = new PdfDocument();
//Adds a page.
PdfPage page = document.Pages.Add();
//Creates document bookmarks.
PdfBookmark bookmark = document.Bookmarks.Add("Page 1");

Copyright © 2001 - 2019 Syncfusion Inc. 131


PDF Working with Hyperlinks

//Sets the destination page.


bookmark.Destination = new PdfDestination(page);
//Sets the destination location.
bookmark.Destination.Location = new PointF(20, 20);
//Sets the text style and color.
bookmark.TextStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Red;
//Saves and closes the PDF document.
document.Save("Output.pdf");
document.Close(True);

VB.NET
'Creates a new document.
Dim document As New PdfDocument()
'Adds a page.
Dim page As PdfPage = document.Pages.Add()
'Creates document bookmarks.
Dim bookmark As PdfBookmark = document.Bookmarks.Add("Page 1")
'Sets the destination page.
bookmark.Destination = New PdfDestination(page)
'Sets the destination location.
bookmark.Destination.Location = New PointF(20, 20)
'Sets the text style and color.
bookmark.TextStyle = PdfTextStyle.Bold
bookmark.Color = Color.Red
'Saves and closes the PDF document.
document.Save("Output.pdf")
document.Close(True)

UWP

C#
//Create a new PDF document.
PdfDocument doc = new PdfDocument();
//Add a page to the document.
PdfPage page = doc.Pages.Add();
//Create an instance for named destination.
PdfNamedDestination destination = new PdfNamedDestination("TOC");
destination.Destination = new PdfDestination(page);
//Set the location
destination.Destination.Location = new PointF(0, 500);
//Set zoom factor to 400 percentage
destination.Destination.Zoom = 4;
doc.NamedDestinationCollection.Add(destination);
//Draw the text.
page.Graphics.DrawString("Hello World!!", new
PdfStandardFont(PdfFontFamily.Helvetica, 10), PdfBrushes.Black, new
PointF(0, 500));
//Save the document.
doc.Save("Output.pdf");
//Close the document.
doc.Close(true);

Copyright © 2001 - 2019 Syncfusion Inc. 132


PDF Working with Hyperlinks

VB.NET
'Create a new PDF document.
Dim doc As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = doc.Pages.Add()
'Create an instance for named destination.
Dim destination As New PdfNamedDestination("TOC")
destination.Destination = New PdfDestination(page)
'Set the location
destination.Destination.Location = New PointF(0, 500)
'Set zoom factor to 400 percentage
destination.Destination.Zoom = 4
doc.NamedDestinationCollection.Add(destination)
'Draw the text.
page.Graphics.DrawString("Hello World!!", New
PdfStandardFont(PdfFontFamily.Helvetica, 10), PdfBrushes.Black, New
PointF(0, 500))
'Save the document.
doc.Save("Output.pdf")
'Close the document.
doc.Close(True)

UWP

C#
//Creates a new PDF document.
PdfDocument document = new PdfDocument();
//Creates a new page
PdfPage page = document.Pages.Add();
//Creates a rectangle
RectangleF rectangle = new RectangleF(10, 40, 30, 30);
//Creates a new popup annotation.
PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(rectangle,"Test
popup annotation");
popupAnnotation.Border.Width = 4;
popupAnnotation.Border.HorizontalRadius = 20;
popupAnnotation.Border.VerticalRadius = 30;
//Sets the pdf popup icon.
popupAnnotation.Icon = PdfPopupIcon.NewParagraph;
//Adds this annotation to the created page.
page.Annotations.Add(popupAnnotation);
//Saves the document to disk.
document.Save("PopupAnnotation.pdf");
document.Close(true);

VB.NET
'Creates a new PDF document.
Dim document As New PdfDocument()
'Creates a new page
Dim page As PdfPage = document.Pages.Add()

Copyright © 2001 - 2019 Syncfusion Inc. 133


PDF Working with Hyperlinks

'Creates a new rectangle


Dim rectangle As New RectangleF(10, 40, 30, 30)
'Creates a new popup annotation.
Dim popupAnnotation As New PdfPopupAnnotation(rectangle, "Test popup
annotation")
popupAnnotation.Border.Width = 4
popupAnnotation.Border.HorizontalRadius = 20
popupAnnotation.Border.VerticalRadius = 30
'Sets the pdf popup icon.
popupAnnotation.Icon = PdfPopupIcon.NewParagraph
'Adds this annotation to the created page.
page.Annotations.Add(popupAnnotation)
'Saves the document to disk.
document.Save("PopupAnnotation.pdf")
document.Close(True)

UWP

C#
//Creates a new PDF document
PdfDocument document = new PdfDocument();
//Creates an attachment
PdfAttachment attachment = new PdfAttachment("Input.txt");
attachment.ModificationDate = DateTime.Now;
attachment.Description = "Input.txt";
attachment.MimeType = "application/txt";
//Adds the attachment to the document
document.Attachments.Add(attachment);
//Saves and closes the PDF document
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Creates a new PDF document
Dim document As New PdfDocument()
'Creates an attachment
Dim attachment As New PdfAttachment("Input.txt")
attachment.ModificationDate = DateTime.Now
attachment.Description = "Input.txt"
attachment.MimeType = "application/txt"
'Adds the attachment to the document
document.Attachments.Add(attachment)
'Saves and closes the PDF document
document.Save("Output.pdf")
document.Close(True)

UWP

C#

Copyright © 2001 - 2019 Syncfusion Inc. 134


PDF Working with Hyperlinks

//Create a new PDF document.


PdfDocument document = new PdfDocument();
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f,
PdfFontStyle.Bold);
PdfBrush brush = PdfBrushes.Black;
//Document security.
PdfSecurity security = document.Security;
//Specifies key size and encryption algorithm
security.KeySize = PdfEncryptionKeySize.Key128Bit;
security.Algorithm = PdfEncryptionAlgorithm.RC4;
security.UserPassword = "password";
graphics.DrawString("Encrypted with RC4 128bit", font, brush, new PointF(0,
40));
//Save and close the document.
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
Dim page As PdfPage = document.Pages.Add()
Dim graphics As PdfGraphics = page.Graphics
Dim font As New PdfStandardFont(PdfFontFamily.TimesRoman, 20.0F,
PdfFontStyle.Bold)
Dim brush As PdfBrush = PdfBrushes.Black
'Document security.
Dim security As PdfSecurity = document.Security
'Specifies key size and encryption algorithm
security.KeySize = PdfEncryptionKeySize.Key128Bit
security.Algorithm = PdfEncryptionAlgorithm.RC4
security.UserPassword = "password"
graphics.DrawString("Encrypted with RC4 128bit", font, brush, New PointF(0,
40))
'Save and close the document.
document.Save("Output.pdf")
document.Close(True)

UWP

C#
//Load a PDF document
PdfLoadedDocument document = new PdfLoadedDocument("Input.pdf");
// Get first page from the document
PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;
//Create PDF redaction for the page
PdfRedaction redaction = new PdfRedaction(new RectangleF(343, 147, 60, 17),
System.Drawing.Color.Black);
//Adds redaction to the loaded page
page.Redactions.Add(redaction);
//Save and close the PDF document

Copyright © 2001 - 2019 Syncfusion Inc. 135


PDF Working with Hyperlinks

document.Save("Output.pdf");
document.Close(true);

VB.NET
'Load a PDF document
Dim document As PdfLoadedDocument = New PdfLoadedDocument("Input.pdf")
'Get first page from the document
Dim page As PdfLoadedPage = TryCast(document.Pages(0), PdfLoadedPage)
'Create PDF redaction for the page
Dim redaction As PdfRedaction = New PdfRedaction(New RectangleF(343, 147,
60, 17), System.Drawing.Color.Black)
'Adds redaction to the loaded page
page.Redactions.Add(redaction)
'Save and close the PDF document
document.Save("Output.pdf")
document.Close(True)

UWP

C#
//Creates a new PDF document.
PdfDocument document = new PdfDocument();
//Adds a new page.
PdfPageBase page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
//Creates a certificate instance from PFX file with private key.
PdfCertificate pdfCert = new PdfCertificate(@"PDF.pfx", "syncfusion");
//Creates a digital signature.
PdfSignature signature = new PdfSignature(document, page, pdfCert,
"Signature");
//Sets an image for signature field.
PdfBitmap signatureImage = new PdfBitmap(@"signature.jpg");
//Sets signature information
signature.Bounds = new RectangleF(new PointF(0, 0),
signatureImage.PhysicalDimension);
signature.ContactInfo = "johndoe@owned.us";
signature.LocationInfo = "Honolulu, Hawaii";
signature.Reason = "I am author of this document.";
//Draws the signature image.
graphics.DrawImage(signatureImage, 0, 0);
//Saves and closes the document.
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Creates a new PDF document.
Dim document As New PdfDocument()
'Adds a new page.
Dim page As PdfPageBase = document.Pages.Add()
Dim graphics As PdfGraphics = page.Graphics
'Creates a certificate instance from PFX file with private key.

Copyright © 2001 - 2019 Syncfusion Inc. 136


PDF Working with Hyperlinks

Dim pdfCert As New PdfCertificate("PDF.pfx", "syncfusion")


'Creates a digital signature.
Dim signature As New PdfSignature(document, page, pdfCert, "Signature")
'Sets an image for signature field.
Dim signatureImage As New PdfBitmap("signature.jpg")
'Sets signature info.
signature.Bounds = New RectangleF(New PointF(0, 0),
signatureImage.PhysicalDimension)
signature.ContactInfo = "johndoe@owned.us"
signature.LocationInfo = "Honolulu, Hawaii"
signature.Reason = "I am author of this document."
'Draws the signature image.
graphics.DrawImage(signatureImage, 0, 0)
'Saves and closes the document.
document.Save("Output.pdf")
document.Close(True)

UWP

C#
//Creating new PDF Document
PdfDocument doc = new PdfDocument();
//Adding new page to PDF document
PdfPage page = doc.Pages.Add();
//Drawing Code39 barcode
PdfCode39Barcode barcode = new PdfCode39Barcode();
//Setting height of the barcode
barcode.BarHeight = 45;
barcode.Text = "CODE39$";
//Printing barcode on to the Pdf.
barcode.Draw(page, new PointF(25, 70 ));
//Saving the Document
doc.Save("CODE39.pdf");

VB.NET
'Creating new PDF Document
Dim doc As New PdfDocument()
'Adding new page to PDF document
Dim page As PdfPage = doc.Pages.Add()
'Drawing Code39 barcode
Dim barcode As New PdfCode39Barcode()
'Setting height of the barcode
barcode.BarHeight = 45
barcode.Text = "CODE39$"
'Printing barcode on to the Pdf.
barcode.Draw(page, New PointF(25, 70))
'Saving the Document
doc.Save("CODE39.pdf")

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 137


PDF Working with Hyperlinks

C#
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Create and add new launch action to the document
PdfLaunchAction action = new PdfLaunchAction("../../Data/logo.png");
document.Actions.AfterOpen = action;
//Save the document
document.Save("LaunchAction.pdf");
document.Close(true);

VB.NET
'Create a new PDF document
Dim document As New PdfDocument()
'Create and add new launch action to the document
Dim action As New PdfLaunchAction("../../Data/logo.png")
document.Actions.AfterOpen = action
'Save the document
document.Save("LaunchAction.pdf")
document.Close(True)

UWP

C#
//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Add a page to the PDF document.
PdfPage pdfPage = pdfDocument.Pages.Add();
PdfGraphics graphics = pdfPage.Graphics;
//set the font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//watermark text.
PdfGraphicsState state = graphics.Save();
graphics.SetTransparency(0.25f);
graphics.RotateTransform(-40);
graphics.DrawString("Imported using Essential PDF", font, PdfPens.Red,
PdfBrushes.Red, new PointF(-150, 450));
//Save and close the document.
pdfDocument.Save("watermark.pdf");
pdfDocument.Close(true);

VB.NET
'Create a new PDF document.
Dim pdfDocument As New PdfDocument()
'Add a page to the PDF document.
Dim pdfPage As PdfPage = pdfDocument.Pages.Add()
Dim graphics As PdfGraphics = pdfPage.Graphics
'set the font
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)

Copyright © 2001 - 2019 Syncfusion Inc. 138


PDF Working with Hyperlinks

' watermark text.


Dim state As PdfGraphicsState = graphics.Save()
graphics.SetTransparency(0.25F)
graphics.RotateTransform(-40)
graphics.DrawString("Imported using Essential PDF", font, PdfPens.Red,
PdfBrushes.Red, New PointF(-150, 450))
'Save and close the document.
pdfDocument.Save("watermark.pdf")
pdfDocument.Close(True)

UWP

C#
// Create a new instance of PdfDocument class.
PdfDocument document = new PdfDocument();
//Create a new portfolio
document.PortfolioInformation = new PdfPortfolioInformation();
//set the view mode of the portfolio
document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;
//Create the attachment
PdfAttachment pdfFile = new
PdfAttachment("../../Data/CorporateBrochure.pdf");
pdfFile.FileName = "CorporateBrochure.pdf";
//Set the startup document to view
document.PortfolioInformation.StartupDocument = pdfFile;
//Add the attachment to the document
document.Attachments.Add(pdfFile);
// Save and close the document.
document.Save("Sample.pdf");
document.Close(true);

VB.NET
' Create a new instance of PdfDocument class.
Dim document As New PdfDocument()
'Create a new portfolio
document.PortfolioInformation = New PdfPortfolioInformation()
'Set the view mode of the portfolio
document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile
'Create the attachment
Dim pdfFile As New PdfAttachment("../../Data/CorporateBrochure.pdf")
pdfFile.FileName = "CorporateBrochure.pdf"
'Set the startup document to view
document.PortfolioInformation.StartupDocument = pdfFile
'Add the attachment to the document
document.Attachments.Add(pdfFile)
'Save and close the document.
document.Save("Sample.pdf")
document.Close(True)

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 139


PDF Working with Hyperlinks

C#
//Create PDF document.
PdfDocument document = new PdfDocument();
PdfPage page = document.Pages.Add();
//Add the first layer.
PdfPageLayer layer = page.Layers.Add("Layer1");
PdfGraphics graphics = layer.Graphics;
graphics.TranslateTransform(100, 60);
//Draw arc.
PdfPen pen = new PdfPen(System.Drawing.Color.Red, 50);
RectangleF bounds = new RectangleF(0, 0, 50, 50);
graphics.DrawArc(pen, bounds, 360, 360);
//Add another layer on the page.
PdfPageLayer layer2 = page.Layers.Add("Layer2");
graphics = layer2.Graphics;
graphics.TranslateTransform(100, 180);
//Draw ellipse.
graphics.DrawEllipse(pen, bounds);
//Save the document.
document.Save("Sample.pdf");
//Close the document
document.Close(true);

VB.NET
'Create PDF document.
Dim document As New PdfDocument()
Dim page As PdfPage = document.Pages.Add()
'Add the first layer.
Dim layer As PdfPageLayer = page.Layers.Add("Layer1")
Dim graphics As PdfGraphics = layer.Graphics
graphics.TranslateTransform(100, 60)
'Draw arc.
Dim pen As New PdfPen(System.Drawing.Color.Red, 50)
Dim bounds As New RectangleF(0, 0, 50, 50)
graphics.DrawArc(pen, bounds, 360, 360)
'Add another layer on the page.
Dim layer2 As PdfPageLayer = page.Layers.Add("Layer2")
graphics = layer2.Graphics
graphics.TranslateTransform(100, 180)
'Draw ellipse.
graphics.DrawEllipse(pen, bounds)
'Save the document.
document.Save("Sample.pdf")
'Close the document
document.Close(True)

UWP

C#
//Creates new PDF document

Copyright © 2001 - 2019 Syncfusion Inc. 140


PDF Working with Hyperlinks

PdfDocument doc = new PdfDocument();


//Set the document title
doc.DocumentInformation.Title = "PdfTextElement";
//Creates new page
PdfPage page = doc.Pages.Add();
//Initialize the structure element with tag type paragraph
PdfStructureElement structureElement = new
PdfStructureElement(PdfTagType.Paragraph);
//represents the text that is exact replacement for PdfTextElement
structureElement.ActualText = "Simple paragraph element";
string text = "Adventure Works Cycles, the fictitious company on which the
AdventureWorks sample databases are based, is a large, multinational
manufacturing company. The company manufactures and sells metal and
composite bicycles to North American, European and Asian commercial markets.
While its base operation is located in Washington with 290 employees,
several regional sales teams are located throughout their market base.";
//Initialize the PDF text element
PdfTextElement element = new PdfTextElement(text);
//Adding tag to the text element
element.PdfTag = structureElement;
//Creates font for the text element
element.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
element.Brush = new PdfSolidBrush(new PdfColor(89, 89, 93));
//Draws text
PdfLayoutResult result = element.Draw(page, new RectangleF(0, 0,
page.Graphics.ClientSize.Width, 200));
//Save the document and dispose it
doc.Save("Output.pdf");
doc.Close(true);

VB.NET
'Creates new PDF document
Dim doc As PdfDocument = New PdfDocument()
'Set the document title
doc.DocumentInformation.Title = "PdfTextElement"
'Creates new page
Dim page As PdfPage = doc.Pages.Add()
'Initialize the structure element with tag type paragraph
Dim structureElement As PdfStructureElement = New
PdfStructureElement(PdfTagType.Paragraph)
'represents the text that is exact replacement for PdfTextElement
structureElement.ActualText = "Simple paragraph element"
Dim text As String = "Adventure Works Cycles, the fictitious company on
which the AdventureWorks sample databases are based, is a large,
multinational manufacturing company. The company manufactures and sells
metal and composite bicycles to North American, European and Asian
commercial markets. While its base operation is located in Washington with
290 employees, several regional sales teams are located throughout their
market base."
'Initialize the PDF text element
Dim element As PdfTextElement = New PdfTextElement(text)
'Adding tag to the text element
element.PdfTag = structureElement
'Creates font for the text element
element.Font = New PdfStandardFont(PdfFontFamily.TimesRoman, 12)

Copyright © 2001 - 2019 Syncfusion Inc. 141


PDF Working with Hyperlinks

element.Brush = New PdfSolidBrush(New PdfColor(89, 89, 93))


'Draws text
Dim result As PdfLayoutResult = element.Draw(page, New RectangleF(0, 0,
page.Graphics.ClientSize.Width, 200))
'Save the document and dispose it
doc.Save("Output.pdf")
doc.Close(True)

UWP

C#
//Load the existing PDF document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("input.pdf");
//Create a new compression option.
PdfCompressionOptions options = new PdfCompressionOptions();
//Enable the compress image.
options.CompressImages = true;
//Set the image quality.
options.ImageQuality = 50;
//Assign the compression option to the document
loadedDocument.CompressionOptions = options;
//Save the PDF document
loadedDocument.Save("Output.pdf");
//Close the document
loadedDocument.Close(true);

VB.NET
'Load the existing PDF document
Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument("input.pdf")
'Create a new compression option.
Dim options As PdfCompressionOptions = New PdfCompressionOptions()
'Enable the compress image.
options.CompressImages = True
'Set the image quality.
options.ImageQuality = 50
'Assign the compression option to the document
loadedDocument.CompressionOptions = options
'Save the PDF document
loadedDocument.Save("Output.pdf")
'Close the document
loadedDocument.Close(True)

Optimizing embedded font


You can optimize the embedded fonts in an existing PDF document by enabling the OptimizeFont
property available in the PdfCompressionOptions class. This technique reduces the font file size by
removing all the unused glyph data.
The following example code snippet illustrates how to optimize embedded font in existing PDF
document.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 142


PDF Working with Hyperlinks

//Load the existing PDF document


PdfLoadedDocument loadedDocument = new PdfLoadedDocument("input.pdf");
//Create a new compression option.
PdfCompressionOptions options = new PdfCompressionOptions();
//Enable the optimize font option
options.OptimizeFont = true;
//Assign the compression option to the document
loadedDocument.CompressionOptions = options;
//Save the PDF document
loadedDocument.Save("Output.pdf");
//Close the document
loadedDocument.Close(true);

VB.NET
'Load the existing PDF document
Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument("input.pdf")
'Create a new compression option.
Dim options As PdfCompressionOptions = New PdfCompressionOptions()
'Enable the optimize font option
options.OptimizeFont = True
'Assign the compression option to the document
loadedDocument.CompressionOptions = options
'Save the PDF document
loadedDocument.Save("Output.pdf")
'Close the document
loadedDocument.Close(True)

Note: The font compression support only in TrueType and Type2 embedded fonts.
Optimizing page contents
You can compress the page contents in an existing PDF document by enabling the
OptimizePageContents property available in the PdfCompressionOptions class. This technique removes
the unwanted data in the content streams such as commented lines, white spaces, etc.,
The following example code snippet illustrates how to optimize page contents in existing PDF document.
C#
//Load the existing PDF document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("input.pdf");
//Create a new compression option.
PdfCompressionOptions options = new PdfCompressionOptions();
//Enable the optimize page contents.
options.OptimizePageContents = true;
//Assign the compression option to the document
loadedDocument.CompressionOptions = options;
//Save the PDF document
loadedDocument.Save("Output.pdf");
//Close the document
loadedDocument.Close(true);

VB.NET
'Load the existing PDF document

Copyright © 2001 - 2019 Syncfusion Inc. 143


PDF Working with Hyperlinks

Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument("input.pdf")


'Create a new compression option.
Dim options As PdfCompressionOptions = New PdfCompressionOptions()
'Enable the optimize page contents.
options.OptimizePageContents = True
'Assign the compression option to the document
loadedDocument.CompressionOptions = options
'Save the PDF document
loadedDocument.Save("Output.pdf")
'Close the document
loadedDocument.Close(True)

Remove metadata information


You can reduce the PDF file size by removing the PDF document metadata information. This can be
achieved by enabling the RemoveMetadata property available in the PdfCompressionOptions class.
The following example code snippet illustrates how to optimize page contents in existing PDF document.
C#
//Load the existing PDF document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("input.pdf");
//Create a new compression option.
PdfCompressionOptions options = new PdfCompressionOptions();
//Set to remove the metadata information.
options.RemoveMetadata = true;
//Assign the compression option to the document
loadedDocument.CompressionOptions = options;
//Save the PDF document
loadedDocument.Save("Output.pdf");
//Close the document
loadedDocument.Close(true);

VB.NET
'Load the existing PDF document
Dim loadedDocument As PdfLoadedDocument = New PdfLoadedDocument("input.pdf")
'Create a new compression option.
Dim options As PdfCompressionOptions = New PdfCompressionOptions()
'Set to remove the metadata information.
options.RemoveMetadata = True
'Assign the compression option to the document
loadedDocument.CompressionOptions = options
'Save the PDF document
loadedDocument.Save("Output.pdf")
'Close the document
loadedDocument.Close(True)

Compressing the PDF content


Essential PDF allows you to control the compression level of the document by using the
PdfCompressionLevel Enum. The compression level can be set to best, normal, none etc...
Content compression involves,

Copyright © 2001 - 2019 Syncfusion Inc. 144


PDF Working with Hyperlinks

1) Removing all extra space characters. 2) Inserting a single repeat character to indicate a string of
repeated characters. 3) Substituting smaller bit strings for frequently occurring characters.
The following code snippet illustrates how to compress the content of the PDF document.
C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Set the compression level to best
document.Compression = PdfCompressionLevel.Best;
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
string text = "Hello World!!!";
PdfTextElement textElement = new PdfTextElement(text, font);
PdfLayoutResult result = textElement.Draw(page, new RectangleF(0, 0,
font.MeasureString(text).Width, page.GetClientSize().Height));
for (int i = 0; i < 1000; i++)
{
result = textElement.Draw(result.Page, new RectangleF(0,
result.Bounds.Bottom +10, font.MeasureString(text).Width,
page.GetClientSize().Height));
}
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Set the compression level to best
document.Compression = PdfCompressionLevel.Best
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
Dim text As String = "Hello World!!!"
Dim textElement As New PdfTextElement(text, font)
Dim result As PdfLayoutResult = textElement.Draw(page, New RectangleF(0, 0,
font.MeasureString(text).Width, page.GetClientSize().Height))
For i As Integer = 0 To 999
result = textElement.Draw(result.Page, New RectangleF(0,
result.Bounds.Bottom + 10, font.MeasureString(text).Width,
page.GetClientSize().Height))
Next
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)

Copyright © 2001 - 2019 Syncfusion Inc. 145


PDF Working with Hyperlinks

You can compress the existing PDF document by using the following code snippet.
C#
//Load the PDF document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Input.pdf");
//Disable the incremental update
loadedDocument.FileStructure.IncrementalUpdate = false;
//Set the compression level
loadedDocument.Compression = PdfCompressionLevel.Best;
//Save and close the document
loadedDocument.Save("Output.pdf");
loadedDocument.Close(true);

VB.NET
'Load the PDF document
Dim loadedDocument As New PdfLoadedDocument("Input.pdf")
'Disable the incremental update
loadedDocument.FileStructure.IncrementalUpdate = False
'Set the compression level
loadedDocument.Compression = PdfCompressionLevel.Best
'Save and close the document
loadedDocument.Save("Output.pdf")
loadedDocument.Close(True)

Compressing images
Essential PDF allows you to compress/change the quality of the image in the PDF document by using the
following code snippet.
C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
PdfBitmap image = new PdfBitmap("Input.jpg");
//Reduce the quality of the image
image.Quality = 50;
image.Draw(page, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);

VB.NET
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.

Copyright © 2001 - 2019 Syncfusion Inc. 146


PDF Working with Hyperlinks

Dim graphics As PdfGraphics = page.Graphics


Dim image As New PdfBitmap("Input.jpg")
'Reduce the quality of the image
image.Quality = 50
image.Draw(page, New PointF(0, 0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)

You can compress the images in the existing PDF document by using the following code snippet.
C#
//Load the PDF document which c images
PdfLoadedDocument loadedDocument = new PdfLoadedDocument("Input.pdf");
//Disable the incremental update
loadedDocument.FileStructure.IncrementalUpdate = false;
//iterate all the pages to replace images
foreach (PdfPageBase page in loadedDocument.Pages)
{
//Extract the images from the document
Image[] extractedImages = page.ExtractImages();
//Iterate all the image
for (int j = 0; j < extractedImages.Count(); j++)
{
PdfBitmap image = new PdfBitmap(extractedImages[j]);
//reduce the quality of the image
image.Quality = 50;
//replace the compressed image with old image in the PDF document
page.ReplaceImage(j, image);
}
}
//Save and close the document
loadedDocument.Save("Output.pdf");
loadedDocument.Close(true);

VB.NET
'Load the PDF document which consist of images
Dim loadedDocument As New PdfLoadedDocument("Input.pdf")
'Disable the incremental update
loadedDocument.FileStructure.IncrementalUpdate = False
'iterate all the pages to replace images
For Each page As PdfPageBase In loadedDocument.Pages
'Extract the images from the document
Dim extractedImages As Image() = page.ExtractImages()
'Iterate all the image
For j As Integer = 0 To extractedImages.Count() - 1
Dim image As New PdfBitmap(extractedImages(j))
'reduce the quality of the image
image.Quality = 50
'replace the compressed image with old image in the PDF document
page.ReplaceImage(j, image)
Next
Next

Copyright © 2001 - 2019 Syncfusion Inc. 147


PDF Working with PDF Conformance

'Save and close the document


loadedDocument.Save("Output.pdf")
loadedDocument.Close(True)

Working with PDF Conformance


The Essential PDF currently supports the following PDF conformances:

 PDF/A-1a conformance
 PDF/A-1b conformance
 PDF/X-1a conformance
 PDF/A-2a conformance
 PDF/A-2b conformance
 PDF/A-2u conformance
 PDF/A-3a conformance
 PDF/A-3b conformance
 PDF/A-3u conformance

Note: 1. To know more details about PDF/A standard refer


https://en.wikipedia.org/wiki/PDF/A#Description
2. To know more details about PDF/X standard refer https://en.wikipedia.org/wiki/PDF/X
Note: Essential PDF supports PDF conformances only in Windows Forms, WPF, ASP.NET and ASP.NET
MVC platforms.
PDF/A-1b conformance
You can create a PDF/A-1b document by specifying the conformance level as Pdf_A1B through
PdfConformanceLevel Enum when creating the new PDF document, as shown below.
C#
//Create a new document with PDF/A-1b standard.
PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
//Add a page.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Create a solid brush.
PdfBrush brush = new PdfSolidBrush(Color.Black);
Font font = new Font("Arial", 20f, FontStyle.Regular);
//Set the font.
PdfFont pdfFont = new PdfTrueTypeFont(font, FontStyle.Regular, 12, false,
true);
//Draw the text.
graphics.DrawString("Hello world!", pdfFont, brush, new PointF(20, 20));
//Save and close the document.
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Create a new document with PDF/A-1b standard.
Dim document As New PdfDocument(PdfConformanceLevel.Pdf_A1B)

Copyright © 2001 - 2019 Syncfusion Inc. 148


PDF Working with PDF Conformance

'Add a page.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Create a solid brush.
Dim brush As PdfBrush = New PdfSolidBrush(Color.Black)
Dim font As New Font("Arial", 20.0F, FontStyle.Regular)
'Set the font.
Dim pdfFont As PdfFont = New PdfTrueTypeFont(font, FontStyle.Regular, 12,
False, True)
'Draw the text.
graphics.DrawString("Hello world!", pdfFont, brush, New PointF(20, 20))
'Save and close the document.
document.Save("Output.pdf")
document.Close(True)

UWP

C#
//Create ZUGFeRD invoice PDF
PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

VB.NET
'Create ZUGFeRD invoice PDF
Dim document As PdfDocument = New PdfDocument(PdfConformanceLevel.Pdf_A3B)
document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic

UWP

C#
//Create a PDF document
PdfDocument pdfDoc = new PdfDocument();
//Create a page
PdfPage page = pdfDoc.Pages.Add();
// Get XMP object.
XmpMetadata metaData = pdfDoc.DocumentInformation.XmpMetadata;
// XMP Basic Schema.
BasicSchema basic = metaData.BasicSchema;
//set the basic details of the document
basic.Advisory.Add("advisory");
basic.BaseURL = new Uri("http://google.com");
basic.CreateDate = DateTime.Now;
basic.CreatorTool = "creator tool";
basic.Identifier.Add("identifier");
basic.Label = "label";
basic.MetadataDate = DateTime.Now;
basic.ModifyDate = DateTime.Now;
basic.Nickname = "nickname";

Copyright © 2001 - 2019 Syncfusion Inc. 149


PDF Working with PDF Conformance

basic.Rating.Add(-25);
//save the document
pdfDoc.Save("DocumentInformation.pdf");
pdfDoc.Close(true);

VB.NET
'Create a PDF document
Dim pdfDoc As New PdfDocument()
'Create a page
Dim page As PdfPage = pdfDoc.Pages.Add()
' Get XMP object.
Dim metaData As XmpMetadata = pdfDoc.DocumentInformation.XmpMetadata
' XMP Basic Schema.
Dim basic As BasicSchema = metaData.BasicSchema
'set the basic details of the document
basic.Advisory.Add("advisory")
basic.BaseURL = New Uri("http://google.com")
basic.CreateDate = DateTime.Now
basic.CreatorTool = "creator tool"
basic.Identifier.Add("identifier")
basic.Label = "label"
basic.MetadataDate = DateTime.Now
basic.ModifyDate = DateTime.Now
basic.Nickname = "nickname"
basic.Rating.Add(-25)
'save the document
pdfDoc.Save("DocumentInformation.pdf")
pdfDoc.Close(True)

UWP

C#
//Creates a new PDF document.
PdfDocument pdfDocument = new PdfDocument();
//Adds a page to the PDF document
PdfPage pdfPage = pdfDocument.Pages.Add();
//Acquires graphics of the page.
PdfGraphics graphics = pdfPage.Graphics;
//Creates CalGray color space.
PdfCalGrayColorSpace calGrayColorSpace = new PdfCalGrayColorSpace();
//Updates color values.
calGrayColorSpace.Gamma = 0.7;
calGrayColorSpace.WhitePoint = new double[] { 0.2, 1, 0.8 };
PdfCalGrayColor calGrayColorSpace1 = new PdfCalGrayColor(calGrayColorSpace);
calGrayColorSpace1.Gray = 0.1;
PdfBrush brush = new PdfSolidBrush(calGrayColorSpace1);
RectangleF bounds = new RectangleF(0, 0, 300, 300);
//Draws rectangle by using the PdfBrush
graphics.DrawRectangle(brush, bounds);
//Saves the document.
pdfDocument.Save("Output.pdf");
//closes the document

Copyright © 2001 - 2019 Syncfusion Inc. 150


PDF Working with PDF Conformance

pdfDocument.Close(true);

VB.NET
'Creates a new PDF document.
Dim pdfDocument As New PdfDocument()
'Adds a page to the PDF document
Dim pdfPage As PdfPage = pdfDocument.Pages.Add()
'Acquires graphics of the page.
Dim graphics As PdfGraphics = pdfPage.Graphics
'Creates CalGray color space.
Dim calGrayColorSpace As New PdfCalGrayColorSpace()
'Updates color values.
calGrayColorSpace.Gamma = 0.7
calGrayColorSpace.WhitePoint = New Double() {0.2, 1, 0.8}
Dim calGrayColorSpace1 As New PdfCalGrayColor(calGrayColorSpace)
calGrayColorSpace1.Gray = 0.1
Dim brush As PdfBrush = New PdfSolidBrush(calGrayColorSpace1)
Dim bounds As New RectangleF(0, 0, 300, 300)
'Draws rectangle using the PdfBrush
graphics.DrawRectangle(brush, bounds)
'Saves the document.
pdfDocument.Save("Output.pdf")
'closes the document
pdfDocument.Close(True)

UWP

C#
//Create a new document
PdfDocument document = new PdfDocument();
//Add a page
PdfPage page = document.Pages.Add();
//Create JavaScript action
PdfJavaScriptAction scriptAction = new
PdfJavaScriptAction("app.alert(\"Hello World!!!\")");
//Add the JavaScript action
document.Actions.AfterOpen = scriptAction;
//Save and close the PDF document
document.Save("Output.pdf");
document.Close(true);

VB.NET
'Create a new document
Dim document As New PdfDocument()
'Add a page
Dim page As PdfPage = document.Pages.Add()
'Create JavaScript action
Dim scriptAction As New PdfJavaScriptAction("app.alert(""Hello World!!!"")")
'Add the JavaScript action
document.Actions.AfterOpen = scriptAction
'Save and close the PDF document

Copyright © 2001 - 2019 Syncfusion Inc. 151


Presentation Working with PDF Conformance

document.Save("Output.pdf")
document.Close(True)

UWP

Presentation
C#
using Syncfusion.Presentation;

VB.NET
Imports Syncfusion.Presentation

UWP

C#
//Opens an existing Presentation from file system
IPresentation pptxDoc = Presentation.Open(fileName);

VB.NET
'Opens an existing Presentation from file system
Dim pptxDoc As IPresentation = Presentation.Open(fileName)

UWP

C#
//Opens a PowerPoint presentation
IPresentation sourcePresentation = Presentation.Open(fileName);
//Clones the Presentation
IPresentation clonedPresentation = sourcePresentation.Clone();
//Gets the first slide from the cloned PowerPoint presentation
ISlide firstSlide = clonedPresentation.Slides[0];
//Adds a textbox in a slide by specifying its position and size
IShape textShape = firstSlide.AddTextBox(100, 75, 756, 200);
//Adds a paragraph in the body of the textShape
IParagraph paragraph = textShape.TextBody.AddParagraph();
//Adds a textPart in the paragraph
ITextPart textPart = paragraph.AddTextPart("Essential Presentation");
//Saves the modified cloned PowerPoint presentation
clonedPresentation.Save("ClonedPresentation.pptx");

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 152


Presentation Working with PDF Conformance

'Opens a PowerPoint presentation


Dim sourcePresentation_1 As IPresentation = Presentation.Open(fileName)
'Clones the Presentation
Dim clonedPresentation_1 As IPresentation = sourcePresentation_1.Clone()
'Gets the first slide from the cloned PowerPoint presentation
Dim firstSlide As ISlide = clonedPresentation_1.Slides(0)
'Adds a textbox in a slide by specifying its position and size
Dim textShape As IShape = firstSlide.AddTextBox(100, 75, 756, 200)
'Adds a paragraph in the body of the textShape
Dim paragraph As IParagraph = textShape.TextBody.AddParagraph()
'Adds a textPart in the paragraph
Dim textPart As ITextPart = paragraph.AddTextPart("Essential Presentation")
'Saves the modified cloned PowerPoint presentation
clonedPresentation_1.Save("ClonedPresentation.pptx")

UWP

C#
//Creates a PowerPoint instance
IPresentation pptxDoc = Presentation.Create();
//Adds a slide to the PowerPoint presentation
ISlide slide = pptxDoc.Slides.Add();
//Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx");
//Closes the Presentation instance
pptxDoc.Close();

VB.NET
'Creates a PowerPoint instance
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds a slide to the PowerPoint presentation
Dim slide As ISlide = pptxDoc.Slides.Add()
'Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx")
'Closes the Presentation instance
pptxDoc.Close()

UWP

C#
//Create a PowerPoint presentation
IPresentation pptxDoc = Presentation.Create();
//Access the first master slide in PowerPoint file
IMasterSlide masterSlide = pptxDoc.Masters[0];
//Get the first shape name from the master slide
string shapeName = masterSlide.Shapes[0].ShapeName;
//Save the PowerPoint file
pptxDoc.Save("Sample.pptx");
//Close the Presentation instance

Copyright © 2001 - 2019 Syncfusion Inc. 153


Presentation Working with PDF Conformance

pptxDoc.Close();

VB.NET
'Create a PowerPoint presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Access the first master slide in PowerPoint file.
Dim masterSlide As IMasterSlide = pptxDoc.Masters(0)
'Get the first shape name from the master slide
Dim shapeName As String = masterSlide.Shapes(0).ShapeName
'Save the PowerPoint file.
pptxDoc.Save("AccessMasterSlide.pptx")
'Close the Presentation instance
pptxDoc.Close()

Create a custom LayoutSlide


The real-world scenarios always require more predefined templates. The Syncfusion PowerPoint library
lets you build your own custom layout designs and use them to create individual slides.
The following code example demonstrates how to create new custom layout slide and access layout
slide in Presentation.
C#
//Create a PowerPoint instance
IPresentation pptxDoc = Presentation.Create();
//Add a new LayoutSlide to the PowerPoint file
ILayoutSlide layoutSlide =
pptxDoc.Masters[0].LayoutSlides.Add(SlideLayoutType.Blank, "CustomLayout");
//Add a shape to the LayoutSlide
IShape shape = layoutSlide.Shapes.AddShape(AutoShapeType.Diamond, 30, 20,
400, 300);
//Change the background color for LayoutSlide
layoutSlide.Background.Fill.SolidFill.Color = ColorObject.FromArgb(78, 89,
90);
//Save the PowerPoint file
pptxDoc.Save("LayoutSlide.pptx");
//Close the Presentation instance
pptxDoc.Close();

VB.NET
'Creates a PowerPoint instance
Dim pptxDoc As IPresentation = Presentation.Create()
'Add a new LayoutSlide to the PowerPoint file
Dim layoutSlide As ILayoutSlide =
pptxDoc.Masters(0).LayoutSlides.Add(SlideLayoutType.Blank, "CustomLayout")
'Add a shape to the LayoutSlide
Dim shape As IShape = layoutSlide.Shapes.AddShape(AutoShapeType.Diamond, 30,
20, 400, 300)
'Change the background color for LayoutSlide
layoutSlide.Background.Fill.SolidFill.Color = ColorObject.FromArgb(78, 89,
90)
'Save the PowerPoint file
pptxDoc.Save("LayoutSlide.pptx")

Copyright © 2001 - 2019 Syncfusion Inc. 154


Presentation Working with Paragraph

'Close the Presentation instance


pptxDoc.Close()

Working with Paragraph


Adding Paragraph to slide
All the textual contents in a Presentation document is represented by Paragraphs. You can have any
number of paragraphs within a TextBody of a textbox or shape in a PowerPoint presentation.
The following code example demonstrates how to add a paragraph in a slide.
C#
//Creates PowerPoint Presentation
IPresentation pptxDoc = Presentation.Create();
//Adds slide to the PowerPoint
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Adds textbox to the slide
IShape textboxShape = slide.AddTextBox(0, 0, 500, 500);
//Adds paragraph to the textbody of textbox
IParagraph paragraph = textboxShape.TextBody.AddParagraph();
//Adds a TextPart to the paragraph
ITextPart textPart = paragraph.AddTextPart();
//Adds text to the TextPart
textPart.Text = "AdventureWorks Cycles, the fictitious company on which the
AdventureWorks sample databases are based, is a large, multinational
manufacturing company. The company manufactures and sells metal and
composite bicycles to North American, European and Asian commercial markets.
While its base operation is located in Washington with 290 employees,
several regional sales teams are located throughout their market base.";
//Saves the Presentation
pptxDoc.Save("Output.pptx");
//Closes the Presentation
pptxDoc.Close();

VB.NET
'Creates PowerPoint Presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds slide to the PowerPoint
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Adds textbox to the slide
Dim textboxShape As IShape = slide.AddTextBox(0, 0, 500, 500)
'Adds paragraph to the textbody of textbox
Dim paragraph As IParagraph = textboxShape.TextBody.AddParagraph()
'Adds a TextPart to the paragraph
Dim textPart As ITextPart = paragraph.AddTextPart()
'Adds text to the TextPart
textPart.Text = "AdventureWorks Cycles, the fictitious company on which the
AdventureWorks sample databases are based, is a large, multinational
manufacturing company. The company manufactures and sells metal and
composite bicycles to North American, European and Asian commercial markets.
While its base operation is located in Washington with 290 employees,
several regional sales teams are located throughout their market base."
'Saves the Presentation
pptxDoc.Save("Output.pptx")

Copyright © 2001 - 2019 Syncfusion Inc. 155


Presentation Working with Paragraph

'Closes the Presentation


pptxDoc.Close()

UWP

C#
//Creates a new Presentation instance.
IPresentation pptxDoc = Presentation.Create();
//Adds a blank slide into the Presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
// Adds a textbox to hold the list
IShape textBoxShape = slide.AddTextBox(65, 140, 410, 270);
// Adds a new paragraph with the text in the left hand side textbox.
IParagraph paragraph = textBoxShape.TextBody.AddParagraph("AdventureWorks
Cycles, the fictitious company on which the AdventureWorks sample databases
are based, is a large, multinational manufacturing company.");
//Sets the list type as Numbered
paragraph.ListFormat.Type = ListType.Numbered;
//Sets the numbered style (list numbering) as Arabic number following by
period.
paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod;
//Sets the starting value as 1
paragraph.ListFormat.StartValue = 1;
//Sets the list level as 1
paragraph.IndentLevelNumber = 1;
// Sets the hanging value
paragraph.FirstLineIndent = -20;
// Sets the bullet character size. Here, 100 means 100% of its text.
Possible values can range from 25 to 400.
paragraph.ListFormat.Size = 100;
// Adds another paragraph with the text in the left hand side textbox.
paragraph = textBoxShape.TextBody.AddParagraph("The company manufactures and
sells metal and composite bicycles to North American, European and Asian
commercial markets.");
//Sets the list type as bulleted
paragraph.ListFormat.Type = ListType.Numbered;
//Sets the numbered style (list numbering) as Arabic number following by
period.
paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod;
//Sets the list level as 1
paragraph.IndentLevelNumber = 1;
// Sets the hanging value
paragraph.FirstLineIndent = -20;
// Sets the bullet character size. Here, 100 means 100% of its text.
Possible values can range from 25 to 400.
paragraph.ListFormat.Size = 100;
// Adds another paragraph with the text in the left hand side textbox.
paragraph = textBoxShape.TextBody.AddParagraph("While its base operation is
located in Washington with 290 employees, several regional sales teams are
located throughout their market base.");
//Sets the list type as bulleted
paragraph.ListFormat.Type = ListType.Numbered;
//Sets the numbered style (list numbering) as Arabic number following by
period.

Copyright © 2001 - 2019 Syncfusion Inc. 156


Presentation Working with Paragraph

paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod;
//Sets the list level as 1
paragraph.IndentLevelNumber = 1;
// Sets the hanging value
paragraph.FirstLineIndent = -20;
// Sets the bullet character size. Here, 100 means 100% of its text.
Possible values can range from 25 to 400.
paragraph.ListFormat.Size = 100;
//Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx");
Process.Start("Sample.pptx");
//Closes the Presentation
pptxDoc.Close();

VB.NET
'Creates a new Presentation instance.
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds the slide into the Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Adds a textbox to hold the list
Dim textBoxShape As IShape = slide.AddTextBox(65, 140, 410, 270)
'Adds a new paragraph with the text in the left hand side textbox.
Dim paragraph As IParagraph =
textBoxShape.TextBody.AddParagraph("AdventureWorks Cycles, the fictitious
company on which the AdventureWorks sample databases are based, is a large,
multinational manufacturing company.")
'Sets the list type as Numbered
paragraph.ListFormat.Type = ListType.Numbered
'Sets the numbered style (list numbering) as Arabic number following by
period.
paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod
'Sets the starting value as 1
paragraph.ListFormat.StartValue = 1
'Sets the list level as 1
paragraph.IndentLevelNumber = 1
' Sets the hanging value
paragraph.FirstLineIndent = -20
' Sets the bullet character size. Here, 100 means 100% of its text. Possible
values can range from 25 to 400.
paragraph.ListFormat.Size = 100
' Adds another paragraph with the text in the left hand side textbox.
paragraph = textBoxShape.TextBody.AddParagraph("The company manufactures and
sells metal and composite bicycles to North American, European and Asian
commercial markets.")
'Sets the list type as bulleted
paragraph.ListFormat.Type = ListType.Numbered
'Sets the numbered style (list numbering) as Arabic number following by
period.
paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod
'Sets the list level as 1
paragraph.IndentLevelNumber = 1
' Sets the hanging value
paragraph.FirstLineIndent = -20
' Sets the bullet character size. Here, 100 means 100% of its text. Possible
values can range from 25 to 400.

Copyright © 2001 - 2019 Syncfusion Inc. 157


Presentation Working with Paragraph

paragraph.ListFormat.Size = 100
' Adds another paragraph with the text in the left hand side textbox.
paragraph = textBoxShape.TextBody.AddParagraph("While its base operation is
located Washington with 290 employees, several regional sales teams are
located throughout their market base.")
'Sets the list type as bulleted
paragraph.ListFormat.Type = ListType.Numbered
'Sets the numbered style (list numbering) as Arabic number following by
period.
paragraph.ListFormat.NumberStyle = NumberedListStyle.ArabicPeriod
'Sets the list level as 1
paragraph.IndentLevelNumber = 1
' Sets the hanging value
paragraph.FirstLineIndent = -20
' Sets the bullet character size. Here, 100 means 100% of its text. Possible
values can range from 25 to 400.
paragraph.ListFormat.Size = 100
'Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx")
Process.Start("Sample.pptx")
'Closes the Presentation
pptxDoc.Close()

UWP

C#
//Creates an instance for PowerPoint
IPresentation pptxDoc = Presentation.Create();
//Adds a blank slide to Presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Adds normal shape to slide
slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200, 300, 300);
//Creates an instance for image as stream
Stream imageStream = File.Open("Image.jpg", FileMode.Open);
//Add picture to the shape collection
IPicture picture = slide.Shapes.AddPicture(imageStream, 373, 83, 526, 382);
//Saves the Presentation
pptxDoc.Save("Sample.pptx");
//Closes the stream
imageStream.Close();
//Closes the Presentation
pptxDoc.Close();

VB.NET
'Creates an instance for PowerPoint Presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds a blank slide to Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Adds normal shape to slide
slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200, 300, 300)
'Creates an instance for image as stream
Dim imageStream As Stream = File.Open("Image.jpg", FileMode.Open)

Copyright © 2001 - 2019 Syncfusion Inc. 158


Presentation Working with Paragraph

'Adds picture to the shape collection


Dim picture As IPicture = slide.Shapes.AddPicture(imageStream, 373, 83, 500,
382)
'Saves the Presentation
pptxDoc.Save("Sample.pptx")
'Closes the stream
imageStream.Close()
'Closes the Presentation
pptxDoc.Close()

UWP

C#
//Creates a instance of Presentation
IPresentation pptxDoc = Presentation.Create();
//Adds a blank slide.
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Gets a picture as stream.
Stream pictureStream = File.Open("Image.png", FileMode.Open);
//Adds the picture to a slide by specifying its size and position.
IPicture picture = slide.Pictures.AddPicture(pictureStream, 0, 0, 250, 250);
//Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx");
//Dispose the image stream
pictureStream.Dispose();
//Closes the Presentation
pptxDoc.Close();

VB.NET
'Creates a instance of Presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds a blank slide.
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Gets a picture as stream.
Dim pictureStream As Stream = File.Open("Image.png", FileMode.Open)
'Adds the picture to a slide by specifying its size and position.
Dim picture As IPicture = slide.Pictures.AddPicture(pictureStream, 0, 0,
250, 250)
'Saves the Presentation to the file system.
pptxDoc.Save("Sample.pptx")
'Dispose the image stream
pictureStream.Dispose()
'Closes the Presentation
pptxDoc.Close()

UWP

C#
//Create a PowerPoint presentation

Copyright © 2001 - 2019 Syncfusion Inc. 159


Presentation Working with Paragraph

IPresentation pptxDoc = Presentation.Create();


//Add slide to the presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add a table to the slide
ITable table = slide.Shapes.AddTable(2, 2, 100, 120, 300, 200);
//Initialize index values to add text to table cells
int rowIndex = 0, colIndex;
//Iterate row-wise cells and add text to it
foreach (IRow rows in table.Rows)
{
colIndex = 0;
foreach (ICell cell in rows.Cells)
{
cell.TextBody.AddParagraph("(" + rowIndex.ToString() + " , " +
colIndex.ToString() + ")");
colIndex++;
}
rowIndex++;
}
//Save the presentation
pptxDoc.Save("Sample.pptx");
//Close the presentation
pptxDoc.Close();

VB.NET
'Create a PowerPoint presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Add slide to the presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add a table to the slide
Dim table As ITable = slide.Shapes.AddTable(2, 2, 100, 120, 300, 200)
'Initialize index values to add text to table cells
Dim rowIndex As Integer = 0, colIndex As Integer
'Iterate row-wise cells and add text to it
For Each rows As IRow In table.Rows
colIndex = 0
For Each cell As ICell In rows.Cells
cell.TextBody.AddParagraph("(" + rowIndex.ToString() + " , " +
colIndex.ToString() + ")")
colIndex += 1
Next
rowIndex += 1
Next
'Save the presentation
pptxDoc.Save("Sample.pptx")
'Close the presentation
pptxDoc.Close()

UWP

C#
//Creates a Presentation instance

Copyright © 2001 - 2019 Syncfusion Inc. 160


Presentation Working with Paragraph

IPresentation pptxDoc = Presentation.Create();


//Adds a blank slide to the Presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Adds chart to the slide with position and size
IPresentationChart chart = slide.Charts.AddChart(100, 10, 700, 500);
//Specifies the chart title
chart.ChartTitle = "Sales Analysis";
//Sets chart data - Row1
chart.ChartData.SetValue(1, 2, "Jan");
chart.ChartData.SetValue(1, 3, "Feb");
chart.ChartData.SetValue(1, 4, "March");
//Sets chart data - Row2
chart.ChartData.SetValue(2, 1, 2010);
chart.ChartData.SetValue(2, 2, 60);
chart.ChartData.SetValue(2, 3, 70);
chart.ChartData.SetValue(2, 4, 80);
//Sets chart data - Row3
chart.ChartData.SetValue(3, 1, 2011);
chart.ChartData.SetValue(3, 2, 80);
chart.ChartData.SetValue(3, 3, 70);
chart.ChartData.SetValue(3, 4, 60);
//Sets chart data - Row4
chart.ChartData.SetValue(4, 1, 2012);
chart.ChartData.SetValue(4, 2, 60);
chart.ChartData.SetValue(4, 3, 70);
chart.ChartData.SetValue(4, 4, 80);
//Creates a new chart series with the name
IOfficeChartSerie seriesJan = chart.Series.Add("Jan");
//Sets the data range of chart series – start row, start column, end row,
end column
seriesJan.Values = chart.ChartData[2, 2, 4, 2];
//Creates a new chart series with the name
IOfficeChartSerie seriesFeb = chart.Series.Add("Feb");
//Sets the data range of chart series – start row, start column, end row,
end column
seriesFeb.Values = chart.ChartData[2, 3, 4, 3];
//Creates a new chart series with the name
IOfficeChartSerie seriesMarch = chart.Series.Add("March");
//Sets the data range of chart series – start row, start column, end row,
end column
seriesMarch.Values = chart.ChartData[2, 4, 4, 4];
//Sets the data range of the category axis
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 4, 1];
//Specifies the chart type
chart.ChartType = OfficeChartType.Column_Clustered;
//Adds the third slide into the Presentation
pptxDoc.Save("sample.pptx");
//Closes the Presentation
pptxDoc.Close();

VB.NET
'Creates a Presentation instance
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds a blank slide to the Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)

Copyright © 2001 - 2019 Syncfusion Inc. 161


Presentation Working with Paragraph

'Adds chart to the slide with position and size


Dim chart As IPresentationChart = slide.Charts.AddChart(100, 10, 700, 500)
'Specifies the chart title
chart.ChartTitle = "Sales Analysis"
'Sets chart data - Row1
chart.ChartData.SetValue(1, 2, "Jan")
chart.ChartData.SetValue(1, 3, "Feb")
chart.ChartData.SetValue(1, 4, "March")
'Sets chart data - Row2
chart.ChartData.SetValue(2, 1, 2010)
chart.ChartData.SetValue(2, 2, 60)
chart.ChartData.SetValue(2, 3, 70)
chart.ChartData.SetValue(2, 4, 80)
'Sets chart data - Row3
chart.ChartData.SetValue(3, 1, 2011)
chart.ChartData.SetValue(3, 2, 80)
chart.ChartData.SetValue(3, 3, 70)
chart.ChartData.SetValue(3, 4, 60)
'Sets chart data - Row4
chart.ChartData.SetValue(4, 1, 2012)
chart.ChartData.SetValue(4, 2, 60)
chart.ChartData.SetValue(4, 3, 70)
chart.ChartData.SetValue(4, 4, 80)
'Creates a new chart series with the name
Dim seriesJan As IOfficeChartSerie = chart.Series.Add("Jan")
'Sets the data range of chart series – start row, start column, end row, end
column
seriesJan.Values = chart.ChartData(2, 2, 4, 2)
'Creates a new chart series with the name
Dim seriesFeb As IOfficeChartSerie = chart.Series.Add("Feb")
'Sets the data range of chart series – start row, start column, end row, end
column
seriesFeb.Values = chart.ChartData(2, 3, 4, 3)
'Creates a new chart series with the name
Dim seriesMarch As IOfficeChartSerie = chart.Series.Add("March")
'Sets the data range of chart series – start row, start column, end row, end
column
seriesMarch.Values = chart.ChartData(2, 4, 4, 4)
'Sets the data range of the category axis
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData(2, 1, 4, 1)
'Specifies the chart type
chart.ChartType = OfficeChartType.Column_Clustered
'Adds the third slide into the Presentation
pptxDoc.Save("sample.pptx")
'Closes the Presentation
pptxDoc.Close()

UWP

C#
//Create an instance for PowerPoint
using (IPresentation pptxDoc = Presentation.Create())
{
//Add a blank slide to Presentation

Copyright © 2001 - 2019 Syncfusion Inc. 162


Presentation Working with Paragraph

ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);


//Add normal shape to slide
IShape cubeShape = slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200, 300,
300);
//Access the animation sequence to create effects
ISequence sequence = slide.Timeline.MainSequence;
//Add bounce effect to the shape
IEffect bounceEffect = sequence.AddEffect(cubeShape, EffectType.Bounce,
EffectSubtype.None, EffectTriggerType.OnClick);
//Save the Presentation
pptxDoc.Save("Sample.pptx");
}

VB.NET
'Create an instance for PowerPoint
Using pptxDoc As IPresentation = Presentation.Create()
'Add a blank slide to Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add normal shape to slide
Dim cubeShape As IShape = slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200,
300, 300)
'Access the animation sequence to create effects
Dim sequence As ISequence = slide.Timeline.MainSequence
'Add bounce effect to the shape
Dim bounceEffect As IEffect = sequence.AddEffect(cubeShape,
EffectType.Bounce, EffectSubtype.None, EffectTriggerType.OnClick)
'Save the Presentation
pptxDoc.Save("Sample.pptx")
End Using

UWP

C#
//Create a PowerPoint presentation
IPresentation pptxDoc = Presentation.Create();
//Add a blank slide to the presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add a shape to the slide
IShape cubeShape = slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200, 300,
300);
//Set the transition effect type
slide.SlideTransition.TransitionEffect = TransitionEffect.Checkerboard;
//Set the transition effect options
slide.SlideTransition.TransitionEffectOption =
TransitionEffectOption.Across;
//Save the presentation
pptxDoc.Save("Sample.pptx");
//Close the presentation
pptxDoc.Close();

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 163


Presentation Working with Paragraph

'Create a PowerPoint presentation


Dim pptxDoc As IPresentation = Presentation.Create()
'Add a blank slide to the presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add a shape to the slide
Dim cubeShape As IShape = slide.Shapes.AddShape(AutoShapeType.Cube, 50, 200,
300, 300)
'Set the transition effect type
slide.SlideTransition.TransitionEffect = TransitionEffect.Checkerboard
'Set the transition effect option
slide.SlideTransition.TransitionEffectOption = TransitionEffectOption.Across
'Save the presentation
pptxDoc.Save("Sample.pptx")
'Close the presentation
pptxDoc.Close()

UWP

C#
//Create a new PowerPoint file
using (IPresentation pptxDoc = Presentation.Create())
{
//Add a slide to the PowerPoint file
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add a rectangle shape on the slide
IShape rectangle = slide.Shapes.AddShape(AutoShapeType.Rectangle, 200, 300,
100, 100);
//Add an oval shape on the slide
IShape oval = slide.Shapes.AddShape(AutoShapeType.Oval, 400, 10, 100, 100);
//Add elbow connector on the slide and connect the end points of connector
with specified port positions 0 and 4 of the beginning and end shapes
IConnector connector = slide.Shapes.AddConnector(ConnectorType.Elbow,
rectangle, 0, oval, 4);
//Save the PowerPoint file
pptxDoc.Save("Sample.pptx");
}

VB.NET
'Create a new PowerPoint file
Using pptxDoc As IPresentation = Presentation.Create
'Add a slide to the PowerPoint file
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add a rectangle shape on the slide
Dim rectangle As IShape = slide.Shapes.AddShape(AutoShapeType.Rectangle,
200, 300, 100, 100)
'Add an oval shape on the slide
Dim oval As IShape = slide.Shapes.AddShape(AutoShapeType.Oval, 400, 10, 100,
100)
'Add elbow connector on the slide and connect the end points of connector
with specified port positions 0 and 4 of the beginning and end shapes
Dim connector As IConnector = slide.Shapes.AddConnector(ConnectorType.Elbow,
rectangle, 0, oval, 4)

Copyright © 2001 - 2019 Syncfusion Inc. 164


Presentation Working with Paragraph

'Save the PowerPoint file


pptxDoc.Save("Sample.pptx")
End Using

UWP

C#
//Creates a Presentation without slides.
IPresentation pptxDoc = Presentation.Create();
//Adds new slide with blank slide layout type.
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Adds new notes slide in the specified slide.
INotesSlide notesSlide = slide.AddNotesSlide();
//Adds text content into the Notes Slide.
notesSlide.NotesTextBody.AddParagraph("Notes content");
//Saves Presentation with specified file name with extension.
pptxDoc.Save("PresentationWithNotesSlide.pptx");

VB.NET
'Creates a Presentation without slides.
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds new slide with blank slide layout type.
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Adds new notes slide in the specified slide.
Dim notesSlide As INotesSlide = slide.AddNotesSlide()
'Adds text content into the Notes Slide.
notesSlide.NotesTextBody.AddParagraph("Notes content")
'Saves Presentation with specified file name with extension.
pptxDoc.Save("PresentationWithNotesSlide.pptx")

UWP

C#
// Create an instance of PowerPoint Presentation
IPresentation pptxDoc = Presentation.Create();
//Add a blank slide to the Presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add a BasicBlockList SmartArt to the slide at the specified size and
position.
ISmartArt smartArt = slide.Shapes.AddSmartArt(SmartArtType.BasicBlockList,
0, 0, 640, 426);
//Save the Presentation
pptxDoc.Save("SmartArt.pptx");
//Close the Presentation
pptxDoc.Close();

VB.NET

Copyright © 2001 - 2019 Syncfusion Inc. 165


Presentation Working with Paragraph

'Create an instance of PowerPoint Presentation


Dim pptxDoc As IPresentation = Presentation.Create()
'Add a blank slide to the Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add a BasicBlockList SmartArt to the slide at the specified size and
position.
Dim smartArt As ISmartArt =
slide.Shapes.AddSmartArt(SmartArtType.BasicBlockList, 0, 0, 640, 426)
'Save the Presentation
pptxDoc.Save("SmartArt.pptx")
'Close the Presentation
pptxDoc.Close()

UWP

C#
//Create a PowerPoint Presentation
IPresentation pptxDoc = Presentation.Create();
//Add a slide to the Presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add a comment to the slide
slide.Comments.Add(10, 10, "Author1", "A1", "Can we change the font size to
20?", DateTime.Now);
//Save the Presentation
pptxDoc.Save("Comment.pptx");
//Close the Presentation
pptxDoc.Close();

VB.NET
'Create a PowerPoint Presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Add a slide to the Presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add a comment to the slide
slide.Comments.Add(10, 10, "Author1", "A1", "Can we change the font size to
20?", DateTime.Now)
'Save the Presentation
pptxDoc.Save("Comment.pptx")
'Close the Presentation
pptxDoc.Close()

UWP

C#
//Creates a PowerPoint presentation
IPresentation pptxDoc = Presentation.Create();
//Adds a section to the PowerPoint presentation
ISection section = pptxDoc.Sections.Add();
//Sets a name to the created section

Copyright © 2001 - 2019 Syncfusion Inc. 166


Presentation Working with Paragraph

section.Name = "SectionDemo";
//Adds a slide to the created section
ISlide slide = section.AddSlide(SlideLayoutType.Blank);
//Adds a text box to the slide
slide.AddTextBox(10, 10, 100, 100).TextBody.AddParagraph("Slide in
SectionDemo");
//Saves the PowerPoint presentation
pptxDoc.Save("Section.pptx");

VB.NET
'Creates a PowerPoint presentation
Dim pptxDoc As IPresentation = Presentation.Create()
'Adds a section to the PowerPoint presentation
Dim section As ISection = pptxDoc.Sections.Add()
'Sets a name to the created section
section.Name = "SectionDemo"
'Adds a slide to the created section
Dim slide As ISlide = section.AddSlide(SlideLayoutType.Blank)
'Adds a text box to the slide
slide.AddTextBox(10, 10, 100, 100).TextBody.AddParagraph("Slide in
SectionDemo")
'Saves the PowerPoint presentation
pptxDoc.Save("Section.PPTX")

UWP

C#
//Opens an existing macro enabled PowerPoint presentation
IPresentation pptxDoc = Presentation.Open("Sample.PPTM");
//Adds a blank slide to the presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Adds a text box to the slide
IParagraph paragraph = slide.Shapes.AddTextBox(100, 100, 300,
80).TextBody.AddParagraph("Preserve Macros");
//Saves the presentation
pptxDoc.Save("Output.PPTM");
//Closes the presentation
pptxDoc.Close();

VB.NET
'Opens an existing macro enabled PowerPoint presentation
Dim pptxDoc As IPresentation = Presentation.Open("Sample.PPTM")
'Adds a blank slide to the presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Adds a text box to the slide
Dim paragraph As IParagraph = slide.Shapes.AddTextBox(100, 100, 300,
80).TextBody.AddParagraph("Preserve Macros")
'Saves the presentation
pptxDoc.Save("Output.PPTM")
'Closes the presentation
pptxDoc.Close()

Copyright © 2001 - 2019 Syncfusion Inc. 167


Presentation Working with Paragraph

UWP

C#
//Creates an instance for Presentation
IPresentation presentation = Presentation.Create();
//Adds slide to Presentation
ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank);
//Adds textbox to slide
IShape shape = slide.Shapes.AddTextBox(100, 30, 200, 300);
//Adds a paragraph with text content.
IParagraph paragraph = shape.TextBody.AddParagraph("Password Protected.");
//Protects the file with password
presentation.Encrypt("PASSWORD!@1#$");
//Saves the Presentation
presentation.Save("Sample.pptx");
//Closes the Presentation
presentation.Close();

VB.NET
'Creates an instance for Presentation
Dim presentationDocument As IPresentation = Presentation.Create()
'Adds slide to Presentation
Dim slide As ISlide = presentationDocument.Slides.Add(SlideLayoutType.Blank)
'Adds textbox to slide
Dim shape As IShape = slide.Shapes.AddTextBox(100, 30, 200, 300)
'Adds a paragraph with text content.
Dim paragraph As IParagraph = shape.TextBody.AddParagraph("Password
Protected.")
'Protects the file with password
presentationDocument.Encrypt("PASSWORD!@1#$")
'Saves the Presentation
presentationDocument.Save("Sample.pptx")
'Closes the Presentation
presentationDocument.Close()

Note: PowerPoint Presentation doesn't support encryption in ASP.NET Core, Blazor and Xamarin.
Decrypting the PowerPoint Presentation
Essential Presentation provides ability to remove the encryption from the PowerPoint Presentation. You
can decrypt a PowerPoint Presentation by opening it with the password.
Opening the Encrypted PowerPoint Presentation
The following code example demonstrates opening the encrypted PowerPoint Presentation.
C#
//Opens an existing Presentation from file system and it can be decrypted by
using the provided password.
IPresentation presentation = Presentation.Open("Sample.pptx",
"PASSWORD!@1#$");

Copyright © 2001 - 2019 Syncfusion Inc. 168


Presentation Working with Paragraph

//Saves the Presentation


presentation.Save("Output.pptx");
//Closes the Presentation
presentation.Close();

VB.NET
'Opens an existing Presentation from file system and it can be decrypted by
using the provided password.
Dim presentationDocument As IPresentation = Presentation.Open("Sample.pptx",
"PASSWORD!@1#$")
'Saves the Presentation
presentationDocument.Save("Output.pptx")
'Closes the Presentation
presentationDocument.Close()

Removing the encryption from Presentation


The following code example demonstrates removing the encryption from a PowerPoint Presentation.
C#
//Opens an existing Presentation from file system and it can be decrypted by
using the provided password.
IPresentation presentation = Presentation.Open("Sample.pptx",
"PASSWORD!@1#$");
//Decrypts the document
presentation.RemoveEncryption();
//Saves the presentation
presentation.Save("Output.pptx");
//Closes the Presentation
presentation.Close();

VB.NET
'Opens an existing Presentation from file system and it can be decrypted by
using the provided password.
Dim presentationDocument As IPresentation = Presentation.Open("Sample.pptx",
"PASSWORD!@1#$")
'Decrypts the document
presentationDocument.RemoveEncryption()
'Saves the Presentation
presentationDocument.Save("Output.pptx")
'Closes the Presentation
presentationDocument.Close()

Write Protection
You can set write protection for a PowerPoint Presentation and remove protection from the write
protected PowerPoint presentation.
Protect PowerPoint Presentation
You can protect a PowerPoint Presentation with password to restrict unauthorized editing.
The following code example shows how to set write protection for a PowerPoint Presentation.

Copyright © 2001 - 2019 Syncfusion Inc. 169


Presentation Working with Paragraph

C#
//Create a new instance for PowerPoint presentation
IPresentation pptxDoc = Presentation.Create();
//Add the blank slide to the presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Add the shape to the slide
IShape shape = slide.Shapes.AddShape(AutoShapeType.BlockArc, 0, 0, 200,
200);
//Add the paragraph to the shape.
IParagraph paragraph = shape.TextBody.AddParagraph("welcome");
//Sets the author name
pptxDoc.BuiltInDocumentProperties.Author = "Syncfusion";
//Set the write protection for presentation instance
pptxDoc.SetWriteProtection("MYPASSWORD");
//Saves the modified cloned PowerPoint presentation
pptxDoc.Save("Sample.pptx");
//Close the presentation instance
pptxDoc.Close();

VB.NET
'Create a new instance for PowerPoint presentation
IPresentation pptxDoc = Presentation.Create()
'Add the blank slide to the presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Add the shape to the slide
IShape shape = slide.Shapes.AddShape(AutoShapeType.BlockArc, 0, 0, 200, 200)
'Add the paragraph to the shape.
IParagraph paragraph = shape.TextBody.AddParagraph("welcome")
'Sets the author name
pptxDoc.BuiltInDocumentProperties.Author = "Syncfusion"
'Set the write protection for presentation instance
pptxDoc.SetWriteProtection("MYPASSWORD")
'Saves the modified cloned PowerPoint presentation
pptxDoc.Save("Sample.pptx")
'Close the presentation instance
pptxDoc.Close()

UWP

C#
//Create new instance of PowerPoint presentation. [Equivalent to launching
MS PowerPoint with no slides].
IPresentation pptxDoc = Presentation.Create();
//Add slide with blank layout to presentation
ISlide slide = pptxDoc.Slides.Add(SlideLayoutType.Blank);
//Get the excel file as stream
Stream excelStream = File.Open("OleTemplate.xlsx", FileMode.Open);
//Image to be displayed, This can be any image
Stream imageStream = File.Open("OlePicture.png", FileMode.Open);
//Add an OLE object to the slide

Copyright © 2001 - 2019 Syncfusion Inc. 170


Presentation Working with Paragraph

IOleObject oleObject = slide.Shapes.AddOleObject(imageStream,


"Excel.Sheet.12", excelStream);
//Set size and position of the OLE object
oleObject.Left = 10;
oleObject.Top = 10;
oleObject.Width = 400;
oleObject.Height = 300;
//Save the presentation
pptxDoc.Save("OleObjectSample.pptx");
//Close the presentation
pptxDoc.Close();

VB.NET
'Create new instance of PowerPoint presentation. [Equivalent to launching MS
PowerPoint with no slides].
Dim pptxDoc As IPresentation = Presentation.Create()
'Add slide with blank layout to presentation
Dim slide As ISlide = pptxDoc.Slides.Add(SlideLayoutType.Blank)
'Get the excel file as stream
Dim excelStream As Stream = File.Open("OleTemplate.xlsx", FileMode.Open)
'Image to be displayed, This can be any image
Dim imageStream As Stream = File.Open("OlePicture.png", FileMode.Open)
'Add an OLE object to the slide
Dim oleObject As IOleObject = slide.Shapes.AddOleObject(imageStream,
"Excel.Sheet.12", excelStream)
'Set size and position of the OLE object
oleObject.Left = 10
oleObject.Top = 10
oleObject.Width = 400
oleObject.Height = 300
'Save the presentation
pptxDoc.Save("OleObjectSample.pptx")
'Close the presentation
pptxDoc.Close()

UWP

C#
//Namespaces to perform PPTX to Image conversion
using Syncfusion.Presentation;
using Syncfusion.OfficeChartToImageConverter;
using System.IO;
using Syncfusion.Drawing;
//Opens a PowerPoint Presentation file
IPresentation pptxDoc = Presentation.Open(fileName);
//Creates an instance of ChartToImageConverter
pptxDoc.ChartToImageConverter = new ChartToImageConverter();
//Sets the scaling mode as best
pptxDoc.ChartToImageConverter.ScalingMode =
Syncfusion.OfficeChart.ScalingMode.Best;
//Converts the first slide into image

Copyright © 2001 - 2019 Syncfusion Inc. 171


Presentation Working with Paragraph

Image image =
pptxDoc.Slides[0].ConvertToImage(Syncfusion.Drawing.ImageType.Metafile);
//Saves the image as file
image.Save("slide1.png");
//Disposes the image
image.Dispose();
//Closes the Presentation instance
pptxDoc.Close();

VB.NET
'Namespaces to perform PPTX to Image conversion
Imports Syncfusion.Presentation
Imports Syncfusion.OfficeChartToImageConverter
Imports Syncfusion.Drawing
Imports System.IO
'Opens a PowerPoint Presentation file
Dim pptxDoc As IPresentation = Presentation.Open(fileName)
'Creates an instance of ChartToImageConverter
pptxDoc.ChartToImageConverter = New ChartToImageConverter()
'Sets the scaling mode as best
pptxDoc.ChartToImageConverter.ScalingMode =
Syncfusion.OfficeChart.ScalingMode.Best
'Converts the first slide into image
Dim image As Image =
pptxDoc.Slides(0).ConvertToImage(Syncfusion.Drawing.ImageType.Metafile)
'Saves the image as file
image.Save("slide1.png")
'Disposes the image
image.Dispose()
'Closes the Presentation instance
Presentation_1.Close()

ASP.NET CORE

C#
//Namespaces to perform PPTX to PDF conversion
using Syncfusion.OfficeChartToImageConverter;
using Syncfusion.Presentation;
using Syncfusion.PresentationToPdfConverter;
using Syncfusion.Pdf;
//Opens a PowerPoint Presentation
IPresentation pptxDoc = Presentation.Open("Sample.pptx");
//Creates an instance of ChartToImageConverter and assigns it to
ChartToImageConverter property of Presentation
pptxDoc.ChartToImageConverter = new ChartToImageConverter();
//Converts the PowerPoint Presentation into PDF document
PdfDocument pdfDocument = PresentationToPdfConverter.Convert(pptxDoc);
//Saves the PDF document
pdfDocument.Save("Sample.pdf");
//Closes the PDF document
pdfDocument.Close(true);
//Closes the Presentation

Copyright © 2001 - 2019 Syncfusion Inc. 172


XlsIO Working with Paragraph

pptxDoc.Close();

VB.NET
'Namespaces to perform PPTX to PDF conversion
Imports Syncfusion.OfficeChartToImageConverter
Imports Syncfusion.Presentation
Imports Syncfusion.PresentationToPdfConverter
Imports Syncfusion.Pdf
'Opens a PowerPoint Presentation
Dim pptxDoc As IPresentation = Presentation.Open("Sample.pptx")
'Creates an instance of ChartToImageConverter and assigns it to
ChartToImageConverter property of Presentation
pptxDoc.ChartToImageConverter = New ChartToImageConverter()
'Converts the PowerPoint Presentation into PDF document
Dim pdfDocument As PdfDocument = PresentationToPdfConverter.Convert(pptxDoc)
'Saves the PDF document
pdfDocument.Save("Sample.pdf")
'Closes the PDF document
pdfDocument.Close(True)
'Closes the Presentation
pptxDoc.Close()

ASP.NET CORE

XlsIO
C#
using Syncfusion.XlsIO;

VB.NET
Imports Syncfusion.XlsIO

UWP

C#
//Creates a new instance for ExcelEngine
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(inputFileName);

VB.NET
'Creates a new instance for ExcelEngine
Dim excelEngine As New ExcelEngine()
'Loads or open an existing workbook through Open method of IWorkbooks
Dim workbook As IWorkbook = excelEngine.Excel.Workbooks.Open(inputFileName)

Copyright © 2001 - 2019 Syncfusion Inc. 173


XlsIO Working with Paragraph

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//The new workbook will have 5 worksheets
IWorkbook workbook = application.Workbooks.Create(5);
//Creating a Sheet
IWorksheet sheet = workbook.Worksheets.Create();
//Creating a Sheet with name “Sample”
IWorksheet namedSheet = workbook.Worksheets.Create("Sample");
workbook.SaveAs("Output.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
'The new workbook will have 5 worksheets
Dim workbook As IWorkbook = application.Workbooks.Create(5)
'Creating a sheet
Dim sheet As IWorksheet = workbook.Worksheets.Create()
'Creating a Sheet with name “Sample”
Dim namedSheet As IWorksheet = workbook.Worksheets.Create("Sample")
workbook.SaveAs("Output.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
//Insert a row
worksheet.InsertRow(3, 1, ExcelInsertOptions.FormatAsBefore);
//Inserting a column
worksheet.InsertColumn(2, 1, ExcelInsertOptions.FormatAsAfter);
workbook.SaveAs("Book1.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()

Copyright © 2001 - 2019 Syncfusion Inc. 174


XlsIO Working with Paragraph

Dim application As IApplication = excelEngine.Excel


application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Inserting a row
worksheet.InsertRow(3, 1, ExcelInsertOptions.FormatAsBefore)
'Inserting a column
worksheet.InsertColumn(2, 1, ExcelInsertOptions.FormatAsAfter)
workbook.SaveAs("Book1.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
//Access a range by specifying cell address
sheet.Range["A7"].Text = "Accessing a Range by specify cell address ";
//Access a range by specifying cell row and column index
sheet.Range[9, 1].Text = "Accessing a Range by specify cell row and column
index ";
//Access a Range by specifying using defined name
IName name = workbook.Names.Add("Name");
name.RefersToRange = sheet.Range["A11"];
sheet.Range["Name"].Text = "Accessing a Range by specifying using defined
name.";
//Accessing a Range of cells by specifying cells address
sheet.Range["A13:C13"].Text = "Accessing a Range of Cells (Method 1)";
//Accessing a Range of cells specifying cell row and column index
sheet.Range[15, 1, 15, 3].Text = "Accessing a Range of Cells (Method 2)";
workbook.SaveAs("Range.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Access a range by specify cell address
sheet.Range("A7").Text = "Accessing a Range by specify cell address "
'Access a range by specify cell row and column index
sheet.Range(9, 1).Text = "Accessing a Range by specify cell row and column
index "
'Access a Range by specifying using defined name
Dim name As IName = workbook.Names.Add("Name")
name.RefersToRange = sheet.Range("A11")

Copyright © 2001 - 2019 Syncfusion Inc. 175


XlsIO Working with Paragraph

sheet.Range("Name").Text = "Accessing a Range by specifying using defined


name"
'Accessing a Range of cells by specify cells address
sheet.Range("A13:C13").Text = "Accessing a Range of Cells (Method 1)"
'Accessing a Range of cells specify cell row and column index
sheet.Range(15, 1, 15, 3).Text = "Accessing a Range of Cells (Method 2)"
workbook.SaveAs("Range.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Creating a new style with cell back color, fill pattern and font attribute
IStyle style = workbook.Styles.Add("NewStyle");
style.Color = Color.LightGreen;
style.FillPattern = ExcelPattern.DarkUpwardDiagonal;
style.Font.Bold = true;
worksheet.Range["B2"].CellStyle = style;
workbook.SaveAs("Style.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Creating a new style with cell back color, fill pattern and font attribute
Dim style As IStyle = workbook.Styles.Add("NewStyle")
style.Color = Color.LightGreen
style.FillPattern = ExcelPattern.DarkUpwardDiagonal
style.Font.Bold = True
worksheet.Range("B2").CellStyle = style
workbook.SaveAs("Style.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;

Copyright © 2001 - 2019 Syncfusion Inc. 176


XlsIO Working with Paragraph

IWorkbook workbook = application.Workbooks.Create(1);


IWorksheet worksheet = workbook.Worksheets[0];
//Initialize the DataTable
DataTable table = SampleDataTable();
//Import DataTable to the worksheet.
worksheet.ImportDataTable(table, true, 1, 1);
workbook.SaveAs("ImportFromDT.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Initialize the DataTable
Dim table As DataTable = sampleDataTable()
'Import DataTable to the worksheet
worksheet.ImportDataTable(table, True, 1, 1)
workbook.SaveAs("ImportFromDT.xlsx")
End Using

UWP

C#
IWorksheet sheet = workbook.Worksheets[0];
//Formula calculation is enabled for the sheet
sheet.EnableSheetCalculations();

VB.NET
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Formula calculation is enabled for the sheet
sheet.EnableSheetCalculations()

UWP

C#
//Applying conditional formatting to "A1"
IConditionalFormats condition = worksheet.Range["A1"].ConditionalFormats;
IConditionalFormat condition1 = condition.AddCondition();

VB.NET
'Applying conditional formatting to "A1"
Dim condition As IConditionalFormats =
worksheet.Range("A1").ConditionalFormats
Dim condition1 As IConditionalFormat = condition.AddCondition()

Copyright © 2001 - 2019 Syncfusion Inc. 177


XlsIO Working with Paragraph

UWP

C#
//Data validation for text length
IDataValidation validation = sheet.Range["A3"].DataValidation;
validation.AllowType = ExcelDataType.TextLength;
//Text length should be lesser than 5 characters
validation.CompareOperator = ExcelDataValidationComparisonOperator.Between;
validation.FirstFormula = "0";
validation.SecondFormula = "5";

VB.NET
'Data validation for text length
Dim validation As IDataValidation = sheet.Range("A3").DataValidation
validation.AllowType = ExcelDataType.TextLength
'Text length should be lesser than 5 characters
validation.CompareOperator = ExcelDataValidationComparisonOperator.Between
validation.FirstFormula = "0"
validation.SecondFormula = "5"

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet sheet = workbook.Worksheets[0];
//Create a Chart
IChartShape chart = sheet.Charts.Add();
//Set Chart Type
chart.ChartType = ExcelChartType.Column_Clustered;
//Set data range in the worksheet
chart.DataRange = sheet.Range["A1:E5"];
workbook.SaveAs("Chart.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Create a Chart

Copyright © 2001 - 2019 Syncfusion Inc. 178


XlsIO Working with Paragraph

Dim chart As IChartShape = sheet.Charts.Add()


'Set Chart Type
chart.ChartType = ExcelChartType.Column_Clustered
'Set data range in the worksheet
chart.DataRange = sheet.Range("A1:E5")
workbook.SaveAs("Chart.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
ExcelEngine excelEngine = new ExcelEngine();
IWorkbook workbook = excelEngine.Excel.Workbooks.Open("Sample.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
//Create Template Marker Processor
ITemplateMarkersProcessor marker =
workbook.CreateTemplateMarkersProcessor();
//Insert Array Horizontally
string[] names = new string[] { "Mickey", "Donald", "Tom", "Jerry" };
string[] descriptions = new string[] { "Mouse", "Duck", "Cat", "Mouse" };
//Add collections to the marker variables where the name should match with
input template
marker.AddVariable("Names", names);
marker.AddVariable("Descriptions", descriptions);
//Process the markers in the template
marker.ApplyMarkers();
workbook.Version = ExcelVersion.Excel2013;
workbook.SaveAs("TemplateMarker.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim workbook As IWorkbook = excelEngine.Excel.Workbooks.Open("Sample.xlsx")
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Create Template Marker Processor
Dim marker As ITemplateMarkersProcessor =
workbook.CreateTemplateMarkersProcessor()
'Insert Array Horizontally
Dim names As String() = New String() {"Mickey", "Donald", "Tom", "Jerry"}
Dim descriptions As String() = New String() {"Mouse", "Duck", "Cat",
"Mouse"}
'Add collections to the marker variables where the name should match with
input template
marker.AddVariable("Names", names)
marker.AddVariable("Descriptions", descriptions)
'Process the markers in the template
marker.ApplyMarkers()
workbook.Version = ExcelVersion.Excel2013
workbook.SaveAs("TemplateMarker.xlsx")
End Using

Copyright © 2001 - 2019 Syncfusion Inc. 179


XlsIO Working with Paragraph

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Create table with the data in given range
IListObject table = worksheet.ListObjects.Create("Table1",
worksheet["A1:C8"]);
string fileName = "Output.xlsx";
workbook.SaveAs(fileName);
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Create table with the data in given range
Dim table As IListObject = worksheet.ListObjects.Create("Table1",
worksheet("A1:C8"))
Dim fileName As String = "Output.xlsx"
workbook.SaveAs(fileName)
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Adding a picture
IPictureShape shape = worksheet.Pictures.AddPicture(1, 1, "Image.png");
workbook.SaveAs("AddingImage.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()

Copyright © 2001 - 2019 Syncfusion Inc. 180


XlsIO Working with Paragraph

Dim application As IApplication = excelEngine.Excel


application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Adding a picture
Dim shape As IPictureShape = worksheet.Pictures.AddPicture(1, 1,
"Image.png")
workbook.SaveAs("AddingImage.xlsx")
End Using

UWP

C#
//Create Pivot cache with the given data range
IPivotCache cache = workbook.PivotCaches.Add(worksheet["A1:H50"]);

VB.NET
'Create Pivot cache with the given data range
Dim cache As IPivotCache = workbook.PivotCaches.Add(worksheet("A1:H50"))

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("PivotTable.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
IPivotTable pivotTable = worksheet.PivotTables[0];
//Adding a chart to workbook
IChart pivotChart = workbook.Charts.Add();
//Set PivotTable as PivotSource to the chart
pivotChart.PivotSource = pivotTable;
//Set PivotChart type
pivotChart.PivotChartType = ExcelChartType.Column_Clustered;
workbook.SaveAs("PivotChart.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = ExcelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("PivotTable.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
Dim pivotTable As IPivotTable = worksheet.PivotTables(0)
'Adding a chart to workbook

Copyright © 2001 - 2019 Syncfusion Inc. 181


XlsIO Working with Paragraph

Dim pivotChart As IChart = workbook.Charts.Add()


'Set PivotTable as PivotSource to the chart
pivotChart.PivotSource = pivotTable
'Set PivotChart type
pivotChart.PivotChartType = ExcelChartType.Column_Clustered
workbook.SaveAs("PivotChart.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
//Encrypt the workbook with password
workbook.PasswordToOpen = "password";
//Set the password to modify the workbook
workbook.SetWriteProtectionPassword("modify_password");
//Set the workbook as read-only
workbook.ReadOnlyRecommended = true;
workbook.SaveAs("Encrypt.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
'Encrypt the workbook with password
workbook.PasswordToOpen = "password"
'Set the password to modify the workbook
workbook.SetWriteProtectionPassword("modify_password")
'Set the workbook as read-only
workbook.ReadOnlyRecommended = True
workbook.SaveAs("Encrypt.xlsx")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
//Creates a new Text Box

Copyright © 2001 - 2019 Syncfusion Inc. 182


XlsIO Working with Paragraph

ITextBoxShape textbox = sheet.TextBoxes.AddTextBox(2, 2, 30, 200);


textbox.Text = "Text Box 1";
textbox = sheet.TextBoxes.AddTextBox(6, 2, 30, 200);
textbox.Text = "Text Box 2";
//Reads a Text Box
ITextBoxShape shape1 = sheet.TextBoxes[0];
shape1.Text = "TextBox";
//Format the control
shape1.Fill.ForeColor = Color.Gold;
shape1.Fill.BackColor = Color.Black;
shape1.Fill.Pattern = ExcelGradientPattern.Pat_90_Percent;
//Remove a Text Box
ITextBoxShape shape2 = sheet.TextBoxes[1];
shape2.Remove();
workbook.SaveAs("Textbox.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Creates a new Text Box
Dim textbox As ITextBoxShape = sheet.TextBoxes.AddTextBox(2, 2, 30, 200)
textbox.Text = "Text Box 1"
textbox = sheet.TextBoxes.AddTextBox(6, 2, 30, 200)
textbox.Text = "Text Box 2"
'Reads a Text Box
Dim shape1 As ITextBoxShape = sheet.TextBoxes(0)
shape1.Text = "TextBox"
'Format the control
shape1.Fill.ForeColor = Color.Gold
shape1.Fill.BackColor = Color.Black
shape1.Fill.Pattern = ExcelGradientPattern.Pat_90_Percent
'Remove a Text Box
Dim shape2 As ITextBoxShape = sheet.TextBoxes(1)
shape2.Remove()
workbook.SaveAs("Textbox.xlsx")
End Using

UWP

C#
//Adding Document to the workbook
IVbaProject project = workbook.VbaProject;
IVbaModule module = project.Modules.Add("Document", VbaModuleType.Document);

VB.NET
//Adding Document to the workbook
Dim project As IVbaProject = workbook.VbaProject

Copyright © 2001 - 2019 Syncfusion Inc. 183


XlsIO Working with Paragraph

Dim [module] As IVbaModule = project.Modules.Add("Document ", VbaModuleType.


Document)

UWP

C#
using(ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
//Open the Excel document to Convert
ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
//Initialize PDF document
PdfDocument pdfDocument = new PdfDocument();
//Convert Excel document into PDF document
pdfDocument = converter.Convert();
//Save the PDF file
pdfDocument.Save("ExcelToPDF.pdf");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
'Open the Excel document to convert
Dim converter As ExcelToPdfConverter = New ExcelToPdfConverter(workbook)
'Initialize the PDF document
Dim pdfDocument As PdfDocument = New PdfDocument()
'Convert Excel document into PDF document
pdfDocument = converter.Convert()
'Save the PDF file
pdfDocument.Save("ExcelToPDF.pdf")
End Using

UWP

C#
using(ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
//Open the Excel document to Convert
ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);

Copyright © 2001 - 2019 Syncfusion Inc. 184


XlsIO Working with Paragraph

//Initialize Excel to PDF converter settings


ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();
// Set the conformance for PDF/A-1b conversion
settings.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1B;
//Convert Excel document into PDF document
PdfDocument pdfDocument = converter.Convert(settings);
//Save the PDF file
pdfDocument.Save("ExcelToPDF.pdf");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
'Open the Excel document to convert
Dim converter As ExcelToPdfConverter = New ExcelToPdfConverter(workbook)
'Initialize Excel to PDF converter settings
Dim settings As ExcelToPdfConverterSettings = New
ExcelToPdfConverterSettings()
'Set the conformance for PDF/A-1b conversion
settings.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1B
'Convert Excel document into PDF document
Dim pdfDocument As PdfDocument = converter.Convert(settings)
'Save the PDF file
pdfDocument.Save("ExcelToPDF.pdf")
End Using

UWP

C#
// Convert as bitmap
Image image = sheet.ConvertToImage(1, 1, 10, 20);
image.Save("Sample.png", ImageFormat.Png);

VB.NET
'Convert as bitmap
Dim image As Image = sheet.ConvertToImage(1, 1, 10, 20)
image.Save("Sample.png", ImageFormat.Png)

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;

Copyright © 2001 - 2019 Syncfusion Inc. 185


XlsIO Working with Paragraph

application.DefaultVersion = ExcelVersion.Excel2013;
application.ChartToImageConverter = new ChartToImageConverter();
application.ChartToImageConverter.ScalingMode = ScalingMode.Best;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
IChart chart = worksheet.Charts[0];
//Creating the memory stream for chart image
MemoryStream stream = new MemoryStream();
//Saving the chart as image
chart.SaveAsImage(stream);
Image image = Image.FromStream(stream);
//Saving image stream to file
image.Save("Output.png");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim ChartToImageConverter As chartToImageConverter = New
ChartToImageConverter()
application.ChartToImageConverter = ChartToImageConverter
application.ChartToImageConverter.ScalingMode = ScalingMode.Best
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
Dim chart As IChart = worksheet.Charts(0)
'Creating the memory stream for chart image
Dim stream As New MemoryStream()
'Saving the chart as image
chart.SaveAsImage(stream)
Dim image As Image = Image.FromStream(stream)
'Saving image stream to file
image.Save("Output.png")
End Using

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
worksheet.Range["A1"].Text = "Month";
worksheet.Range["B1"].Text = "Sales";
worksheet.Range["A5"].Text = "Total";
worksheet.Range["A2"].Text = "January";
worksheet.Range["A3"].Text = "February";
worksheet.AutofitColumn(1);
worksheet.Range["B2"].Number = 68878;
worksheet.Range["B3"].Number = 71550;

Copyright © 2001 - 2019 Syncfusion Inc. 186


XlsIO Working with Paragraph

worksheet.Range["B5"].Formula = "SUM(B2:B4)";
//Comments
IComment comment = worksheet.Range["B5"].AddComment();
comment.RichText.Text = "This cell has formula.";
IRichTextString richText = comment.RichText;
IFont blueFont = workbook.CreateFont();
blueFont.Color = ExcelKnownColors.Blue;
richText.SetFont(0, 13, blueFont);
IFont redFont = workbook.CreateFont();
redFont.Color = ExcelKnownColors.Red;
richText.SetFont(14, 20, redFont);
//Formatting
IStyle style = workbook.Styles.Add("Style1");
style.Color = Color.DarkBlue;
style.Font.Color = ExcelKnownColors.WhiteCustom;
worksheet.Range["A1:B1"].CellStyleName = "Style1";
worksheet.Range["A5:B5"].CellStyleName = "Style1";
//Save in ODS format
workbook.SaveAs("Output.ods");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
worksheet.Range("A1").Text = "Month"
worksheet.Range("B1").Text = "Sales"
worksheet.Range("A5").Text = "Total"
worksheet.Range("A2").Text = "January"
worksheet.Range("A3").Text = "February"
worksheet.AutofitColumn(1)
worksheet.Range("B2").Number = 68878
worksheet.Range("B3").Number = 71550
worksheet.Range("B5").Formula = "SUM(B2:B4)"
'Comments
Dim comment As IComment = worksheet.Range("B5").AddComment()
comment.RichText.Text = "This cell has formula."
Dim richText As IRichTextString = comment.RichText
Dim blueFont As IFont = workbook.CreateFont()
blueFont.Color = ExcelKnownColors.Blue
richText.SetFont(0, 13, blueFont)
Dim redFont As IFont = workbook.CreateFont()
redFont.Color = ExcelKnownColors.Red
richText.SetFont(14, 20, redFont)
'Formatting
Dim style As IStyle = workbook.Styles.Add("Style1")
style.Color = Color.DarkBlue
style.Font.Color = ExcelKnownColors.WhiteCustom
worksheet.Range("A1:B1").CellStyleName = "Style1"
worksheet.Range("A5:B5").CellStyleName = "Style1"
'Save in ODS format
workbook.SaveAs("Output.ods")
End Using

Copyright © 2001 - 2019 Syncfusion Inc. 187


XlsIO Working with Paragraph

UWP

C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Adding CustomXmlData to Workbook
ICustomXmlPart customXmlPart = workbook.CustomXmlparts.Add("SD10003");
//Add XmlData to CustomXmlPart
byte[] xmlData = File.ReadAllBytes("Test.xml");
customXmlPart.Data = xmlData;
workbook.SaveAs("CustomXml.xlsx");
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Adding CustomXmlData to Workbook
Dim customXmlPart As ICustomXmlPart = workbook.CustomXmlparts.Add("SD10003")
'Add XmlData to CustomXmlPart
Dim xmlData() As Byte = File.ReadAllBytes("Test.xml")
customXmlPart.Data = xmlData
workbook.SaveAs("CustomXml.xlsx")
End Using

UWP

C#
int lastRow = sheet.UsedRange.LastRow;
for(int i=0;i<lastRow;i++)
{
//codes
}
//Do not use like below.
for(int i = 0;i<sheet.UsedRange.LastRow;i++)
{
//codes
}

VB.NET
Dim lastRow As Integer = sheet.UsedRange.LastRow

Copyright © 2001 - 2019 Syncfusion Inc. 188


XlsIO Working with Paragraph

For i As Integer = 0 To lastRow - 1


'codes
Next
'Do not use like below.
For i As Integer = 0 To sheet.UsedRange.LastRow - 1
'codes
Next

Range Access
Use IMigrantRange instead of IRange to optimize performance while dealing with large data.
The IMigrantRange interface can be used to access and manipulate worksheet range. This is an optimal
method of writing values with better memory performance.
The following code example illustrates how the IMigrantRange is accessed.
C#
IMigrantRange migrantRange = workbook.Worksheets[0].MigrantRange;
// Writing Data.
for (int row = 1; row <= rowCount; row++)
{
for (int column = 1; column <= colCount; column++)
{
// Writing values.
migrantRange.ResetRowColumn(row, column);
// Setting value of this migrant range which is similar to IRange object.
migrantRange.Value = "Syncfusion";
}
}

VB.NET
'Writing Data.
Dim row As Integer
Dim migrantRange As IMigrantRange = workbook.Worksheets(0).MigrantRange
For row = 1 To rowCount Step row + 1
Dim column As Integer
For column = 1 To colCount Step column + 1
'Writing values.
migrantRange.ResetRowColumn(row, column)
' Setting value of this migrant range which is similar to IRange object.
migrantRange.Value = "Syncfusion"
Next
Next

IMigrantRange provides us a SetValue method in which different value for the range can be assigned.
Following code snippet illustrates regarding this.
C#
ExcelEngine excelEngine = new ExcelEngine();
excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = excelEngine.Excel.Workbooks.Create();
IWorksheet sheet = workbook.Worksheets[0];
IMigrantRange migrantRange = workbook.Worksheets[0].MigrantRange;

Copyright © 2001 - 2019 Syncfusion Inc. 189


XlsIO Working with Paragraph

// Writing values.
migrantRange.ResetRowColumn(1, 1);
//Setting boolean value
migrantRange.SetValue(true);
migrantRange.ResetRowColumn(1, 2);
//Setting DateTime value
migrantRange.SetValue(DateTime.Now);
migrantRange.ResetRowColumn(1, 3);
//Setting double value
migrantRange.SetValue(5.5);
migrantRange.ResetRowColumn(1, 4);
//Setting int value
migrantRange.SetValue(5);
migrantRange.ResetRowColumn(1, 5);
//Setting string value
migrantRange.SetValue("Syncfusion");
workbook.Version = ExcelVersion.Excel2013;
workbook.SaveAs("MigrantRange.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = excelEngine.Excel.Workbooks.Create()
Dim sheet As IWorksheet = workbook.Worksheets(0)
Dim migrantRange As IMigrantRange = workbook.Worksheets(0).MigrantRange
' Writing values.
migrantRange.ResetRowColumn(1, 1)
'Setting boolean value
migrantRange.SetValue(True)
migrantRange.ResetRowColumn(1, 2)
'Setting DateTime value
migrantRange.SetValue(DateTime.Now)
migrantRange.ResetRowColumn(1, 3)
'Setting double value
migrantRange.SetValue(5.5)
migrantRange.ResetRowColumn(1, 4)
'Setting int value
migrantRange.SetValue(5)
migrantRange.ResetRowColumn(1, 5)
'Setting string value
migrantRange.SetValue("Syncfusion")
workbook.Version = ExcelVersion.Excel2013
workbook.SaveAs("MigrantRange.xlsx")
workbook.Close()
excelEngine.Dispose()

Styles
Use global styles, rather than using different cell styles for each cell/range. See Applying global styles.
Use Begin and End call while using more than one global style for a worksheet.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 190


XlsIO Working with Paragraph

//Defining body style


IStyle bodyStyle = workbook.Styles.Add("BodyStyle");
bodyStyle.BeginUpdate();
bodyStyle.Color = Color.FromArgb(239, 243, 247);
bodyStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle =
ExcelLineStyle.Thin;
bodyStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle =
ExcelLineStyle.Thin;
bodyStyle.EndUpdate();

VB.NET
'Defining body style
Dim bodyStyle As IStyle = workbook.Styles.Add("BodyStyle")
bodyStyle.BeginUpdate()
bodyStyle.Color = Color.FromArgb(239, 243, 247)
bodyStyle.Borders(ExcelBordersIndex.EdgeLeft).LineStyle =
ExcelLineStyle.Thin
bodyStyle.Borders(ExcelBordersIndex.EdgeRight).LineStyle =
ExcelLineStyle.Thin
bodyStyle.EndUpdate()

AutoFit
Minimize AutoFit manipulations which reduces the time consumption.
Importing DataTable
ImportDataTable overload method which has ImportOnSave argument allows you to import data with
less memory consumption along with improved method performance by serializing the data directly on
save method. This option is preferred for larger data that need to be imported in short time.
C#
DataTable table = Worksheet.ExportDataTable(1, 1,
Worksheet.UsedRange.LastRow, Worksheet.UsedRange.LastColumn,
ExcelExportDataTableOptions.DetectColumnTypes);
//Enable ImportOnSave option along with column header.
workbook.Worksheets[0].ImportDataTable(table, 1, 1, true, true);
workbook.Version = ExcelVersion.Excel2013;
workbook.SaveAs("Output.xlsx");

VB.NET
Dim table As DataTable = Worksheet.ExportDataTable(1, 1,
Worksheet.UsedRange.LastRow, Worksheet.UsedRange.LastColumn,
ExcelExportDataTableOptions.DetectColumnTypes)
'Enable ImportOnSave option along with column header.
workbook.Worksheets(0).ImportDataTable(table, 1, 1, True, True)
workbook.Version = ExcelVersion.Excel2013
workbook.SaveAs("Output.xlsx")

Limitations

 Cannot modify data dynamically

Copyright © 2001 - 2019 Syncfusion Inc. 191


XlsIO Known Exceptions Details

 Styles cannot be applied


 Table style cannot be applied
 Existing sheet data will be lost

Data Validation
Use of BeginUpdate and EndUpdate methods for large blocks of Data Validation greatly improves the
performance.
C#
// List data validation for entire column
IDataValidation validation = sheet.Range["A3"].EntireColumn.DataValidation;
validation.BeginUpdate();
validation.DataRange = sheet.Range["D1:D56"];
validation.IsEmptyCellAllowed = true;
validation.IsListInFormula = false;
validation.EndUpdate();

VB.NET
' List data validation for entire column
Dim validation As IDataValidation =
sheet.Range("A3").EntireColumn.DataValidation
validation.BeginUpdate()
validation.DataRange = sheet.Range("D1:D56")
validation.IsEmptyCellAllowed = True
validation.IsListInFormula = False
validation.EndUpdate()

Known Exceptions Details


The list of known exceptions thrown in Essential XlsIO is listed below.
ApplicationException
Class Message Reason
"Workbook was not created from
file." + " That is why workbook file
Workbook The file name cannot be empty
not specified." + " You must use
SaveAs method instead."
"Can't deselect all worksheets." Can't deselect all worksheets
The value of current mso index
"Can't find data for MSODrawing" cannot greater than array drawings
count
Worksheet "Sheet is already protected, before The property is true the sheet is
use unprotect method" already protected
The condition is false you cannot
"You cannot use this command on
use this command on protected
a protected sheet
sheet

Copyright © 2001 - 2019 Syncfusion Inc. 192


XlsIO Known Exceptions Details

ArgumentException
Class Message Reason
Valid filename of the image must
Pictures string cannot be empty.
be provided.
From center style support only var1 From center style support only var1
or var2 or var2
strName cannot be null or empty. String cannot be empty
strShapeName - string cannot be
String cannot be empty
empty.
The rotation value should be The rotation value should be
between -3600 and 3600 between -3600 and 3600
Name of the UserPicture cannot be
Name cannot be null or empty
empty.
Path of the UserPicture cannot be
Path cannot be null or empty
null or empty.
Path of the UserTexture cannot be
Path cannot be null or empty
empty.

Shape Valid name is not found for the


Shape name cannot be null.
shape.
TextureHorizontalScale must be >=
The specified value is out of range
21475.
 The specified value is out of
TextureOffsetX must be >= 169056.
range
 The specified value is out of
TextureOffsetY must be >= 169056.
range
 The specified value is out of TextureVerticalScale must be >=
range 21475.
This method supports only preset Custom gradient texture does not
textured support.
The TransparencyFrom on shape
TransparencyColor should not be less than 0 and
greater than 1.
The value of the string index 0 is
TextBox "Reference is not valid equal to "=" the reference is not
valid

Copyright © 2001 - 2019 Syncfusion Inc. 193


XlsIO Known Exceptions Details

"Can't refer to external


Cannot refer to external workbook
worksheets"
"FileName cannot be empty." The file name cannot be empty
"fileName" String cannot be empty
"name" String cannot be empty
"Names array must contain at least Names array must contain at least
one name." one name
"separator" String cannot be empty
Workbook
"strFileName - string cannot be
String cannot be empty
empty."
"strName - string cannot be empty" String cannot be empty
"strSheetName" String cannot be empty
"Workbook is protected and Workbook is protected and
password wasn't specified." password wasn't specified
"Contains invalid characters Contains invalid characters
"FileName cannot be empty. The file name cannot be empty
"arrDataColumns can't be empty" String cannot be empty
"Cannot sets formula value in cell Cannot sets formula value in cell
that doesn't contain formula" that doesn't contain formula
Cannot insert column given
"Can't insert column"
condition is false
Cannot insert row given condition
"Can't insert row"
is true
The array extend formats count is
"cellFormat" not less than cell format index
Worksheet value
The XF index value is not equal to
"defaultStyle"
minimum value of the integer
"Each range argument should Each range argument should
contain a single cell" contain a single cell
"FileName cannot be empty." File name cannot be empty
"Image Path doesn't exist" Image path does not exist
"Ranges do not fit each other" The Ranges do not fit each other
"separator" String cannot be null or empty

Copyright © 2001 - 2019 Syncfusion Inc. 194


XlsIO Known Exceptions Details

"strName - string cannot be


String cannot be empty
empty."
"Workbook at least must contains Workbook at least must contain
one worksheet. You cannot remove one worksheet. You cannot remove
last worksheet.", "sheet" last worksheet
"Workbook must contains at least Workbook must contain at least
one worksheet. You cannot remove one worksheet. You cannot remove
last worksheet.", "sheet" last worksheet
The column index is not less than 0
"Invalid column index.
and greater than 0x3fff
The row index is not less than 0 and
"Invalid row index.
greater than 0xfffff
"separator String cannot be empty
Sheet Name is InValid Sheet Name is InValid

ArgumentNullException
Class Message Reason
"Name can't be NULL." Name can't be NULL
"separator" The string cannot be empty
Workbook
"styleIndexes" The style index is not equal to null
"password String cannot be empty
The condition property is not null
"Conditions" and CFExRecords property is not
equal to null
The column index value is not equal
"firstColumn" to 0 and greater than book
Worksheet maximum column count
"password" The string cannot be empty
"separator" String cannot be empty
"dataSource String cannot be empty

ArgumentOutOfRangeException
Class Message Reason
Parts array must have only three The header/footer string should
PageSetup
elements. have 3 parts.

Copyright © 2001 - 2019 Syncfusion Inc. 195


XlsIO Known Exceptions Details

The string is too long. Reduce the The header/footer value exceeds
number of characters used. the characters limit.
Zoom value must be between 10 The zoom value in page setup
and 400 percent. should me within the given limit.
The BottomRowOffset should not
BottomRowOffset
be less than 0.
The Height should not be less than
Height
0.
The column should not be less than
iColumn1 1 and greater than maximum
column count.
The column should not be less than
iColumn2 1 and greater than maximum
column count.
The pixels should not be less than 0
iPixels
and greater than row height.
The iPixels should not be less than
Can't be less than zero.
0.
The row value should not be less
iRow1 than 1 and greater than maximum
Shape row count.
The row value should not less than
iRow2 1 and greater than maximum row
count.
The LeftColumnOffset should not
LeftColumnOffset
be less than 0.
The RightColumnOffset should not
RightColumnOffset
be less than 0.
The ScaleHeight should not be less
scaleHeight
than 0.
The ScaleWidth should not be less
scaleWidth
than 0.
The TopRowOffset should not be
TopRowOffset
less than 0.
The Transparency should not be
Value
less than 0 and greater than 1.

Copyright © 2001 - 2019 Syncfusion Inc. 196


XlsIO Known Exceptions Details

The Weight should not be less than


Weight 0 and greater than maximum line
weight value.
The Width should not be less than
Width
0.
The iPixels should not be less than
iPixels can't be less than zero.
0
The gradient range should not be
Gradient degree is out of range
less than -1 and greater than 1.
The Transparency on shape should
Transparency not be less than 0 and greater than
1.
The TransparencyFrom value on
TransparencyFrom shape should not be less than 0 and
greater than 1.
The TransparencyTo value on
TransparencyTo shape should not be less than 0 and
greater than 1.
The sheet value is not less than 0
"ActiveSheetIndex"
and greater than list object count
"Array cannot contain more than 4 Array cannot contain more than 4
selection records" selection records
"DisplayedTab", "Displayed tab Displayed tab must be greater than
must be greater than zero and less zero and less than Worksheets
than Worksheets count" count
"fileName" The file name cannot be empty
"fullName" String cannot be empty
Workbook
Value cannot be less than 0 and
"index"
greater than Count
"index", "Index cannot be less than
Index cannot be less than 0 and
0 and larger than Palette colors
larger than Palette colors array size
array size."
"index", "Value cannot be less than Value cannot be less than 0 and
0 and greater than Count - 1." greater than Count - 1
The reference index value is not
"iRef" less than or equal to extern sheet
reference and less than 0;

Copyright © 2001 - 2019 Syncfusion Inc. 197


XlsIO Known Exceptions Details

"iReferenceIndex", "Value cannot


Value cannot be less than 0 and
be less than 0 and greater than
greater than arrRefs.Count - 1
arrRefs.Count - 1"
The start index value is not less
"iStartIndex" than stro0 and greater than color
count
The XF index value is not less than
"maxCount"
or equal to 0
"PasswordToOpen", "Password too
Password too long. Maximum
long. Maximum password length is
password length is 15 characters
15 characters."
"referenceIndex", "Value cannot be
Value cannot be less than 0 and
less than 0 and greater than
greater than arrRefs.Count - 1
arrRefs.Count - 1"
"sheetsQuantity", "Quantity of
Quantity of worksheets must be
worksheets must be greater than
greater than zero
zero."
string.Format( "index is {0}, Count Index value is not less than 0 and
is {1}", index, List.Count) not greater than equal to list count
string.Format("index is {0}, Count is Index value is not less than 0 and
{1}", index, count) not greater than equal to list count
"Apostrophe can't be used as first Apostrophe can't be used as first
and/or last character of the and/or last character of the
worksheet's name." worksheet's name
Index value is not less than 0 and
"Chart index"
not greater than equal to list count
The column index value is not
"column index" equal to 0 and greater than book
maximum column count
Worksheet
"Column", "Column index cannot
Column index cannot be larger
be larger then 256 or less then
than 256 or less than one
one"
"columnIndex", "Value cannot be Value cannot be less than 0 and
less than 0 and greater than 255" greater than 255
"count" The count is not less than 0
"drawingItemName" The string name cannot be empty

Copyright © 2001 - 2019 Syncfusion Inc. 198


XlsIO Known Exceptions Details

The column index value is not


"firstColumn" equal to 0 and greater than book
maximum column count
The row index value is not equal to
"firstRow" 0 and greater than book maximum
rows count
"iColumn can't be less than 1" iColumn can't be less than 1
"iColumnCount", "Value cannot be
Value cannot be less 1 and greater
less 1 and greater than max column
than max column index
index"
"iColumnIndex", "Column index is
Column index is out of range
out of range."
"iColumnIndex", "Value cannot be
Value cannot be less 1 and greater
less 1 and greater than max column
than max column index.
index."
"iColumnIndex", "Value cannot be Value cannot be less than 1 and
less than 1 and greater than greater than
m_book.MaxColumnCount." m_book.MaxColumnCount
"iCondFmtPos" The index value is not less than 0
Index value is not less than 0 and
"iCustomPropertyPos"
not greater than equal to list count
"iDValPos" The integer value is not less than 0
"index < 0" The index value is not less than 0
Index value is not less than 0 and
"index"
not greater than equal to list count
"index", "Value cannot be less than Value cannot be less than 0 and
0 and greater than Count - 1." greater than Count - 1
Index value is not less than 0 and
"iNewIndex"
not greater than equal to list count
Index value is not less than 0 and
"iOldIndex"
not greater than equal to list count
The row index value is not equal to
"iRowIndex" 0 and greater than book maximum
rows count
"iRowIndex", "Value cannot be less Value cannot be less 1 and greater
1 and greater than max row index." than max row index

Copyright © 2001 - 2019 Syncfusion Inc. 199


XlsIO Known Exceptions Details

"iRowIndex", "Value cannot be less Value cannot be less than 1 and


than 1 and greater than greater than
m_book.MaxColumnCount." m_book.MaxColumnCount
The shared string index value is not
"iSSTIndex" less than 0 or greater than book
inner shared string count
"iStartIndex" The index value is not less than 0
"Length of the password can't be The password length value is
more than " + greater than default maximum
DEFMAXPASSWORDLEN password length
The index value is not less than or
"maxCount"
equal to 0
The range of the row and column is
"range" not equal to range of the last
column and last row
The row index value is not less than
"rowIndex" 1 and greater than book maximum
count
The standard row height value is
"Standard Row Height"
not less than 0
"Text value cannot be null or
Text value cannot be null or empty
empty"
"Text value cannot be null or Text value cannot be null or empty.
empty. First symbol must be '#'" First symbol must be '#'
"Text value cannot be null or Text value cannot be null or empty.
empty. First symbol of formula First symbol of formula cannot be
cannot be '='" '='
"Value cannot be less 1 and greater Value cannot be less 1 and greater
than max column index." than maximum column index
Given value does not contains
"Value does not valid error string."
dictionary
"Worksheets collection does not Worksheets collection does not
contain specified worksheet." contain specified worksheet
"Zoom", "Zoom must be in range Zoom must be in range from 10 till
from 10 till 400." 400.
strParentItemName The string name cannot be empty

Copyright © 2001 - 2019 Syncfusion Inc. 200


XlsIO Known Exceptions Details

Column value cannot be less than 0 Value cannot be less than 0 and
and greater than 255 greater than 255
End Row Index cannot be greater Value cannot be greater than max
than max row index row index
The column index value is not
firstColumn equal to 0 and greater than book
maximum column count
The row index value is not equal to
firstRow 0 and greater than book maximum
rows count
The password length value is
Length of the password can't be
greater than default maximum
more than password length
password length
Row Index value cannot be less The row index value is not equal to
than 1 and greater than max row 0 and greater than book maximum
index rows count
The standard column width value is
Standard Column Width. not less than 0 and greater than
default maximum column width
Value cannot be less 1 and greater Value cannot be less 1 and greater
than max column index. than max column index
Value cannot be less 1 and greater Value cannot be less 1 and greater
than max row index. than max row index
Value must be 0 to 3 Value must be 0 to 3
string.Format("index is {0}, Count is Index value is not less than 0 and
{1}", index, List.Count) not greater than equal to list count

ExcelWorkbookNotSavedException
Class Message Reason
"Object cannot be disposed." + "
Save workbook or set property
Workbook Save workbook or set property
ThrowNotSavedOnDestroy to false
ThrowNotSavedOnDestroy to false.

FileNotFoundException
Class Message Reason
File represents by current path File represents by current path
Shape
doesn't exist doesn't exist.

Copyright © 2001 - 2019 Syncfusion Inc. 201


XlsIO Known Exceptions Details

"File could not be found. Please


"File could not be found.
verify the file path."
Workbook string.Format("File {0} could not be
The file name is not there in given
found. Please verify the file path.",
file path the exception will throw
filename)

InvalidRangeException
Class Message Reason
The destination array formula not
Worksheet Can't copy to destination range separator the cannot copy to
destination range

NotSupportedException
Class Message Reason
This property can be set only when This property can be set only when
Gradient Style is selected. Gradient Style is selected.
This property supports only if This property supports only if
pattern style is checked pattern style is checked.
This property supports only if This property supports only if
pattern style is checked texture style is checked.
This property support only if This property support only if
defined user texture of picture defined user texture of picture.
"This property supports only if This property supports only if Solid
Checked Solid style." style is checked
"This shape doesn't support fill The m_bSupportOption is false the
Shape properties." fill format not supported
"This shape doesn't support line The m_bSupportOption is false the
properties." line format not supported
The shape is not equal to
HyperLink AutoShape, picture, textbox does
not supported in hyperlink
This property supported only if Supports only Excel gradient
checked preset color type preset.
This property supports only if Supports only Excel gradient
checked one color gradient preset.
This variant doesn't support center The shape object doesn't support
shading style. center shading style.

Copyright © 2001 - 2019 Syncfusion Inc. 202


XlsIO FAQ Section

"Name of worksheet must be Name of worksheet must be


unique in a workbook." unique in a workbook
This property is not supported for
Workbook "Not supported encryption type."
encryption type
"Weak encryption algorithm is not Weak encryption algorithm is not
supported." supported.
Name of worksheet must be Name of worksheet must be
Worksheet
unique in a workbook unique in a workbook

FAQ Section
The frequently asked questions in Essential XlsIO are listed below.
How to open an existing XLSX workbook and save it as XLS?
You can open and save an existing .xlsx file to the .xls file by using XlsIO. The following code snippet
illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
//Open an existing Excel 2013 file.
IWorkbook workbook = excelEngine.Excel.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
//Save it as "Excel 97 to 2003" format.
workbook.Version = ExcelVersion.Excel97to2003;
workbook.SaveAs("Output.xls");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
'Open an existing Excel 2013 file.
Dim workbook As IWorkbook = excelEngine.Excel.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
'Save it as "Excel 97 to 2003" format.
workbook.Version = ExcelVersion.Excel97to2003
workbook.SaveAs("Output.xls")
workbook.Close()
excelEngine.Dispose()

Note: Workbook must be saved in appropriate version, failing in this leads to file corruption.
How to open an Excel file from Stream?
XlsIO provides support for opening a file that is stored as a stream. The following code snippet illustrates
this.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 203


XlsIO FAQ Section

ExcelEngine excelEngine = new ExcelEngine();


IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//Opening a File from a Stream
FileStream fileStream = new FileStream("Sample.xlsx", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
IWorkbook workbook = application.Workbooks.Open(fileStream);
workbook.SaveAs("Output.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
'Opening a File from a Stream
Dim fileStream As New FileStream("Sample.xlsx", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite)
Dim workbook As IWorkbook = application.Workbooks.Open(fileStream)
workbook.SaveAs("Output.xlsx")
workbook.Close()
excelEngine.Dispose()

How to save a file to stream?


XlsIO provides support to save a workbook to a .NET stream. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
//Save the workbook to stream.
FileStream fileStream = new FileStream("Output.xlsx", FileMode.Create,
FileAccess.ReadWrite, FileShare.ReadWrite);
workbook.SaveAs(fileStream);
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
'Save the workbook to stream.
Dim fileStream As New FileStream("Output.xlsx", FileMode.Create,
FileAccess.ReadWrite, FileShare.ReadWrite)
workbook.SaveAs(fileStream)
workbook.Close()
excelEngine.Dispose()

Copyright © 2001 - 2019 Syncfusion Inc. 204


XlsIO FAQ Section

How to create and open Excel Template files by using XlsIO?


Creating Excel Template Files
Excel template files (XLT or XLTX) can be created in XlsIO by saving a file as Template using
ExcelSaveType enumeration. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Save as XLT.
workbook.Version = ExcelVersion.Excel97to2003;
workbook.SaveAs("XLTFile.xlt", ExcelSaveType.SaveAsTemplate);
//Save as XLTX.
workbook.Version = ExcelVersion.Excel2007;
workbook.SaveAs("XLTXFile.xltx", ExcelSaveType.SaveAsTemplate);
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Save as XLT.
workbook.Version = ExcelVersion.Excel97to2003
workbook.SaveAs("XLTFile.xlt", ExcelSaveType.SaveAsTemplate)
'Save as XLTX.
workbook.Version = ExcelVersion.Excel2007
workbook.SaveAs("XLTXFile.xltx", ExcelSaveType.SaveAsTemplate)
workbook.Close()
excelEngine.Dispose()

Opening Excel Template Files


In XlsIO, an Excel template file is opened in the same way, as excel workbook (.xls and .xlsx) is opened.
The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//Open Excel Template.
IWorkbook workbook = application.Workbooks.Open("Sample.xltx",
ExcelOpenType.Automatic);
workbook.SaveAs("Output.xlsx");
workbook.Close();
excelEngine.Dispose();

Copyright © 2001 - 2019 Syncfusion Inc. 205


XlsIO FAQ Section

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
'Open Excel Template.
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xltx",
ExcelOpenType.Automatic)
workbook.SaveAs("Output.xlsx")
workbook.Close()
excelEngine.Dispose()

How to open an Excel 2013 Macro Enabled Template?


You can open and save an Excel 2013 Macro Enabled Template to XLSM (Excel 2013 Macro Enabled
Document) format. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//Open an existing XLTM file.
IWorkbook workbook = application.Workbooks.Open("Sample.xltm",
ExcelOpenType.Automatic);
//Save the file as XLSM.
workbook.SaveAs("Output.xlsm");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
'Open an existing XLTM file.
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xltm",
ExcelOpenType.Automatic)
'Save the file as XLSM.
workbook.SaveAs("Output.xlsm")
workbook.Close()
excelEngine.Dispose()

How to change the grid line color of the Excel sheet?


In Essential XlsIO, you can change the grid line color of the worksheet using GridLineColor property. The
below code snippet illustrate this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//To change the grid line color using ExcelKnownColors
worksheet.GridLineColor = ExcelKnownColors.Blue;

Copyright © 2001 - 2019 Syncfusion Inc. 206


XlsIO FAQ Section

workbook.SaveAs("GridLineColor.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'To change the grid line color using ExcelKnownColors
worksheet.GridLineColor = ExcelKnownColors.Blue
workbook.SaveAs("GridLineColor.xlsx")
workbook.Close()
excelEngine.Dispose()

How to copy and paste the values of the cells that contain only formulas?
You can copy and paste the values of the cell which contain only formula using CopyTo method by
specifying the ExcelCopyRangeOptions as None. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Assigning formula to a cell
worksheet.Range["A3"].Formula="SUM(1+1)";
IRange sourceRange = worksheet.Range["A3"];
IRange destinationRange = worksheet.Range["B1"];
//Copy and paste the values using ExcelCopyRangeOption
sourceRange.CopyTo(destinationRange, ExcelCopyRangeOptions.None);
workbook.SaveAs("Output.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Assigning formula to a cell
worksheet.Range("A3").Formula = "SUM(1+1)"
Dim sourceRange As IRange = worksheet.Range("A3")
Dim destinationRange As IRange = worksheet.Range("B1")
'Copy and paste the values using ExcelCopyRangeOption
sourceRange.CopyTo(destinationRange, ExcelCopyRangeOptions.None)
workbook.SaveAs("Output.xlsx")
workbook.Close()
excelEngine.Dispose()

Copyright © 2001 - 2019 Syncfusion Inc. 207


XlsIO FAQ Section

How to copy a range from one workbook to another?


You can copy the range from source workbook to the destination workbook through CopyTo method.
The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook sourceWorkbook = application.Workbooks.Open("SourceWorkbook.xlsx",
ExcelOpenType.Automatic);
IWorkbook destinationWorkbook =
application.Workbooks.Open("DestinationWorkbook.xlsx",
ExcelOpenType.Automatic);
IWorksheet SourceWorksheet = SourceWorkbook.Worksheets[0];
//The first worksheet object in the worksheets collection in the Destination
Workbook is accessed.
IWorksheet DestinationWorksheet = DestinationWorkbook.Worksheets[0];
//Assigning an object to the range of cells (90 rows) both for source and
destination.
IRange sourceRange = SourceWorksheet.Range[1, 1, 90, 100];
IRange destinationRange = DestinationWorksheet.Range[1, 1, 90, 100];
//Copying (90 rows) from Source to Destination worksheet.
sourceRange.CopyTo(destinationRange);
destinationWorkbook.SaveAs("CopyingRange.xlsx");
destinationWorkbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As ExcelEngine = New ExcelEngine
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013Dim sourceWorkbook As
IWorkbook = application.Workbooks.Open("SourceWorkbook.xlsx",
ExcelOpenType.Automatic)
Dim destinationWorkbook As IWorkbook =
application.Workbooks.Open("DestinationWorkbook.xlsx",
ExcelOpenType.Automatic)
'The first worksheet object in the worksheets collection in the Source
Workbook is accessed.
Dim SourceWorksheet As Syncfusion.XlsIO.IWorksheet =
SourceWorkbook.Worksheets(0)
'The first worksheet object in the worksheets collection in the Destination
Workbook is accessed.
Dim DestinationWorksheet As Syncfusion.XlsIO.IWorksheet =
DestinationWorkbook.Worksheets(0)
'Assigning an object to the range of cells (90 rows) both for source and
destination.
Dim sourceRange As Syncfusion.XlsIO.IRange = SourceWorksheet.Range(1, 1, 90,
100)
Dim destinationRange As Syncfusion.XlsIO.IRange =
DestinationWorksheet.Range(1, 1, 90, 100)
'Copying (90 rows) from Source to Destination worksheet.
sourceRange.CopyTo(destinationRange)
destinationWorkbook.SaveAs("CopyingRange.xlsx")
destinationWorkbook.Close()

Copyright © 2001 - 2019 Syncfusion Inc. 208


XlsIO FAQ Section

excelEngine.Dispose()

How to merge several excel files from more than one workbook to a single file?
You can merge several excel files from more than one work book to a single file. The following code
snippet illustrates this.
C#
//Loads the all template document from Data folder.
string[] files = Directory.GetFiles(@"../../Data/");
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
//Create empty Excel workbook instance with one empty worksheet
IWorkbook workbook = application.Workbooks.Create(1);
//Enumerates all the workbook files from the data folder and clone and merge
it into new workbook.
foreach (string file in files)
{
//Loads the all template document from data folder.
FileStream inputStream = new FileStream(file, FileMode.Open,
FileAccess.Read);
//Opens the template workbook from stream
IWorkbook tempWorkbook = application.Workbooks.Open(inputStream);
//Disposes the stream
inputStream.Dispose();
//Cloning all workbook's worksheets
workbook.Worksheets.AddCopy(tempWorkbook.Worksheets);
}
//removing the first empty worksheet
workbook.Worksheets.Remove(0);
workbook.SaveAs("MergingFiles.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
'Loads the all template document from data folder.
Dim files As String() = Directory.GetFiles("../../Data/")
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
'Create empty Excel workbook instance with one empty worksheet
Dim workbook As IWorkbook = application.Workbooks.Create(1)
'Enumerates all the workbook files from the data folder and clone and merge
it into new workbook.
For Each file As String In files
'Loads the all template document from data folder.
Dim inputStream As New FileStream(file, FileMode.Open, FileAccess.Read)
'Opens the template workbook from stream
Dim tempWorkbook As IWorkbook = application.Workbooks.Open(inputStream)
'Disposes the stream
inputStream.Dispose()
'Cloning all workbook's worksheets
workbook.Worksheets.AddCopy(tempWorkbook.Worksheets)

Copyright © 2001 - 2019 Syncfusion Inc. 209


XlsIO FAQ Section

Next
'removing the first empty worksheet
workbook.Worksheets.Remove(0)
workbook.SaveAs("MergingFiles.xlsx")
workbook.Close()
excelEngine.Dispose()

How to ignore the green error marker in worksheets?


When there exists data that are of different formats, the error marker appears in cells. In XlsIO You can
ignore this by using IgnoreErrorOptions property. The following code snippet illustrate this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Ignore Error Options.
worksheet.Range["B3"].IgnoreErrorOptions = ExcelIgnoreError.All;
workbook.SaveAs("IgnoreGreenError.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Ignore Error Options.
worksheet.Range("B3").IgnoreErrorOptions = ExcelIgnoreError.All
workbook.SaveAs("IgnoreGreenError.xlsx")
workbook.Close()
excelEngine.Dispose()

How to protect certain cells in a worksheet?


All the cells in an Excel worksheet have a Locked property, which determines if the cell will be editable.
When a worksheet is protected, all the cells in the worksheet get locked, by default.
However, there is often a need to protect only certain cells in a worksheet. In this scenario, you need to
protect a worksheet, and set the IsLocked property as false for the cells that need to be made editable.
The following code snippet illustrate this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);

Copyright © 2001 - 2019 Syncfusion Inc. 210


XlsIO FAQ Section

IWorksheet worksheet = workbook.Worksheets[0];


//Sample data
worksheet.Range["A1:K20"].Text = "Locked";
//A1:A10 will not be protected, hence it is editable.
worksheet.Range["A1:A10"].CellStyle.Locked = false;
worksheet.Range["A1:A10"].Text = "UnLocked";
worksheet.Protect("syncfusion", ExcelSheetProtection.All);
workbook.SaveAs("ProtectCells.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Sample data
worksheet.Range("A1:K20").Text = "Locked"
'A1:A10 will not be protected.
worksheet.Range("A1:A10").CellStyle.Locked = False
worksheet.Range("A1:A10").Text = "UnLocked"
worksheet.Protect("syncfusion", ExcelSheetProtection.All)
workbook.SaveAs("ProtectCells.xlsx")
workbook.Close()
excelEngine.Dispose()

Note: Locking/Unlocking cells in an unprotected worksheet has no effect.


How to set a line break inside a cell?
In order to set a line break inside a cell, you have to enable Text Wrapping for the cell, and then break
the text. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Save the line break inside the cell
worksheet.Range["A1"].CellStyle.WrapText = true;
worksheet.Range["A1"].Text = String.Format("Hello\nworld");
workbook.SaveAs("LineBreak.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)

Copyright © 2001 - 2019 Syncfusion Inc. 211


XlsIO FAQ Section

Dim worksheet As IWorksheet = workbook.Worksheets(0)


'Save the line break inside the cell
worksheet.Range("A1").CellStyle.WrapText = True
worksheet.Range("A1").Text = String.Format("Hello" & vbLf & "world")
workbook.SaveAs("LineBreak.xlsx")
workbook.Close()
excelEngine.Dispose()

How to set or format a Header/Footer?


Script commands are used to set header/ footer formatting. The following code snippet illustrate this.
For more information on formatting the string, see Inserting and Formatting Text in Headers and Footers
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Format the header
worksheet.PageSetup.CenterHeader = @"&""Gothic,bold""Center Header Text";
workbook.SaveAs("HeaderFormat.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Format the header
worksheet.PageSetup.CenterHeader = "&""Gothic,bold""Center Header Text"
workbook.SaveAs("HeaderFormat.xlsx")
workbook.Close()
excelEngine.Dispose()

Note: Go to “ View -> Page Layout” option to view the header and footer in Microsoft Excel.
How to set print titles?
Printing Title Rows
XlsIO allows to designate row header to repeat on all pages of a printed workbook using PrintTitleRows
property. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Print Rows 1 to 3 on every printed page.

Copyright © 2001 - 2019 Syncfusion Inc. 212


XlsIO FAQ Section

worksheet.PageSetup.PrintTitleRows = "$A$1:$IV$3";
workbook.SaveAs("TitleRows.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Print Rows 1 to 3 on every printed page.
worksheet.PageSetup.PrintTitleRows = "$A$1:$IV$3"
workbook.SaveAs("TitleRows.xlsx")
workbook.Close()
excelEngine.Dispose()

Printing Title Columns


XlsIO allows to designate column header to repeat on all pages of a printed workbook using
PrintTitleColumns property. The following code illustrates printing Title Columns.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Print Columns 1 to 3 on every printed page.
worksheet.PageSetup.PrintTitleColumns = "$A$1:$C$65536";
workbook.SaveAs("TitleColumns.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Print Columns 1 to 3 on every printed page.
worksheet.PageSetup.PrintTitleColumns = "$A$1:$C$65536"
workbook.SaveAs("TitleColumns.xlsx")
workbook.Close()
excelEngine.Dispose()

For information on Print settings, refer to section Page Setup Settings.

Copyright © 2001 - 2019 Syncfusion Inc. 213


XlsIO FAQ Section

How to unfreeze the rows and columns in XlsIO?


You can unfreeze rows and columns in XlsIO by using the RemovePanes method. The following code
snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Freeze the panes.
worksheet.Range[8, 1].FreezePanes();
//Unfreeze the panes
worksheet.RemovePanes();
workbook.SaveAs("Unfreeze.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Freeze the panes.
worksheet.Range(8, 1).FreezePanes()
'Unfreeze the panes
worksheet.RemovePanes()
workbook.SaveAs("Unfreeze.xlsx")
workbook.Close()
excelEngine.Dispose()

What is the maximum range of Rows and Columns?


XlsIO has support below worksheet size for Excel 97 to 2003, Excel 2007 and later versions.

 Excel 97 to 2003(.xls format) – 65,536 by 256 rows and columns.


 Excel 2007 and Later versions(.xlsx format) – 1,048,576 by 16,384 rows and columns

The above specification is the worksheet size of Excel. For more information, see Excel specifications and
limits
How to use Named Ranges with XlsIO?
A named range can be added to worksheet or workbook based on the required scope, the following
code snippet illustrate this. For more information, see Named Range
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;

Copyright © 2001 - 2019 Syncfusion Inc. 214


XlsIO FAQ Section

IWorkbook workbook = application.Workbooks.Create(1);


IWorksheet worksheet = workbook.Worksheets[0];
//Adding named range to the workbook
IName workBookName = workbook.Names.Add("WorkBookName");
workBookName.RefersToRange = worksheet.Range["I8"];
//Looping through the Named Ranges in a workbook.
foreach (IName workbookName in workbook.Names)
{
MessageBox.Show(workbookName.Name.ToString());
}
//Adding named range to the worksheet
IName worksheetName = worksheet.Names.Add("WorkSheetName");
worksheetName.RefersToRange = worksheet.Range["J8"];
//Looping through the Named Ranges in a worksheet.
foreach (IName name in worksheet.Names)
{
MessageBox.Show(name.Name.ToString());
}
workbook.SaveAs("NamedRange.Xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Adding named range to the workbook
Dim workBookName__1 As IName = workbook.Names.Add("WorkBookName")
workBookName__1.RefersToRange = worksheet.Range("I8")
'Looping through the Named Ranges in a workbook.
For Each workbookName__2 As IName In workbook.Names
MessageBox.Show(workbookName__2.Name.ToString())
Next
'Adding named range to the worksheet
Dim worksheetName__3 As IName = worksheet.Names.Add("WorkSheetName")
worksheetName__3.RefersToRange = worksheet.Range("J8")
'Looping through the Named Ranges in a worksheet.
For Each worksheetName__4 As IName In worksheet.Names
MessageBox.Show(worksheetName__4.Name.ToString())
Next
workbook.SaveAs("NamedRange.Xlsx")
workbook.Close()
excelEngine.Dispose()

How to add chart labels to scatter points?


The following code illustrates adding chart labels to the scatter points of the chart.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;

Copyright © 2001 - 2019 Syncfusion Inc. 215


XlsIO FAQ Section

IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",


ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Get the chart from the charts collection
IChart chart = worksheet.Charts[0];
//Get the first series from the Series collection
IChartSerie serieOne = chart.Series[0];
//Set the Series name to the Data Labels through Data Points
serieOne.DataPoints[0].DataLabels.IsSeriesName = true;
//Set the Value to the Data Labels through Data Points
serieOne.DataPoints[0].DataLabels.IsValue = true;
workbook.SaveAs("ChartLabels.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Get the chart from the charts collection
Dim chart As IChart = worksheet.Charts(0)
'Get the first series from the Series collection
Dim serieOne As IChartSerie = chart.Series(0)
'Set the Series name to the Data Labels through Data Points
serieOne.DataPoints(0).DataLabels.IsSeriesName = True
'Set the Value to the Data Labels through Data Points
serieOne.DataPoints(0).DataLabels.IsValue = True
workbook.SaveAs("ChartLabels.xlsx")
workbook.Close()
excelEngine.Dispose()

How to create a Chart with a discontinuous range?


The following code example illustrates creating a chart with discontinuous data ranges.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Entering the data for the chart.
worksheet.Range["A1"].Text = "Texas books Unit sales";
worksheet.Range["A1:D1"].Merge();
worksheet.Range["A1"].CellStyle.Font.Bold = true;
worksheet.Range["B2"].Text = "Jan";
worksheet.Range["C2"].Text = "Feb";
worksheet.Range["D2"].Text = "Mar";
worksheet.Range["A3"].Text = "Austin";
worksheet.Range["A4"].Text = "Dallas";
worksheet.Range["A5"].Text = "Houston";
worksheet.Range["A6"].Text = "San Antonio";

Copyright © 2001 - 2019 Syncfusion Inc. 216


XlsIO FAQ Section

worksheet.Range["B3"].Number = 53.75;
worksheet.Range["B4"].Number = 52.85;
worksheet.Range["B5"].Number = 59.77;
worksheet.Range["B6"].Number = 96.15;
worksheet.Range["C3"].Number = 79.79;
worksheet.Range["C4"].Number = 59.22;
worksheet.Range["C5"].Number = 10.09;
worksheet.Range["C6"].Number = 73.02;
worksheet.Range["D3"].Number = 26.72;
worksheet.Range["D4"].Number = 33.71;
worksheet.Range["D5"].Number = 45.81;
worksheet.Range["D6"].Number = 12.17;
worksheet.Range["F1"].Number = 26.72;
worksheet.Range["F2"].Number = 33.71;
worksheet.Range["F3"].Number = 45.81;
worksheet.Range["F4"].Number = 12.17;
//Discontinuous range.
IRanges rangesOne = worksheet.CreateRangesCollection();
rangesOne.Add(worksheet.Range["B3:B6"]);
rangesOne.Add(worksheet.Range["F1:F2"]);
IRanges rangesTwo = worksheet.CreateRangesCollection();
rangesTwo.Add(worksheet.Range["D3:D6"]);
rangesTwo.Add(worksheet.Range["F3:F4"]);
//Adding a New (Embedded chart) to the Worksheet.
IChartShape shape = worksheet.Charts.Add();
shape.PrimaryCategoryAxis.Title = "City";
shape.PrimaryValueAxis.Title = "Sales (in Dollars)";
shape.ChartTitle = "Texas Books Unit Sales";
//Setting the Series Names in a Legend.
IChartSerie serieOne = shape.Series.Add();
serieOne.Name = "Jan";
serieOne.Values = rangesOne;
IChartSerie serieTwo = shape.Series.Add();
serieTwo.Name = "March";
serieTwo.Values = rangesTwo;
//Setting the (Rows & Columns) Property for the Embedded chart.
shape.BottomRow = 40;
shape.TopRow = 10;
shape.LeftColumn = 3;
shape.RightColumn = 15;
workbook.SaveAs("DiscontinuousRange.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Entering the data for the chart.
worksheet.Range("A1").Text = "Texas books Unit sales"
worksheet.Range("A1:D1").Merge()
worksheet.Range("A1").CellStyle.Font.Bold = True
worksheet.Range("B2").Text = "Jan"

Copyright © 2001 - 2019 Syncfusion Inc. 217


XlsIO FAQ Section

worksheet.Range("C2").Text = "Feb"
worksheet.Range("D2").Text = "Mar"
worksheet.Range("A3").Text = "Austin"
worksheet.Range("A4").Text = "Dallas"
worksheet.Range("A5").Text = "Houston"
worksheet.Range("A6").Text = "San Antonio"
worksheet.Range("B3").Number = 53.75
worksheet.Range("B4").Number = 52.85
worksheet.Range("B5").Number = 59.77
worksheet.Range("B6").Number = 96.15
worksheet.Range("C3").Number = 79.79
worksheet.Range("C4").Number = 59.22
worksheet.Range("C5").Number = 10.09
worksheet.Range("C6").Number = 73.02
worksheet.Range("D3").Number = 26.72
worksheet.Range("D4").Number = 33.71
worksheet.Range("D5").Number = 45.81
worksheet.Range("D6").Number = 12.17
worksheet.Range("F1").Number = 26.72
worksheet.Range("F2").Number = 33.71
worksheet.Range("F3").Number = 45.81
worksheet.Range("F4").Number = 12.17
'Discontinuous range.
Dim rangesOne As IRanges = worksheet.CreateRangesCollection()
rangesOne.Add(worksheet.Range("B3:B6"))
rangesOne.Add(worksheet.Range("F1:F2"))
Dim rangesTwo As IRanges = worksheet.CreateRangesCollection()
rangesTwo.Add(worksheet.Range("D3:D6"))
rangesTwo.Add(worksheet.Range("F3:F4"))
'Adding a New (Embedded chart) to the Worksheet.
Dim shape As IChartShape = worksheet.Charts.Add()
shape.PrimaryCategoryAxis.Title = "City"
shape.PrimaryValueAxis.Title = "Sales (in Dollars)"
shape.ChartTitle = "Texas Books Unit Sales"
'Setting the Series Names in a Legend.
Dim serieOne As IChartSerie = shape.Series.Add()
serieOne.Name = "Jan"
serieOne.Values = rangesOne
Dim serieTwo As IChartSerie = shape.Series.Add()
serieTwo.Name = "March"
serieTwo.Values = rangesTwo
'Setting the (Rows & Columns)Property for the Embedded chart.
shape.BottomRow = 40
shape.TopRow = 10
shape.LeftColumn = 3
shape.RightColumn = 15
workbook.SaveAs("DiscontinuousRange.xlsx")
workbook.Close()
excelEngine.Dispose()

How to define discontinuous ranges?


You can define a discontinuous range by adding different ranges to the Range collection. The following
code example illustrates this.
C#

Copyright © 2001 - 2019 Syncfusion Inc. 218


XlsIO FAQ Section

ExcelEngine excelEngine = new ExcelEngine();


IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Create Range collection.
IRanges rangeCollection = worksheet.CreateRangesCollection();
//Add different ranges to the Range collection.
rangeCollection.Add(worksheet.Range["D2:D3"]);
rangeCollection.Add(worksheet.Range["D10:D11"]);
rangeCollection.Text = "Welcome";
workbook.SaveAs("DiscontinuousRange.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Create Range collection.
Dim range As IRanges = worksheet.CreateRangesCollection()
'Add different ranges to the Range collection.
range.Add(worksheet.Range("D2:D3"))
range.Add(worksheet.Range("D10:D11"))
range.Text = "Welcome"
workbook.SaveAs("DiscontinuousRange.xlsx")
workbook.Close()
excelEngine.Dispose()

How to format text within a cell?


In Essential XlsIO, You can use the rich text formatting option to format the text within a cell. The
following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
//Insert Rich Text.
IRange range = worksheet.Range["A1"];
range.Text = "RichText";
IRichTextString richText = range.RichText;
//Formatting first 4 characters.
IFont redFont = workbook.CreateFont();
redFont.Bold = true;
redFont.Italic = true;
redFont.RGBColor = Color.Red;
richText.SetFont(0, 3, redFont);
//Formatting last 4 characters.
IFont blueFont = workbook.CreateFont();

Copyright © 2001 - 2019 Syncfusion Inc. 219


XlsIO FAQ Section

blueFont.Bold = true;
blueFont.Italic = true;
blueFont.RGBColor = Color.Blue;
richText.SetFont(4, 7, blueFont);
workbook.SaveAs("FormattingText.xlsx");
workbook.Close();
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Insert Rich Text.
Dim range As IRange = worksheet.Range("A1")
range.Text = "RichText"
Dim richText As IRichTextString = range.RichText
'Formatting first 4 characters.
Dim redFont As IFont = workbook.CreateFont()
redFont.Bold = True
redFont.Italic = True
redFont.RGBColor = Color.Red
richText.SetFont(0, 3, redFont)
'Formatting last 4 characters.
Dim blueFont As IFont = workbook.CreateFont()
blueFont.Bold = True
blueFont.Italic = True
blueFont.RGBColor = Color.Blue
richText.SetFont(4, 7, blueFont)
workbook.SaveAs("FormattingText.xlsx")
workbook.Close()
excelEngine.Dispose()

How to hide the summary rows and columns using XlsIO?


You can hide the summary rows and columns by using the IsSummaryRowBelow and
IsSummaryColumnRight properties. The following code snippet illustrates this.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic);
IWorksheet worksheet = workbook.Worksheets[0];
//Hide the summary rows at the bottom.
worksheet.PageSetup.IsSummaryRowBelow = false;
//Hide the summary columns to the right.
worksheet.PageSetup.IsSummaryColumnRight = false;
workbook.SaveAs("SuppressRowsColumns.xlsx");
workbook.Close();
excelEngine.Dispose();

Copyright © 2001 - 2019 Syncfusion Inc. 220


XlsIO FAQ Section

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx",
ExcelOpenType.Automatic)
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Hide the summary rows at the bottom.
worksheet.PageSetup.IsSummaryRowBelow = False
'Suppress the summary columns to the right.
worksheet.PageSetup.IsSummaryColumnRight = False
workbook.SaveAs("SuppressRowsColumns.xlsx")
workbook.Close()
excelEngine.Dispose()

How to zip files using the Syncfusion.Compression.Zip namespace?


You can compress the file using Syncfusion.Compression.Zip namespace. The following code illustrate
this.
C#
using Syncfusion.Compression.Zip;
ZipArchive zipArchive = new Syncfusion.Compression.Zip.ZipArchive();
zipArchive.DefaultCompressionLevel =
Syncfusion.Compression.CompressionLevel.Best;
//Add the file you want to zip.
zipArchive.AddFile("SampleFile.cs");
//Zip file name and location.
zipArchive.Save("SyncfusionCompressFileSample.zip");
zipArchive.Close();

VB.NET
Imports Syncfusion.Compression.Zip
Dim zipArchive As ZipArchive = New Syncfusion.Compression.Zip.ZipArchive()
zipArchive.DefaultCompressionLevel =
Syncfusion.Compression.CompressionLevel.Best
'Add the file you want to zip.
zipArchive.AddFile("SampleFile.cs")
'Zip file name and location.
zipArchive.Save("SyncfusionCompressFileSample.zip")
zipArchive.Close()

Tips: You can use CompressionLevel to reduce the size of the file.
For compressing directories, you can make use of the AddDirectory method which adds an empty
directory file to a ZipArchive. If you want to add all the files inside the directory, then you should
manually add these files by using the AddItem method.
The following code snippet illustrate how to add the file from the local drive.
C#
string fileName = @"SampleFile.cs";
ZipArchive zipArchive = new Syncfusion.Compression.Zip.ZipArchive();

Copyright © 2001 - 2019 Syncfusion Inc. 221


XlsIO FAQ Section

zipArchive.DefaultCompressionLevel =CompressionLevel.Best;
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
FileAttributes attributes = File.GetAttributes(fileName);
ZipArchiveItem item = new ZipArchiveItem(zipArchive, "SampleFile.cs",
stream, true, attributes);
zipArchive.AddItem(item);
zipArchive.Save(@"SyncfusionCompressFileSample.zip");
zipArchive.Close();

VB.NET
Dim fileName As String = "SampleFile.cs"
Dim zipArchive As ZipArchive = New Syncfusion.Compression.Zip.ZipArchive()
zipArchive.DefaultCompressionLevel = CompressionLevel.Best
Dim stream As Stream = New FileStream(fileName, FileMode.Open,
FileAccess.Read)
Dim attributes As FileAttributes = File.GetAttributes(fileName)
Dim item As New ZipArchiveItem(zipArchive, "SampleFile.cs", stream, True,
attributes)
zipArchive.AddItem(item)
zipArchive.Save("SyncfusionCompressFileSample.zip")
zipArchive.Close()

How to zip all the files in subfolders using the Syncfusion.Compression.Zip namespace?
You can compress and decompress the files with our Compression library. The following code snippet
illustrates this.
C#
using Syncfusion.Compression.Zip;
class Program
{
private static List<DirectoryInfo> arrOfItems = new List<DirectoryInfo>();
private static ZipArchive zipArchive = new ZipArchive();
private static string folderPath = @"..\..\ZipFiles";
private static void SubFoldersFiles(string path)
{
DirectoryInfo dInfo = new DirectoryInfo(path);
foreach (DirectoryInfo d in dInfo.GetDirectories())
{
SubFoldersFiles(d.FullName);
arrOfItems.Add(d);
}
}
// Zip and save the file.
private static void ZipAndSave()
{
SubFoldersFiles(folderPath);
if (Directory.Exists(folderPath))
{
AddRootFiles();
AddSubFoldersFiles();
// Saving zipped file.
zipArchive.Save(@"..\..\UnzippedFile.zip");
zipArchive.Close();

Copyright © 2001 - 2019 Syncfusion Inc. 222


XlsIO FAQ Section

Console.WriteLine("Files Zipped successfully!");


}
}
private static void AddRootFiles()
{
string fileName = "";
foreach (string rootFiles in Directory.GetFiles(folderPath))
{
//Creating the stream from file
FileStream stream = new FileStream(rootFiles, FileMode.Open,
FileAccess.ReadWrite);
//Getting the File Name alone and ignoring the directory path
fileName = Path.GetFileName(rootFiles);
FileAttributes attribute = File.GetAttributes(rootFiles);
zipArchive.AddItem(fileName, stream, false, attribute);
}
}
private static void AddSubFoldersFiles()
{
foreach (DirectoryInfo dInfo in arrOfItems)
{
FileInfo[] fInfo = dInfo.GetFiles();
string mainDirectoryPath = Path.GetFullPath(folderPath);
foreach (FileInfo file in fInfo)
{
//Get the File name with its current folder and ignoring the Main Directory
string fileName = file.FullName.Replace(mainDirectoryPath, "");
//Read the file stream by its Full name
FileStream stream = new FileStream(file.FullName, FileMode.Open,
FileAccess.ReadWrite);
FileAttributes attributes = File.GetAttributes(file.FullName);
//Add the item to the zip Archive
zipArchive.AddItem(fileName, stream, true, attributes);
}
}
}
//Unzipping the Folder
private static void UnZipFiles()
{
ZipArchive zip = new ZipArchive();
string path = @"..\..\UnZippedFile";
zip.Open(@"..\..\UnzippedFile.zip");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
//Saving the contents of zip file to disk.
for (int i = 0; i < zip.Count; i++)
{
ZipArchiveItem item = zip[i];
string itemName = path + item.ItemName;
//checking whether the item is root file
if (itemName.Contains("/"))
{
itemName = itemName.Replace("/", "\\");
}
//Check whether the Directory is present or not
if (!Directory.Exists(itemName) || itemName.Contains("\\"))
{

Copyright © 2001 - 2019 Syncfusion Inc. 223


XlsIO FAQ Section

int index = itemName.LastIndexOf("\\");


string directoryPath = itemName.Remove(index, itemName.Length - index);
Directory.CreateDirectory(directoryPath);
}
FileStream fileStream = new FileStream(itemName, FileMode.OpenOrCreate,
FileAccess.ReadWrite);
MemoryStream memoryStream = item.DataStream as MemoryStream;
memoryStream.WriteTo(fileStream);
fileStream.Flush();
fileStream.Close();
}
Console.WriteLine("File has been Unzipped");
}
static void Main(string[] args)
{
ZipAndSave();
UnZipFiles();
}
}

VB.NET
Imports Syncfusion.Compression.Zip
Class Program
Private Shared arrOfItems As New List(Of DirectoryInfo)()
Private Shared zipArchive As New ZipArchive()
Private Shared folderPath As String = "..\..\ZipFiles"
Private Shared Sub SubFoldersFiles(path As String)
Dim dInfo As New DirectoryInfo(path)
For Each d As DirectoryInfo In dInfo.GetDirectories()
SubFoldersFiles(d.FullName)
arrOfItems.Add(d)
Next
End Sub
' Zip and save the file.
Private Shared Sub ZipAndSave()
SubFoldersFiles(folderPath)
If Directory.Exists(folderPath) Then
AddRootFiles()
AddSubFoldersFiles()
' Saving zipped file.
zipArchive.Save("..\..\UnzippedFile.zip")
zipArchive.Close()
Console.WriteLine("Files Zipped successfully!")
End If
End Sub
Private Shared Sub AddRootFiles()
Dim fileName As String = ""
For Each rootFiles As String In Directory.GetFiles(folderPath)
'Creating the stream from file
Dim stream As New FileStream(rootFiles, FileMode.Open, FileAccess.ReadWrite)
'Getting the File Name alone and ignoring the directory path
fileName = Path.GetFileName(rootFiles)
Dim attribute As FileAttributes = File.GetAttributes(rootFiles)
zipArchive.AddItem(fileName, stream, False, attribute)
Next

Copyright © 2001 - 2019 Syncfusion Inc. 224


XlsIO FAQ Section

End Sub
Private Shared Sub AddSubFoldersFiles()
For Each dInfo As DirectoryInfo In arrOfItems
Dim fInfo As FileInfo() = dInfo.GetFiles()
Dim mainDirectoryPath As String = Path.GetFullPath(folderPath)
For Each file__1 As FileInfo In fInfo
'Get the File name with its current folder and ignoring the Main Directory
Dim fileName As String = file__1.FullName.Replace(mainDirectoryPath, "")
'Read the file stream by its Full name
Dim stream As New FileStream(file__1.FullName, FileMode.Open,
FileAccess.ReadWrite)
Dim attributes As FileAttributes = File.GetAttributes(file__1.FullName)
'Add the item to the zip Archive
zipArchive.AddItem(fileName, stream, True, attributes)
Next
Next
End Sub
'Unzipping the Folder
Private Shared Sub UnZipFiles()
Dim zip As New ZipArchive()
Dim path As String = "..\..\UnZippedFile"
zip.Open("..\..\UnzippedFile.zip")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
'Saving the contents of zip file to disk.
For i As Integer = 0 To zip.Count - 1
Dim item As ZipArchiveItem = zip(i)
Dim itemName As String = path + item.ItemName
'checking whether the item is root file
If itemName.Contains("/") Then
itemName = itemName.Replace("/", "\")
End If
'Check whether the Directory is present or not
If Not Directory.Exists(itemName) OrElse itemName.Contains("\") Then
Dim index As Integer = itemName.LastIndexOf("\")
Dim directoryPath As String = itemName.Remove(index, itemName.Length -
index)
Directory.CreateDirectory(directoryPath)
End If
Dim fileStream As New FileStream(itemName, FileMode.OpenOrCreate,
FileAccess.ReadWrite)
Dim memoryStream As MemoryStream = TryCast(item.DataStream, MemoryStream)
memoryStream.WriteTo(fileStream)
fileStream.Flush()
fileStream.Close()
Next
Console.WriteLine("File has been Unzipped")
End Sub
Private Shared Sub Main(args As String())
ZipAndSave()
UnZipFiles()
End Sub
End Class

Copyright © 2001 - 2019 Syncfusion Inc. 225


XlsIO FAQ Section

Does Essential XlsIO provide support for Client Profile?


Yes, Essential XlsIO provides support for Client Profile. In order to use Essential XlsIO in an application
(which targeted to Client Profile), the user should include the following assemblies.

 Syncfusion.Core.dll
 Syncfusion.Compression.Base.dll
 Syncfusion.XlsIO.ClientProfile.dll

Note: Syncfusion.Core is no longer needed from 13.2 version onwards.


How to resolve the “File does not contain workbook stream” error in Syncfusion.XlsIO.Base.dll?
XlsIO does not support files generated prior to 97-2003 version. Hence the exception "File does not
contain workbook stream" occurs. This can be checked in prior with the below code snippet.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
//To check whether the file is supported
var isSupported = application.IsSupported("Sample.xls");
excelEngine.Dispose();

VB.NET
Dim excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
'To check whether the file is supported
Dim isSupported = application.IsSupported("Sample.xls")
excelEngine.Dispose()

Note: This method is available from 12.4 version onwards.


How to resolve "Excel cannot open the file 'filename.xlsx' because the file format for the file
extension is not valid. Verify that the file has not been corrupted and that the file extension
matches the format of the file" error?
This error occurs when there is a mismatch between the file format and its extension. The default
workbook creation version in XlsIO is Excel97-2003 (.xls). The application version set to the required
version should match its file format during save, as in the below code.
C#
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
//Set application version
application.DefaultVersion = ExcelVersion.Excel2013;
//Do some manipulation
//Do some manipulation
//Workbook is saved in Excel2013 format
workbook.SaveAs("Sample.xlsx");

VB.NET
Dim excelEngine As New ExcelEngine()

Copyright © 2001 - 2019 Syncfusion Inc. 226


XlsIO FAQ Section

Dim application As IApplication = excelEngine.Excel


'Set application version
application.DefaultVersion = ExcelVersion.Excel2013
'Do some manipulation
'Do some manipulation
'Workbook is saved in Excel2013 format
workbook.SaveAs("Sample.xlsx")

If the application version is ignored, then the workbook version should be set properly during creation
and save.

 To save a workbook in Excel2003 format, set the workbook version to Excel97to2003 and save
the file with extension ‘.xls’ i.e. binary file format.
 To save a workbook in Excel 2007 and above formats, set the workbook version to Excel2007
and above and save the file with extension ‘.xlsx’ i.e. open XML file format.

These are represented in the below code snippet.


C#
workbook.Version = ExcelVersion.Excel97to2003;
workbook.SaveAs("Sample.xls");
workbook.Version = ExcelVersion.Excel2013;
workbook.SaveAs("Sample.xlsx");

VB.NET
workbook.Version = ExcelVersion.Excel97to2003
workbook.SaveAs("Sample.xls")
workbook.Version = ExcelVersion.Excel2013
workbook.SaveAs("Sample.xlsx")

What happens when an Excel file containing uninstalled fonts is converted to PDF/Image?
When the fonts used in particular Excel document are not installed in the machine, the desired
characters will be missing in the PDF/Image conversion. However, XlsIO comes up with a font
substitution method through SubstituteFontEventHandler event. This will enable user to specify
alternate font name to render the characters in the specified alternate font. Otherwise, Microsoft Sans
Serif is used as the default one.
Note: Due to this font substitution, there might be a slight difference with the rendered text in the
generated PDF/Image files during Excel to PDF/Image conversion.
The following code snippet shows how to use font substitution in Excel to PDF conversion using XlsIO.
C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
IWorkbook workbook = application.Workbooks.Open("Sample.xlsx");
//Initializes the SubstituteFont event to perform font substitution during
Excel to PDF conversion

Copyright © 2001 - 2019 Syncfusion Inc. 227


XlsIO FAQ Section

application.SubstituteFont += new
SubstituteFontEventHandler(SubstituteFont);
ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
PdfDocument pdf = converter.Convert();
Stream stream = File.Create("Output.pdf");
pdf.Save(stream);
}
private static void SubstituteFont(object sender, SubstituteFontEventArgs
args)
{
//Sets the alternate font when a specified font is not installed in the
production environment
if (args.OriginalFontName == "Wingdings Regular")
args.AlternateFontName = "Bauhaus 93";
else
args.AlternateFontName = "Times New Roman";
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
Dim workbook As IWorkbook = application.Workbooks.Open("Sample.xlsx")
'Initializes the SubstituteFont event to perform font substitution during
Excel to PDF conversion
AddHandler application.SubstituteFont, AddressOf SubstituteFont
Dim converter As ExcelToPdfConverter = New ExcelToPdfConverter(workbook)
Dim pdf As PdfDocument = converter.Convert()
Dim stream As Stream = File.Create("Output.pdf")
pdf.Save(stream)
End Using
Private Shared Sub SubstituteFont(ByVal sender As Object, ByVal args As
SubstituteFontEventArgs)
'Sets the alternate font when a specified font is not installed in the
production environment.
If args.OriginalFontName = "Wingdings Regular" Then
args.AlternateFontName = "Bauhaus 93"
Else
args.AlternateFontName = "Times New Roman"
End If
End Sub

How to avoid exception when adding worksheets with same name


Microsoft Excel throws exception when adding worksheet with existing worksheet name in a workbook
and XlsIO does the same. But in some case, if you want to add worksheets with the same name using
XlsIO then you can avoid the exception in XlsIO by setting IApplication IgnoreSheetNameException
property as true.
The following code snippet shows how to add two worksheets with same name in a workbook.
C#
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;

Copyright © 2001 - 2019 Syncfusion Inc. 228


XlsIO FAQ Section

application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
//Set IgnoreSheetNameException property as true
application.IgnoreSheetNameException = true;
//Create worksheets with same name
IWorksheet sheet_1 = workbook.Worksheets.Create("Sheet");
IWorksheet sheet_2 = workbook.Worksheets.Create("Sheet");
string fileName = "Output.xlsx";
workbook.SaveAs(fileName);
}

VB.NET
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Excel2013
Dim workbook As IWorkbook = application.Workbooks.Create(1)
’Set IgnoreSheetNameException property as true
application.IgnoreSheetNameException = true
‘Create worksheets with same name
Dim sheet_1 As IWorksheet = workbook.Worksheets.Create("Sheet")
Dim sheet_2 As IWorksheet = workbook.Worksheets.Create("Sheet")
Dim fileName As String = "Output.xlsx"
workbook.SaveAs(fileName)
End Using

UWP

Copyright © 2001 - 2019 Syncfusion Inc. 229

S-ar putea să vă placă și