Documente Academic
Documente Profesional
Documente Cultură
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.
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
Development Environment
In order to develop applications with Syncfusion File Formats platform, you need to have installed
anyone of the Visual Studio version.
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.
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).
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.
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.
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
Web (Essential JS 1)
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.
2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.
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.
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.
4. Confirmation wizard will be displayed. Here you can view and modify the list of platforms that
will be installed.
Note: You can check the Estimated size of the Download and Installation by clicking the Download Size
and Installation Size link.
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.
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.
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).
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.
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.
2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.
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.
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.
1. Double-click the Syncfusion Essential Studio Platform Online Installer setup file. The Setup
Wizard opens and extracts the package automatically.
2. Welcome wizard of the Syncfusion Online Installer will be displayed. Click Next.
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
4. Confirmation wizard will be displayed. Here you can view and modify the list of platforms that
will be installed/uninstalled.
Note: You can check the Estimated size of the Download and Installation by clicking the Download Size
and Installation Size link.
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.
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.
Information: The selected platforms will be installed based on your Syncfusion License (Trial or
Licensed).
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.
Note: The Setup wizard extracts the syncfusionessentialfileformats_(version).exe dialog, displaying the
unzip operation of the package.
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.
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
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.
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.
7. The Completed screen is displayed once the File Formats platform is installed.
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.
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.
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.
8. Setup is uninstalled.
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…
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.
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;
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
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";
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
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;
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#
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;
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
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)
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
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
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
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
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
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;
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
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
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");
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
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
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
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
VB.NET
'Gets the document as stream
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++;
}
}
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
The following code illustrates how to set ligature types for 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 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()
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()
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()
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
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()
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
'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()
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()
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()
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()
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()
}
//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()
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()
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#
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.
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.
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;
---------
//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
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"
‘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);
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
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.
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
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.
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)
‘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;
---------
//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()
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.
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.
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.
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)
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);
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()
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;
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:
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);
//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)
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;
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
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
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
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)
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)
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
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
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);
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()
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\"))
{
//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
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
VB.NET
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
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
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
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");
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);
}
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
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
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.
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.
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.
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";
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.
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);
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);
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");
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);
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()
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#
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
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.
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
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)
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
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
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)
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)
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
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)
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)
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.
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
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
VB.NET
'Create a new document with PDF/A-1b standard.
Dim document As New PdfDocument(PdfConformanceLevel.Pdf_A1B)
'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";
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
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
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
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
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()
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")
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")
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.
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.
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)
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
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
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)
UWP
C#
//Create an instance for PowerPoint
using (IPresentation pptxDoc = Presentation.Create())
{
//Add a blank slide to Presentation
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
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)
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
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
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()
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#$");
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()
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.
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
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
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
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)
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()
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")
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;
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()
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
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
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()
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
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
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
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);
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;
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;
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
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
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;
// 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#
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
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()
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.
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.
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.
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.
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.
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#
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()
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()
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()
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()
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()
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()
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()
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)
Next
'removing the first empty worksheet
workbook.Worksheets.Remove(0)
workbook.SaveAs("MergingFiles.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()
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()
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)
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.
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()
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()
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()
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;
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()
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()
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"
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()
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()
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()
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()
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();
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();
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
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
Syncfusion.Core.dll
Syncfusion.Compression.Base.dll
Syncfusion.XlsIO.ClientProfile.dll
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()
VB.NET
Dim excelEngine As New ExcelEngine()
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.
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
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
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