C#/VB.NET: Convert Excel Cell Values from Text to Number or from Number to Text

Converting cell values from text to number or from number to text is a common task that many people encounter when working with Excel spreadsheets. There are various reasons why you may need to convert data in this way, including mathematical calculations, data analysis, and formatting issues. In this article, we will explore how to convert Excel cell values from text to number or from number to text using C# and VB.NET.

  • Convert Excel Cell Values from Text to Number in C# and VB.NET
  • Convert Excel Cell Values from Number to Text in C# and VB.NET

Installation

To convert Excel cell values, this article uses Spire.XLS for .NET library. You can install Spire.XLS for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.XLS

Alternatively, you can also download the DLL files of Spire.XLS for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Convert Excel Cell Values from Text to Number in C# and VB.NET

Excel might treat numerical values stored as text as text and not recognize them as numbers. Therefore, you may get wrong results when you perform calculations on those values. In such a case, you can convert the numerical values stored as text to number format.

In Spire.XLS, you can use the XlsRange.ConvertToNumber() method to implement this function. The following are the detailed steps:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile(string fileName) method.
  • Get a specific worksheet of the file using the Workbook.Worksheets[int index] property.
  • Get the cell range containing numerical values stored as text using the Worksheet.Range[string name] property.
  • Call the XlsRange.ConvertToNumber() method to convert the values of the cell range to number format.
  • Save the result file to a specific location using the Workbook.SaveToFile(string fileName, ExcelVersion version) method.

C#

using Spire.Xls;

namespace ConvertTextToNumber
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();

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

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

            //Get the cell range containing numerical values stored as text 
            CellRange range = worksheet.Range["B2:I5"];
            //Convert the values of the cell range to number format
            range.ConvertToNumber();

            //Save the result file to a specific location
            workbook.SaveToFile("ConvertTextToNumber.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace ConvertTextToNumber
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()

            'Load an Excel file
            workbook.LoadFromFile("Sample1.xlsx")

            'Get the first worksheet of the file
            Dim worksheet As Worksheet = workbook.Worksheets(0)

            'Get the cell range containing numerical values stored as text 
            Dim range As CellRange = worksheet.Range("B2:I5")
            'Convert the values of the cell range to number format
            range.ConvertToNumber()

            'Save the result file to a specific location
            workbook.SaveToFile("ConvertTextToNumber.xlsx", ExcelVersion.Version2013)
            workbook.Dispose()
        End Sub
    End Class
End Namespace
Convert Excel Cell Values from Text to Number in C# and VB.NET

Convert Excel Cell Values from Number to Text in C# and VB.NET

Converting Excel cell values from number to text can be useful in situations where you need to display numerical data as text, such as when working with account numbers or other identification numbers that should not be subject to mathematical operations.

In Spire.XLS, you can format numerical values as string using the XlsRange.NumberFormat property. The following are the detailed steps:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using the Workbook.LoadFromFile(string fileName) method.
  • Get a specific worksheet of the file using the Workbook.Worksheets[int index] property.
  • Get the cell range containing numerical values stored as text using the Worksheet.Range[string name] property.
  • Format the values of the cell range as string using the XlsRange.NumberFormat property.
  • Save the result file to a specific location using the Workbook.SaveToFile(string fileName, ExcelVersion version) method.

C#

using Spire.Xls;

namespace ConvertNumberToText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();

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

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

            //Get the cell range containing numerical values
            CellRange range = worksheet.Range["A1"];
            //Format the numerical values as string
            range.NumberFormat = "@";

            //Save the result file to a specific location
            workbook.SaveToFile("ConvertNumberToText.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace ConvertNumberToText
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()

            'Load an Excel file
            workbook.LoadFromFile("Sample2.xlsx")

            'Get the first worksheet of the file
            Dim worksheet As Worksheet = workbook.Worksheets(0)

            'Get the cell range containing numerical values
            Dim range As CellRange = worksheet.Range("A1")
            'Format the numerical values as string
            range.NumberFormat = "@"

            'Save the result file to a specific location
            workbook.SaveToFile("ConvertNumberToText.xlsx", ExcelVersion.Version2013)
            workbook.Dispose()
        End Sub
    End Class
End Namespace
Convert Excel Cell Values from Number to Text in C# and VB.NET

See More

Documentation | Forum Support

C#/VB.NET: Change the Font Style in a Word Document

Changing the font style in a Word document is an effective way to customize the appearance of your text. By applying different font styles, you can add visual interest and create a clear hierarchy within your content. This not only improves the overall quality of your document but also enhances the effectiveness of your communication. This article will demonstrate how to programmatically change the font style in a Word document using C# and VB.NET.

The following topics will be discussed:

  • Change the Font Style of a Specific Word in a Word Document
  • Change the Font Style of a Specific Paragraph in a Word Document
  • Change the Font Style of an Entire Word Document

Installation

To change the font style in a Word document, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Change the Font Style of a Specific Word in a Word Document in C# and VB.NET

To change the font style of a specific word in a Word document, you need to search for the word in the document, then change the font style of all its occurrences.

The following steps explain how to change the font style of a specific word in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Search for the word that you want to change the font color for using the Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
  • Iterate through all the occurrences of the searched text.
  • Get the current occurrence as a single text range using the TextSelection.GetAsOneRange() method.
  • Change the font color of the text range using the TextRange.CharacterFormat.TextColor property.
  • Make the text of the text range bold using the TextRange.CharacterFormat.Bold property.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace ChangeFontStyleForWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Search for the text that you want to change the font style for
            TextSelection[] text = document.FindAllString("Information", false, true);

            //Iterate through all the occurrences of the searched text
            foreach (TextSelection seletion in text)
            {
                //Get the current occurrence as a single text range
                TextRange range = seletion.GetAsOneRange();
                //Change the font color of the text range
                range.CharacterFormat.TextColor = Color.Red;
                //Make the text of the text range bold
                range.CharacterFormat.Bold = true;
            }

            //Save the result document
            document.SaveToFile("ChangeFontStyleForSpecificWord.docx", FileFormat.Docx2013);
            document.Dispose();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing

Namespace ChangeFontStyleForWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Search for the text that you want to change the font style for
            Dim text As TextSelection() = document.FindAllString("Information", False, True)

            'Iterate through all the occurrences of the searched text
            For Each seletion As TextSelection In text
                'Get the current occurrence as a single text range
                Dim range As TextRange = seletion.GetAsOneRange()
                'Change the font color of the text range
                range.CharacterFormat.TextColor = Color.Red
                'Make the text of the text range bold
                range.CharacterFormat.Bold = True
            Next

            'Save the result document
            document.SaveToFile("ChangeFontStyleForSpecificWord.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Specific Word in Word Document using C# or VB.NET

Change the Font Style of a Specific Paragraph in a Word Document in C# and VB.NET

You can change the font style of a paragraph by creating a new paragraph style with a specific font style, then applying the new paragraph style to the paragraph you want to modify.

The following steps explain how to change the font style of a specific paragraph in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Get a specific section of the document using the Document.Sections[int index] property.
  • Get a specific paragraph of the section using the Section.Paragraphs[int index] property.
  • Initialize an instance of the ParagraphStyle class to create a new paragraph style.
  • Set the name and font style for the paragraph style.
  • Add the paragraph style to the document using the Document.Styles.Add(IStyle style) method.
  • Apply the paragraph style to the specific paragraph using the Paragraph.ApplyStyle(string styleName) method.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontStyleForParagraph
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Get the first section
            Section section = document.Sections[0];

            //Get the second paragraph
            Paragraph p1 = section.Paragraphs[1];

            //Create a new paragraph style with a specific font style
            ParagraphStyle paragraphStyle = new ParagraphStyle(document);
            paragraphStyle.Name = "ParaStyle";
            paragraphStyle.CharacterFormat.TextColor = Color.ForestGreen;
            paragraphStyle.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;

            //Add the paragraph style to the document
            document.Styles.Add(paragraphStyle);

            //Apply the paragraph style to the second paragraph
            p1.ApplyStyle(paragraphStyle.Name);

            //Save the result document
            document.SaveToFile("ChangeFontStyleForParagraph.docx", FileFormat.Docx2013);
            document.Dispose();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace ChangeFontStyleForParagraph
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Get the first section
            Dim section As Section = document.Sections(0)

            'Get the second paragraph
            Dim p1 As Paragraph = section.Paragraphs(1)

            'Create a new paragraph style with a specific font style
            Dim paragraphStyle As ParagraphStyle = New ParagraphStyle(document)
            paragraphStyle.Name = "ParaStyle"
            paragraphStyle.CharacterFormat.TextColor = Color.ForestGreen
            paragraphStyle.CharacterFormat.UnderlineStyle = UnderlineStyle.[Single]

            'Add the paragraph style to the document
            document.Styles.Add(paragraphStyle)

            'Apply the paragraph style to the second paragraph
            p1.ApplyStyle(paragraphStyle.Name)

            'Save the result document
            document.SaveToFile("ChangeFontStyleForParagraph.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Specific Paragraph in Word Document using C# or VB.NET

Change the Font Style of an Entire Word Document in C# and VB.NET

To change the font style of an entire Word document, you need to create a new paragraph style with a specific font style, then iterate through all the paragraphs in the document and apply the new paragraph style to them.

The following steps explain how to change the font style of an entire Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the ParagraphStyle class to create a new paragraph style.
  • Set the name and font style for the paragraph style.
  • Add the paragraph style to the document using the Document.Styles.Add(IStyle style) method.
  • Iterate through all the sections in the document.
  • Iterate through all the paragraphs in each section.
  • Apply the paragraph style to each paragraph using the Paragraph.ApplyStyle(string styleName) method.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontStyleForDocument
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Create a new paragraph style with specific font style
            ParagraphStyle paraStyle = new ParagraphStyle(document);
            paraStyle.Name = "ParaStyle";
            paraStyle.CharacterFormat.TextColor = Color.CornflowerBlue;
            paraStyle.CharacterFormat.Font = new Font("Arial", 12);
            paraStyle.CharacterFormat.Italic = true;

            //Add the paragraph style to the document
            document.Styles.Add(paraStyle);

            //Iterate through all the sections of the document
            foreach (Section section in document.Sections)
            {
                //Iterate through all the paragraphs of each section
                foreach (Paragraph para in section.Paragraphs)
                {
                    //Apply the paragraph style to each paragraph
                    para.ApplyStyle(paraStyle.Name);
                }
            }

            //Save the result document
            document.SaveToFile("ChangeFontStyleForEntireDocument.docx", FileFormat.Docx2013);
            document.Dispose();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace ChangeFontStyleForDocument
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Create a new paragraph style with specific font style
            Dim paraStyle As ParagraphStyle = New ParagraphStyle(document)
            paraStyle.Name = "ParaStyle"
            paraStyle.CharacterFormat.TextColor = Color.CornflowerBlue
            paraStyle.CharacterFormat.Font = New Font("Arial", 12)
            paraStyle.CharacterFormat.Italic = True

            'Add the paragraph style to the document
            document.Styles.Add(paraStyle)

            'Iterate through all the sections of the document
            For Each section As Section In document.Sections
                'Iterate through all the paragraphs of each section
                For Each para As Paragraph In section.Paragraphs
                    'Apply the paragraph style to each paragraph
                    para.ApplyStyle(paraStyle.Name)
                Next
            Next

            'Save the result document
            document.SaveToFile("ChangeFontStyleForEntireDocument.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Entire Word Document using C# or VB.NET

C#/VB.NET: Convert PDF to PDF/A or PDF/A to PDF

PDF/A is an ISO-standardized version of PDF that ensures the long-term preservation of digital documents. It restricts certain features of the regular PDF format to ensure that documents can be accessed and read in the future, even if the software or hardware used to create them is no longer available. In certain cases, it’s necessary to convert PDF files to PDF/A format for long-term archiving purposes. However, there may also be a need to convert PDF/A files back to regular PDF format if the restrictions and standards of PDF/A are no longer required, or if there is a need to edit or modify the files. This article will explain how to convert PDF files to PDF/A or convert PDF/A files to PDF in C# and VB.NET.

Installation

To achieve conversions between PDF and PDF/A, this article uses Spire.PDF for .NET library. You can install Spire.PDF for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.PDF

Alternatively, you can also download Spire.PDF for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Convert PDF to PDF/A in C# and VB.NET

The Spire.PDF library provides the PdfStandardsConverter class, which is specifically designed for converting PDF files to PDF/A and PDF/X-1a:2001 formats. This class offers a range of methods that enable you to convert regular PDF files to different versions of PDF/A, including:

  • PDF/A-1a
  • PDF/A-1b
  • PDF/A-2a
  • PDF/A-2b
  • PDF/A-3a
  • PDF/A-3b

The following steps describe how to convert a regular PDF file to different versions of PDF/A:

  • Initialize an instance of the PdfStandardsConverter class, and pass the PDF file path to the constructor of the class as a parameter.
  • Convert the PDF file to Pdf/A-1a and save the result file to a specific location using the PdfStandardsConverter.ToPdfA1A(string filePath) method.
  • Convert the PDF file to Pdf/A-1b and save the result file to a specific location using the PdfStandardsConverter.ToPdfA1B(string filePath) method.
  • Convert the PDF file to Pdf/A-2a and save the result file to a specific location using the PdfStandardsConverter.ToPdfA2A(string filePath) method.
  • Convert the PDF file to Pdf/A-2b and save the result file to a specific location using the PdfStandardsConverter.ToPdfA2B(string filePath) method.
  • Convert the PDF file to Pdf/A-3a and save the result file to a specific location using the PdfStandardsConverter.ToPdfA3A(string filePath) method.
  • Convert the PDF file to Pdf/A-3b and save the result file to a specific location using the PdfStandardsConverter.ToPdfA3B(string filePath) method.

C#

using Spire.Pdf.Conversion;

namespace ConvertPdfToPdfA
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input PDF’s file path
            string inputFile = @"C:\Users\Administrator\Desktop\sample.pdf";

            //Specify the output folder
            string outputFolder = @"C:\Users\Administrator\Desktop\Output\";

            //Initialize an instance of the PdfStandardsConverter class, and pass the input PDF’s file path to the constructor of the class as a parameter
            PdfStandardsConverter converter = new PdfStandardsConverter(inputFile);

            //Convert the PDF file to PdfA1A
            converter.ToPdfA1A(outputFolder + "ToPdfA1A.pdf");

            //Convert the PDF file to PdfA1B
            converter.ToPdfA1B(outputFolder + "ToPdfA1B.pdf");

            //Convert the PDF file to PdfA2A
            converter.ToPdfA2A(outputFolder + "ToPdfA2A.pdf");

            //Convert the PDF file to PdfA2B
            converter.ToPdfA2B(outputFolder + "ToPdfA2B.pdf");

            //Convert the PDF file to PdfA3A
            converter.ToPdfA3A(outputFolder + "ToPdfA3A.pdf");

            //Convert the PDF file to PdfA3B
            converter.ToPdfA3B(outputFolder + "ToPdfA3B.pdf");            
        }
    }
}

VB.NET

Imports Spire.Pdf.Conversion

Namespace ConvertPdfToPdfA
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Specify the input PDF’s file path
            Dim inputFile = "C:\Users\Administrator\Desktop\sample.pdf"

            'Specify the output folder
            Dim outputFolder = "C:\Users\Administrator\Desktop\Output\"

            'Initialize an instance of the PdfStandardsConverter class, and pass the input PDF’s file path to the constructor of the class as a parameter
            Dim converter As PdfStandardsConverter = New PdfStandardsConverter(inputFile)

            'Convert the PDF file to PdfA1A
            converter.ToPdfA1A(outputFolder & "ToPdfA1A.pdf")

            'Convert the PDF file to PdfA1B
            converter.ToPdfA1B(outputFolder & "ToPdfA1B.pdf")

            'Convert the PDF file to PdfA2A
            converter.ToPdfA2A(outputFolder & "ToPdfA2A.pdf")

            'Convert the PDF file to PdfA2B
            converter.ToPdfA2B(outputFolder & "ToPdfA2B.pdf")

            'Convert the PDF file to PdfA3A
            converter.ToPdfA3A(outputFolder & "ToPdfA3A.pdf")

            'Convert the PDF file to PdfA3B
            converter.ToPdfA3B(outputFolder & "ToPdfA3B.pdf")
        End Sub
    End Class
End Namespace

Convert PDF/A to PDF in C# and VB.NET

The way to convert a PDF/A file to regular PDF format is to create a new regular PDF, then draw the content of the PDF/A file into the new PDF.

The following steps describe how to convert a PDF/A file to regular PDF format:

  • Initialize an instance of the PdfDocument class.
  • Load the PDF/A file using the PdfDocument.LoadFromFile(string filePath) method.
  • Initialize an instance of the PdfNewDocument class to create a new PDF file.
  • Iterate through all pages in the PDF/A file.
  • Add pages to the new PDF file using the PdfDocumentBase.Pages.Add(SizeF size, PdfMargins margins) method.
  • Create templates from the pages of the PDF/A file, and draw the templates on the pages of the new PDF file using the PdfPageBase.CreateTemplate().Draw(PdfPageBase page, float x, float y) method.
  • Save the result file using the PdfDocumentBase.Save(string filePath) method.

C#

using Spire.Pdf;
using System.Drawing;

namespace ConvertPdfAToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input file path
            string inputFile = @"C:\Users\Administrator\Desktop\Output\ToPdfA1A.pdf";

            //Specify the output folder
            string outputFolder = @"C:\Users\Administrator\Desktop\Output\";

            //Initialize an instance of the PdfDocument class
            PdfDocument doc = new PdfDocument();
            //Load the PDF/A file specified by the input file path
            doc.LoadFromFile(inputFile);

            //Initialize an instance of the PdfNewDocument class to create a new PDF file
            PdfNewDocument newDoc = new PdfNewDocument();
            //Set the conpression level of the new PDF file as none
            newDoc.CompressionLevel = PdfCompressionLevel.None;

            //Iterate through all the pages in the PDF/A file
            foreach (PdfPageBase page in doc.Pages)
            {
                SizeF size = page.Size;
                //Add pages to the new PDF file
                PdfPageBase p = newDoc.Pages.Add(size, new Spire.Pdf.Graphics.PdfMargins(0));
                //Draw the page content of the PDF/A file into the new PDF file
                page.CreateTemplate().Draw(p, 0, 0);
            }

            //Save the result file in the specified output folder
            newDoc.Save(outputFolder + "ToPdf.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports System.Drawing

Namespace ConvertPdfAToPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Specify the input file path
            Dim inputFile = "C:\Users\Administrator\Desktop\Output\ToPdfA1A.pdf"

            'Specify the output folder
            Dim outputFolder = "C:\Users\Administrator\Desktop\Output\"

            'Initialize an instance of the PdfDocument class
            Dim doc As PdfDocument = New PdfDocument()
            'Load the PDF/A file specified by the input file path
            doc.LoadFromFile(inputFile)

            'Initialize an instance of the PdfNewDocument class to create a new PDF file
            Dim newDoc As PdfNewDocument = New PdfNewDocument()
            'Set the conpression level of the new PDF file as none
            newDoc.CompressionLevel = PdfCompressionLevel.None

            'Iterate through all the pages in the PDF/A file
            For Each page As PdfPageBase In doc.Pages
                Dim size As SizeF = page.Size
                'Add pages to the new PDF file
                Dim p As PdfPageBase = newDoc.Pages.Add(size, New Spire.Pdf.Graphics.PdfMargins(0))
                'Draw page content of the PDF/A file into the new PDF file
                page.CreateTemplate().Draw(p, 0, 0)
            Next

            'Save the result file in the specified output folder
            newDoc.Save(outputFolder & "ToPdf.pdf")
        End Sub
    End Class
End Namespace

C#/VB.NET: Set or Remove Editable Ranges in Word Documents

Setting editable ranges is an effective way to control the editing permissions for specific areas of a Word document. This feature is particularly useful when working on collaborative documents or templates that require restricting changes to certain areas while granting users the ability to add or modify text in other sections. With editable ranges, you can ensure that only authorized users can make changes to selected parts of the document while maintaining the overall structure and formatting. This article will show how to set or remove editable ranges in Word documents using C# and VB.NET.

  • Set Editable Ranges in Word Documents in C# and VB.NET
  • Remove Editable Ranges from Word Documents in C# and VB.NET

Installation

To set or remove editable ranges in Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of FreeSpire.Doc for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Set Editable Ranges in Word Documents in C# and VB.NET

You can set a specific area, for example, a paragraph or part of a paragraph, as an editable range by creating a permission start tag and a permission end tag using the PermissionStart and PermissionEnd classes, then adding these tags to specific positions of the paragraph. After that, you need to protect the document with a password to enable this setting.

The following steps explain how to set a paragraph as an editable range in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Get a specific section of the document by its index using the Document.Sections[int index] property.
  • Get a specific paragraph of the section by its index using the Section.Paragraphs[int index] property.
  • Initialize an instance of the PermissionStart class to create a permission start tag.
  • Initialize an instance of the PermissionEnd class to create a permission end tag.
  • Add the permission start tag and permission end tag to specific positions of the paragraph.
  • Protect the document with a password using the Document.Protect(ProtectionType type, string password) method.
  • Save the result document to another file using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;

namespace SetEditableRanges
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile(@"Sample.docx");
            
            //Get the first section of the document
            Section section= document.Sections[0];
            //Get the first paragraph of the section
            Paragraph paragraph = section.Paragraphs[0];

            //Create a permission start tag (note that the id of the start tag and its end tag must be the same)
            PermissionStart startTag = new PermissionStart(document, "Id");
            //Create a permission end tag
            PermissionEnd endTag = new PermissionEnd(document, "Id");

            //Set the first paragraph as an editable range
            //Add the permission start tag to the beginning of the paragraph
            paragraph.ChildObjects.Insert(0, startTag);
            //Add the permission end tag to the end of the paragraph
            paragraph.ChildObjects.Add(endTag);

            //Protect the document with a password and a specific protection type
            document.Protect(ProtectionType.AllowOnlyReading, "password");

            //Save the result document to another file
            document.SaveToFile("SetEditableRange.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace SetEditableRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Get the first section of the document
            Dim section As Section = document.Sections(0)
            'Get the first paragraph of the section
            Dim paragraph As Paragraph = section.Paragraphs(0)

            'Create a permission start tag (note that the id of the start tag and its end tag must be the same)
            Dim startTag As PermissionStart = New PermissionStart(document, "Id")
            'Create a permission end tag
            Dim endTag As PermissionEnd = New PermissionEnd(document, "Id")

            'Set the first paragraph as an editable range
            'Add the permission start tag to the beginning of the paragraph
            paragraph.ChildObjects.Insert(0, startTag)
            'Add the permission end tag to the end of the paragraph
            paragraph.ChildObjects.Add(endTag)

            'Protect the document with a password and a specific protection type
            document.Protect(ProtectionType.AllowOnlyReading, "password")

            'Save the result document to another file
            document.SaveToFile("SetEditableRange.docx", FileFormat.Docx2013)
            document.Close()
        End Sub
    End Class
End Namespace

When you open the result document after setting editable ranges, Microsoft Word automatically highlights the editable regions for you:

Set Editable Ranges in Word Document in C# or VB.NET

Remove Editable Ranges from Word Documents in C# and VB.NET

If you no longer need the editable ranges in a Word document, you can remove them. To achieve this, you need to iterate through all the elements in the document, then find the elements that are of the PermissionStart or PermissionEnd type and remove them from the paragraphs of the document using the Paragraph.ChildObjects.Remove(IDocumentObject entity) method.

The following steps explain how to remove the editable ranges from a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Iterate through all the sections in the document.
  • Iterate through all the paragraphs in each section.
  • Iterate through all the child objects in each paragraph.
  • Check if the objects are of the PermissionStart or PermissionEnd type.
  • If the result is true, remove them from the paragraph using the Paragraph.ChildObjects.Remove(IDocumentObject entity) method.
  • Save the result document to another file using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;

namespace RemoveEditableRanges
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile(@"SetEditableRange.docx");

            //Iterate through all the sections in the document
            foreach (Section section in document.Sections)
            {
                //Iterate through all the paragraphs in each section
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    //Iterate through all the child objects in each paragraph
                    for (int i = 0; i < paragraph.ChildObjects.Count;)
                    {
                        DocumentObject obj = paragraph.ChildObjects[i];
                        //Find the "PermissionStart" and "PermissionEnd" tags and remove them
                        if (obj is PermissionStart || obj is PermissionEnd)
                        {
                            paragraph.ChildObjects.Remove(obj);
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
            }

            //Save the result document to another file
            document.SaveToFile("RemoveEditableRange.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace RemoveEditableRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("SetEditableRange.docx")

            'Iterate through all the sections in the document
            For Each section As Section In document.Sections
                'Iterate through all the paragraphs in each section
                For Each paragraph As Paragraph In section.Body.Paragraphs
                    'Iterate through all the child objects in each paragraph
                    Dim i = 0

                    While i < paragraph.ChildObjects.Count
                        Dim obj As DocumentObject = paragraph.ChildObjects(i)
                        'Find the "PermissionStart" and "PermissionEnd" tags and remove them
                        If TypeOf obj Is PermissionStart OrElse TypeOf obj Is PermissionEnd Then
                            paragraph.ChildObjects.Remove(obj)
                        Else
                            i += 1
                        End If
                    End While
                Next
            Next

            'Save the result document to another file
            document.SaveToFile("RemoveEditableRange.docx", FileFormat.Docx2013)
            document.Close()
        End Sub
    End Class
End Namespace

When you open the result document after removing editable ranges, you will find that none of the regions are highlighted, indicating that there are no any editable ranges in the document:

Remove Editable Ranges in Word Document in C# or VB.NET

Conclusion

This article described how to protect a Word document while allowing certain areas to be edited by setting editable ranges in C# and VB.NET. Furthermore, it also demonstrated how to remove existing editable ranges from a Word document in C# and VB.NET. In addition to that, the Free Spire.Doc for .NET library also supports protecting Word documents in many other ways, you can take a look at the article C#/VB.NET: Protect Word Documents if interested.

C#/VB.NET: Compare Word Documents for Differences

Working with multiple versions of a Word document can be a daunting task, especially when it comes to identifying differences between each version. Manually reviewing the files can be very time-consuming and error-prone. To simplify this process, Microsoft Word provides users with a valuable comparison feature. This feature highlights all the differences (including differences in text, formatting, layout, tables, images, and other elements) between different versions of a document, making it easier for users to spot variations and saving them a lot of effort and time. In this article, I will explain how to programmatically compare Word documents using C# and VB.NET.

The following topics will be covered:

  • Compare Word Documents and Show Changes in a New Document
  • Compare Word Documents with Customized Options
  • Compare Word Documents and Save the Insertions and Deletions in a TXT File

Installation

To compare Word documents, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Compare Word Documents and Show Changes in a New Document in C# and VB.NET

You can use the Document.Compare(Document document, string author) method to compare two Word documents. This method will highlight the changes between the two documents using “Track Changes”. After you have reviewed the changes, you can accept or reject them according to your needs.

The following steps demonstrate how to compare two Word documents and save the comparison result to a new document:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Compare the two Word documents using the Document.Compare(Document document, string author) method.
  • Save the comparison result to a new document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;

namespace CompareWordDocuments
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Aiden");

            //Save the result document to another file
            doc1.SaveToFile("Compare.docx", FileFormat.Docx2016);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace CompareWordDocuments
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Compare the two Word documents
            doc1.Compare(doc2, "Aiden")

            'Save the result document to another file
            doc1.SaveToFile("Compare.docx", FileFormat.Docx2016)
        End Sub
    End Class
End Namespace

Compare Word Documents with Customized Options in C# and VB.NET

You can use the Document.Compare(Document document, string author, CompareOptions options) method to compare two Word documents with customized options, for example, ignore formatting changes during comparison.

The following steps demonstrate how to compare two Word documents while ignoring formatting changes:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the CompareOptions class.
  • Set the CompareOptions.IgnoreFormatting property as true to ignore formatting during comparison.
  • Compare the two Word documents with the specific compare option using the Document.Compare(Document document, string author, CompareOptions options) method.
  • Save the comparison result to a new document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents.Comparison;

namespace CompareWordDocumentsWithOptions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

            //Initialize an instance of the CompareOptions class
            CompareOptions compareOptions = new CompareOptions();
            //Set to ignore formatting changes during comparison
            compareOptions.IgnoreFormatting = true;

            //Compare the two Word documents with the specific compare options
            doc1.Compare(doc2, "Aiden", compareOptions);

            //Save the result document to another file
            doc1.SaveToFile("CompareWithOptions.docx", FileFormat.Docx2016);
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents.Comparison

Namespace CompareWordDocumentsWithOptions
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Initialize an instance of the CompareOptions class
            Dim compareOptions As CompareOptions = New CompareOptions()
            'Set to ignore formatting changes during comparison
            compareOptions.IgnoreFormatting = True

            'Compare the two Word documents with the specific compare options
            doc1.Compare(doc2, "Aiden", compareOptions)

            'Save the result document to another file
            doc1.SaveToFile("CompareWithOptions.docx", FileFormat.Docx2016)
        End Sub
    End Class
End Namespace

Compare Word Documents and Save the Insertions and Deletions in a TXT File in C# and VB.NET

In addition to saving the changes into a new document, you can also save the changes, such as insertions and deletions, into a TXT file.

The following steps demonstrate how to compare two Word documents and save the insertions and deletions in a TXT file:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Compare the two Word documents using the Document.Compare(Document document, string author) method.
  • Initialize an instance of the DifferRevisions class and pass the first Document instance to the constructor of the class to get the changes between the two Word documents.
  • Get the insertions from the changes using the DifferRevisions.InsertRevisions property.
  • Get the deletion revisions from the changes using the DifferRevisions.DeleteRevisions property.
  • Initialize an instance of the StringBuilder class for storing the insertions and deletions.
  • Iterate through all the insertions, and append the content of each insertion into the StringBuilder instance.
  • Iterate through all the deletions, and append the content of each deletion into the StringBuilder instance.
  • Save the content in the StringBuilder instance into a TXT file.

C#

using Spire.Doc;
using Spire.Doc.Fields;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ExtractInsertionsAndDeletions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Aiden");

            //Get the changes between the documents
            DifferRevisions revisions = new DifferRevisions(doc1);

            //Get the insertions from the changes and save them into a list
            List<DocumentObject> insertRevisionsList = revisions.InsertRevisions;

            //Get the deletions from the changes and save them into a list
            List<DocumentObject> deleteRevisionsList = revisions.DeleteRevisions;

            int m = 0;
            int n = 0;

            //Initialize an instance of the StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Iterate through the insertion revision list
            for (int i = 0; i < insertRevisionsList.Count; i++)
            {
                if (insertRevisionsList[i] is TextRange)
                {
                    m += 1;
                    //Get the content of each insertion and save it to the string builder
                    TextRange textRange = (TextRange)insertRevisionsList[i];
                    sb.AppendLine("Insertion #" + m + ":" + textRange.Text);
                }
            }

            sb.AppendLine("=====================");

            //Iterate through the deletion revision list
            for (int i = 0; i < deleteRevisionsList.Count; i++)
            {
                if (deleteRevisionsList[i] is TextRange)
                {
                    n += 1;
                    //Get the content of each deletion and save it to the string builder
                    TextRange textRange = (TextRange)deleteRevisionsList[i];
                    sb.AppendLine("Deletion #" + n + ":" + textRange.Text);
                }
            }

            //Save the content in the string builder into a .txt file
            File.WriteAllText("InsertionsAndDeletions.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Fields
Imports System.Collections.Generic
Imports System.IO
Imports System.Text

Namespace ExtractInsertionsAndDeletions
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Compare the two Word documents
            doc1.Compare(doc2, "Aiden")

            'Get the changes between the documents
            Dim revisions As DifferRevisions = New DifferRevisions(doc1)

            'Get the insertions from the changes and save them into a list
            Dim insertRevisionsList As List(Of DocumentObject) = revisions.InsertRevisions

            'Get the deletions from the changes and save them into a list
            Dim deleteRevisionsList As List(Of DocumentObject) = revisions.DeleteRevisions

            Dim m = 0
            Dim n = 0

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through the insertion revision list
            For i = 0 To insertRevisionsList.Count - 1
                If TypeOf insertRevisionsList(i) Is TextRange Then
                    m += 1
                    'Get the content of each insertion and save it to the string builder
                    Dim textRange As TextRange = CType(insertRevisionsList(i), TextRange)
                    sb.AppendLine("Insertion #" & m.ToString() & ":" & textRange.Text.ToString())
                End If
            Next

            sb.AppendLine("=====================")

            'Iterate through the deletion revision list
            For i = 0 To deleteRevisionsList.Count - 1
                If TypeOf deleteRevisionsList(i) Is TextRange Then
                    n += 1
                    'Get the content of each deletion and save it to the string builder
                    Dim textRange As TextRange = CType(deleteRevisionsList(i), TextRange)
                    sb.AppendLine("Deletion #" & n.ToString() & ":" & textRange.Text.ToString())
                End If
            Next

            'Save the content in the string builder into a .txt file
            Call File.WriteAllText("InsertionsAndDeletions.txt", sb.ToString())
        End Sub
    End Class
End Namespace

Organize Pages in PDF Documents in Java

When editing PDF documents, users often need to organize pages to make the documents fit their specific requirements. For instance, they may need to insert new pages to include additional information or graphics, rearrange pages to ensure that the content is presented in a logical order, or delete pages containing confidential or sensitive information to protect privacy. In this article, I will explain how to organize pages in a PDF document in Java.

The following topics will be covered in this article:

  • Insert Pages into a PDF Document in Java
  • Delete Pages from a PDF Document in Java
  • Rearrange Pages in a PDF Document in Java
  • Rotate Pages in a PDF Document in Java
  • Import Pages from Another PDF Document in Java
  • Extract Pages from a PDF Document in Java

Add Dependencies

To organize pages in pdf, this article uses Spire.PDF for Java library. If you are using Maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

<repositories>   
    <repository>    
        <id>com.e-iceblue</id>   
        <name>e-iceblue</name>   
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>   
    </repository>   
</repositories>   
<dependencies>   
    <dependency>   
        <groupId> e-iceblue </groupId>   
        <artifactId>spire.pdf </artifactId>   
        <version>9.3.11</version>   
    </dependency>   
</dependencies>

If you are not using Maven, you can download Spire.PDF for Java from the official website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Insert Pages into a PDF Document in Java

You can insert a page at a specific position of a PDF document using the PdfDocument.getPages().insert(int index) method or add a page to the end of a PDF document using the PdfDocument.getPages().add() method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Insert a page at a specific position of the document using the PdfDocument.getPages().insert(int index) method, or add a page to the end of a PDF document using the PdfDocument.getPages().add() method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class InsertPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Insert a page at the first index position
        pdf.getPages().insert(0);

        //Add a page to the end of the document
        //pdf.getPages().add();

        //Save the result document
        pdf.saveToFile("InsertPages.pdf");
    }
}

Delete Pages from a PDF Document in Java

You can delete a specific page from a PDF document using the PdfDocument.getPages().removeAt(int index) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Delete a specific page by its index using the PdfDocument.getPages().removeAt(int index) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class DeletePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Delete the first page by page index
        pdf.getPages().removeAt(0);

        //Save the result document
        pdf.saveToFile("DeletePages.pdf");
    }
}

Rearrange Pages in a PDF Document in Java

You can rearrange the pages in a PDF document using the PdfDocument.getPages().reArrange(int[] orderArray) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Create an int array for the new page order.
  • Rearrange the pages in the document according to the order specified in the int array using the PdfDocument.getPages().reArrange(int[] orderArray) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class RearrangePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Create an int array for new page order 
        //Original page order: 0, 1, 2, 3. Changed page order: 1, 0, 2, 3
        int[] orderArray = new int[] { 1, 0, 2, 3 };
        //Rearrange the pages according to the order specified in the array
        pdf.getPages().reArrange(orderArray);

        //Save the result document
        pdf.saveToFile("RearrangePages.pdf");
    }
}

Rotate Pages in a PDF Document in Java

You can rotate a PDF page using the PdfPageBase.setRotation(PdfPageRotateAngle rotateAngle) method.

The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Get the page that you want to rotate using the PdfDocument.getPages().get(int index) method.
  • Get the original rotation angle of the page using the PdfPageBase.getRotation().getValue() method.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using the PdfPageBase.setRotation(PdfPageRotateAngle rotateAngle) method.
  • Save the result document using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

public class RotatePages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Get the original rotation angle of the page
        int rotation = (int)page.getRotation().getValue();

        //Rotate the page 180 degrees clockwise based on the original rotation angle
        rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue();
        page.setRotation(PdfPageRotateAngle.fromValue(rotation));

        //Save the result document
        pdf.saveToFile("RotatePages.pdf");
    }
}

Import Pages from Another PDF Document in Java

You can import a page or a range of pages from one PDF document to another PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.

The detailed steps are as follows:

  • Initialize an instance of the PdfDocument class and load the first PDF document using the PdfDocument.loadFromFile() method.
  • Initialize an instance of the PdfDocument class and load the second PDF document using the PdfDocument.loadFromFile() method.
  • Import a specific page or a range of pages from the second PDF document to the first PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.
  • Save the first PDF document to file using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
public class ImportPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf1 = new PdfDocument();
        //Load the first PDF document
        pdf1.loadFromFile("Sample.Pdf");

        //Initialize an instance of the PdfDocument class
        PdfDocument pdf2 = new PdfDocument();
        //Load the second PDF document
        pdf2.loadFromFile("test.Pdf");

        //Import the first page of the second PDF to the first PDF
        pdf1.insertPage(pdf2, 0);

        //Import a range of pages (page 1 - 4) of the second PDF to the first PDF
        //pdf1.insertPageRange(pdf2, 0, 3);

        //Save the first PDF document to file
        pdf1.saveToFile("ImportPages.pdf");
    }
}

Extract Pages from a PDF Document in Java

The PdfDocument.insertPage(PdfDocument doc, int pageIndex) and PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) methods can also be used to extract a specific page or a range of pages from a PDF document to a new PDF document.

The detailed steps are as follows:

  • Initialize an instance of the PdfDocument class and load the source PDF document using the PdfDocument.loadFromFile() method.
  • Initialize an instance of the PdfDocument class to create a new PDF document.
  • Extract a specific page or a range of pages from the source PDF document to the new PDF document using the PdfDocument.insertPage(PdfDocument doc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument doc, int startIndex, int endIndex) method.
  • Save the new PDF document to file using the PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class ExtractPages {
    public static void main(String[] args) {
        //Initialize an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        //Load the source PDF document
        pdf.loadFromFile("Sample.Pdf");

        //Initialize an instance of the PdfDocument class to create a new PDF document
        PdfDocument newPdf = new PdfDocument();

        //Extract the first page of the source PDF to the new PDF
        newPdf.insertPage(pdf, 0);

        //Extract a range of pages (page 1 - 4) of the source PDF to the new PDF
        //newPdf.insertPageRange(pdf, 0, 3);

        //Save the new PDF document to file
        newPdf.saveToFile("ExtractPages.pdf");
    }
}

Java: Count the Number of Words, Characters, Paragraphs, Pages and Lines in Word Documents

The word count feature in Microsoft Word is a very helpful tool that provides users with the ability to easily and accurately determine the number of words, characters, paragraphs, pages, and lines in their documents. By using this feature, authors can ensure that their writings meet specific length requirements, while readers can evaluate the length of the documents and make informed decisions about how to allocate their reading time. In this article, I will explain how to programmatically count the number of words, characters, paragraphs, pages, and lines in a Word document in Java.

Add Dependencies

In order to count the number of words, characters, paragraphs, pages, and lines in Word documents, this article uses Spire.Doc for Java, which is a professional Word library specifically designed for creating, reading, writing, converting, and printing Word documents in Java applications

Before coding, you need to add needed dependencies for including Spire.Doc for Java into your Java project. There are two ways to do that.

Method 1: If you are using maven, you can easily import the JAR file of Spire.Doc for Java into your application by adding the following code to your project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.3.0</version>
    </dependency>
</dependencies>

Method 2: If you are not using maven, you can download the JAR file of Spire.Doc for Java from the official website, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

Count the Number of Words, Characters, Paragraphs, Pages and Lines in a Word Document in Java

The following are the main steps to count the number of words, characters, paragraphs, pages, and lines in a Word document:

  • Create an instance of the Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Create an instance of the StringBuilder class.
  • Use Document.getBuiltinDocumentProperties().getPageCount()Document.getBuiltinDocumentProperties().getWordCount()Document.getBuiltinDocumentProperties().getCharCount()Document.getBuiltinDocumentProperties().getCharCountWithSpace()Document.getBuiltinDocumentProperties().getParagraphCount(), and Document.getBuiltinDocumentProperties().getLinesCount() methods to get the count of pages, words, characters, paragraphs and lines in the document.
  • Append the results to the string builder.
  • Save the data in the string builder to a .txt file using FileWriter.write() method.
import com.spire.doc.Document;
import java.io.FileWriter;
import java.io.IOException;

public class WordCount {
    public static void main(String[] args) throws IOException {
        //Create an instance of the Document class
        Document wordDocument = new Document();
        //Load a Word document
        wordDocument.loadFromFile("Sample.docx");

        //Create an instance of the StringBuilder class
        StringBuilder outputStringBuilder = new StringBuilder();

        //Count the number of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder
        int pageCount = wordDocument.getBuiltinDocumentProperties().getPageCount();
        int wordCount = wordDocument.getBuiltinDocumentProperties().getWordCount();
        int charCount = wordDocument.getBuiltinDocumentProperties().getCharCount();
        int charCountWithSpace = wordDocument.getBuiltinDocumentProperties().getCharCountWithSpace();
        int paraCount = wordDocument.getBuiltinDocumentProperties().getParagraphCount();
        int lineCount = wordDocument.getBuiltinDocumentProperties().getLinesCount();

        outputStringBuilder.append("Pages: ").append(pageCount).append(System.lineSeparator());
        outputStringBuilder.append("Words: ").append(wordCount).append(System.lineSeparator());
        outputStringBuilder.append("Characters with No Spaces: ").append(charCount).append(System.lineSeparator());
        outputStringBuilder.append("Characters with Spaces: ").append(charCountWithSpace).append(System.lineSeparator());
        outputStringBuilder.append("Paragraphs: ").append(paraCount).append(System.lineSeparator());
        outputStringBuilder.append("Lines: ").append(lineCount).append(System.lineSeparator());

        //Save the data in the string builder to a text file 
        try (FileWriter fWriter = new FileWriter("WordCount.txt", true)) {
            fWriter.write(outputStringBuilder.toString());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

C++: Create or Edit Excel Files

Excel files are files created by Microsoft Excel or other spreadsheet programs. They enable users to easily store, organize and analyze data in tabular form. Today, Excel files are widely used in various industries for data management, budgeting, accounting, statistical data analysis, and more. In this article, you will see how to create or edit Excel files using C++.

C++ Library to Create or Edit Excel Files

In order to create or edit Excel files in C++ applications, this article uses a third-party library — Spire.XLS for C++. Spire.XLS for C++ is a professional Excel API that can be applied to create, write, edit, convert, and read Excel files in C++ applications.

NuGet is the easiest way to integrate Spire.XLS for C++ into your application, and there are two ways to install Spire.XLS for C++ through NuGet.

1. Install Spire.XLS for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for “Spire.XLS.Cpp” and click install.

2. Install Spire.XLS for C++ using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.XLS.Cpp” and press enter.

If you can’t install the library through NuGet, you can download the package from the official site and manually import it into your project. For more details, you can check the documentation — How to Integrate Spire.XLS for C++ in a C++ Application.

Create Excel XLS or XLSX Files using C++

You can create Excel files with a wide variety of elements using Spire.XLS for C++, such as text, numeric data, images, formulas, hyperlinks, comments, shapes, and charts. The following steps explain how to create a simple Excel file with text and numeric data:

  • Initialize an instance of the Workbook class.
  • Get a specific worksheet by its index (zero-based) using Workbook->GetWorksheets()->Get(int) method (by default, a newly created workbook has 3 worksheets).
  • Add some text and numeric data to specific cells of the worksheet using Worksheet->GetRange(int, int)->SetText() and Worksheet->GetRange(int, int)->SetNumberValue() methods.
  • Set style for the header row and the remaining rows respectively.
  • Autofit column width using Worksheet->GetAllocatedRange()->AutoFitColumns() method.
  • Save the file to an XLS or XLSX file using Workbook->SaveToFile (LPCWSTR_S, ExcelVersion) method.
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main()
{
    //Initialize an instance of the Workbook class
    Workbook* workbook = new Workbook();
	//Get the first worksheet (by default, a newly created workbook has 3 worksheets)
    Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Add some text and numeric data to specific cells of the first worksheet
	sheet->GetRange(1, 1)->SetText(L"Department");
	sheet->GetRange(2, 1)->SetText(L"Accounting and Finance");
	sheet->GetRange(3, 1)->SetText(L"Research and Development");
	sheet->GetRange(4, 1)->SetText(L"Human Resources");
	sheet->GetRange(5, 1)->SetText(L"Sales");
	sheet->GetRange(1, 2)->SetText(L"Name");
	sheet->GetRange(2, 2)->SetText(L"Martin");
	sheet->GetRange(3, 2)->SetText(L"Patrick");
	sheet->GetRange(4, 2)->SetText(L"Karen");
	sheet->GetRange(5, 2)->SetText(L"Anthony");
	sheet->GetRange(1, 3)->SetText(L"Salary");
	sheet->GetRange(2, 3)->SetNumberValue(6100);
	sheet->GetRange(3, 3)->SetNumberValue(7800);
	sheet->GetRange(4, 3)->SetNumberValue(5400);
	sheet->GetRange(5, 3)->SetNumberValue(7400);

	//Get row count
	int rowCount = sheet->GetRows()->GetCount();
	//Get column count
	int colCount = sheet->GetColumns()->GetCount();

	//Iterate through the rows and columns in the worksheet
	for (int row = 1; row <= rowCount; row++)
	{
		for (int col = 1; col <= colCount; col++)
		{	//Set style for cells of the header row	
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetFontName(L"Calibri");
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetSize(12);
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetIsBold(true);
			sheet->GetRange(1, col)->GetStyle()->SetHorizontalAlignment(HorizontalAlignType::Center);
			sheet->GetRange(1, col)->GetStyle()->SetVerticalAlignment(VerticalAlignType::Center);

			//Set style for cells of the remaining rows
			sheet->GetRange(row + 1, col)->GetStyle()->GetFont()->SetFontName(L"Calibri");
			sheet->GetRange(row + 1, col)->GetStyle()->GetFont()->SetSize(11);
			sheet->GetRange(row + 1, col)->GetStyle()->SetHorizontalAlignment(HorizontalAlignType::Center);
			sheet->GetRange(row + 1, col)->GetStyle()->SetVerticalAlignment(VerticalAlignType::Center);
		}
	}

	//Autofit column width
	sheet->GetAllocatedRange()->AutoFitColumns();

	//Save the file to an XLSX file
	workbook->SaveToFile(L"CreateExcel.xlsx", ExcelVersion::Version2013);
	//Save the file to an XLS file
	//workbook->SaveToFile(L"CreateExcel.xls", ExcelVersion::Version97to2003);
	workbook->Dispose();
	delete workbook;
}
Create Excel File in C++

Edit Excel XLS or XLSX Files using C++

You can also edit or update existing Excel files using Spire.XLS for C++. The steps below explain how to update the text of a specific cell and set a background color for it:

  • Initialize an instance of the Workbook class.
  • Load an XLS or XLSX File using Workbook->LoadFromFile() method.
  • Get a specific worksheet by its index (zero-based) using Workbook->GetWorksheets()->Get(int) method.
  • Edit the text of a specific cell using Worksheet->GetRange(int, int)->SetText() method.
  • Set a background color for the cell using Worksheet->GetRange(int, int)-> GetStyle()->SetColor() method.
  • Save the file to an XLS or XLSX file using Workbook->SaveToFile (LPCWSTR_S, ExcelVersion) method.
#include "Spire.Xls.o.h";

using namespace Spire::Xls;
using namespace Spire::Common;

int main()
{
	//Initialize an instance of the Workbook class
	Workbook* workbook = new Workbook();
	//Load an XLSX or XLS file
	workbook->LoadFromFile(L"CreateExcel.xlsx");
	//workbook->LoadFromFile(L"CreateExcel.xls");
	
	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);
	
	//Update the text of the cell [2, 1]
	sheet->GetRange(2, 1)->SetText(L"Updated Cell");
	//Set a background color for the cell [2, 1]
	sheet->GetRange(2, 1)->GetStyle()->SetColor(Color::GetMediumSpringGreen());

	//Save the file to an XLSX file
	workbook->SaveToFile(L"EditExcel.xlsx", ExcelVersion::Version2013);
	//Save the file to an XLS file
	//workbook->SaveToFile(L"EditExcel.xls", ExcelVersion::Version97to2003);
	workbook->Dispose();
	delete workbook;
}
Edit Excel File in C++

C++: Create PDF Files

PDF stands for Portable Document Format, which is a standardized and versatile file format developed by Adobe in 1992. PDF files have many advantages, for example, they can be opened on almost any hardware or operating system without the need for a PDF reader, their layout can remain unchanged no matter what hardware or operating system is used to open them, and their content is not easy to edit. This article will demonstrate how to programmatically create PDF Files using C++.

C++ Library to Create PDF Files

In order to create PDF files in C++ applications, this article uses a third-party library – Spire.PDF for C++. Spire.PDF for C++ is a professional PDF API that can be applied to create, write, edit, convert, and read PDF files in C++ applications.

NuGet is the easiest way to integrate Spire.PDF for C++ into your application, and there are two ways to install Spire.PDF for C++ through NuGet.

1. Install Spire.PDF for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for “Spire.PDF.Cpp” and click install.

2. Install Spire.PDF for C++ using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.PDF.Cpp” and press enter.

In case you can’t install the library through NuGet, you can download the package from the official site and then manually import it into your project. For more details, you can check the documentation — How to Integrate Spire.PDF for C++ in a C++ Application.

Create PDF Files in C++

A PDF file can contain a wide variety of elements, such as text, images, tables, hyperlinks, signatures, fillable form fields, attachments and annotations. The following steps will explain how to create a simple PDF file with text and image:

  • Create a PdfDocument instance.
  • Add a page using PdfDocument->GetPages()->Add() method.
  • Create two PdfSolidBrush instances.
  • Create two PdfTrueTypeFont instances.
  • Create a PdfStringFormat instance and set the text alignment to center using PdfStringFormat ->SetAlignment(PdfTextAlignment::Center) method.
  • Specify the title text.
  • Draw title text on the center of the page with specific brush, font, and string format using PdfPageBase->GetCanvas()->DrawString() method.
  • Specify body text.
  • Create a PdfTextWidget instance based on the body text.
  • Create a RectangleF instance which will then be used to specify the page area for drawing body text.
  • Create a PdfTextLayout instance and set the layout type to paginate to make the content paginated automatically.
  • Draw body text on specific area of the page using PdfTextWidget.Draw() method.
  • Create a PdfImage instance and load an image using PdfImage->FromFile() method.
  • Draw image on the page using PdfPageBase->GetCanvas()->DrawImage() method.
  • Save the result file using PdfDocument->SaveToFile() method.
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace Spire::Common;
using namespace std;

int main()
{
    //Create a PdfDocument instance
    PdfDocument* pdf = new PdfDocument();
    //Add a page
    PdfPageBase* page = pdf->GetPages()->Add();

    //Create two PdfSolidBrush instances
    PdfSolidBrush* brush1 = new PdfSolidBrush(new PdfRGBColor(Color::GetBlue()));
    PdfSolidBrush* brush2 = new PdfSolidBrush(new PdfRGBColor(Color::GetBlack()));

    //Create two PdfTrueTypeFont instances
    PdfTrueTypeFont* font1 = new PdfTrueTypeFont(L"Times New Roman", 20, PdfFontStyle::Bold, true);
    PdfTrueTypeFont* font2 = new PdfTrueTypeFont(L"Times New Roman", 12, PdfFontStyle::Regular, true);

    //Create a PdfStringFormat instance
    PdfStringFormat* format = new PdfStringFormat();
    //Set the text alignment to center
    format->SetAlignment(PdfTextAlignment::Center);

    //Specify title text
    wstring title = L"Introduction to C++ Programming Language";

    //Draw title on the center of the page
    page->GetCanvas()->DrawString(title.c_str(), font1, brush1, new PointF((float)page->GetCanvas()->GetClientSize()->GetWidth() / 2, 20), format);

    //Specify body text
    wstring body = L"C++ (pronounced C plus plus) is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.";

    //Create a PdfTextWidget instance
    PdfTextWidget* widget = new PdfTextWidget(body.c_str(), font2, brush2);
    //Create a RectangleF instance
    RectangleF* rect = new RectangleF(new PointF(0, 50), new SizeF((float)page->GetCanvas()->GetClientSize()->GetWidth(), (float)page->GetCanvas()->GetClientSize()->GetHeight()));

    //Create a PdfTextLayout instance
PdfTextLayout* layout = new PdfTextLayout();
    //Set the PdfLayoutType to Paginate to make the content paginated automatically
    layout->SetLayout(PdfLayoutType::Paginate);

    PdfNewPage* newPage = Object::Convert<PdfNewPage>(page);

    //Draw body text on the page
    widget->Draw(newPage, rect, layout);

    //Load an image
    PdfImage* image = new PdfImage();
    image = image->FromFile(L"C++.png");
    float width = image->GetWidth()*0.35;
    float height = image->GetHeight()*0.35;
    float x = (page->GetCanvas()->GetClientSize()->GetWidth() - width) / 2;

    //Draw image on the page
    page->GetCanvas()->DrawImage(image, x, 100, width, height);

    //Save the result file
    pdf->SaveToFile(L"CreatePdf.pdf");
    pdf->Close();
    delete pdf;
    delete brush1;
    delete brush2;
    delete font1;
    delete font2;
    delete format;
    delete widget;
    delete rect;
    delete layout;
    delete image;
}
Create PDF File in C++

Convert RTF to Word or Word to RTF in C++

RTF stands for Rich Text Format, which is a proprietary file format developed by Microsoft for exchanging text files between different word processing programs. Unlike Word documents, RTF is readable across many programs and platforms, but it has some limitations, for example, it cannot retain certain types of formatting, such as track changes and comments, or include certain types of images. Sometimes, you may need to convert an RTF file to Word to get rid of these limitations or convert a Word file to RTF to improve its compatibility. In this article, I will demonstrate how to programmatically convert RTF files to Word or convert Word files to RTF in C++.

  • Convert RTF to Word in C++
  • Convert Word to RTF in C++

C++ Library to Convert RTF to Word or Word to RTF

In order to implement the conversions between RTF and Word files in C++ applications, this article uses a third-party library called Spire.Doc for C++. Spire.Doc for C++ is a professional Word library specifically designed for creating, reading, writing, converting, merging, splitting, and comparing Word documents in C++ applications with fast and high-quality performance.

NuGet is the easiest way to integrate Spire.Doc for C++ into your application, and there are two ways to install Spire.Doc for C++ through NuGet.

1. Install Spire.Doc for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for Spire.Doc.Cpp and click install.

2. Install the library using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.Doc.Cpp” and press enter.

In case you can’t install the library through NuGet, you can download the package from the official site and then manually import it into your project. For more details, you can check the documentation – How to Integrate Spire.Doc for C++ in a C++ Application.

Convert RTF to Word in C++

Converting an RTF file to Word is very straightforward with Spire.Doc for C++, you just need to load the file and then call the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method. The following steps show you how to convert RTF to Word in C++:

  • Initialize an instance of the Document class.
  • Load an RTF document using Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Save the RTF document to Word Doc/Docx format using Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main()
{
	//Initialize an instance of the document class
	Document* doc = new Document();
	//Load an RTF file 
	doc->LoadFromFile(L"Input.rtf");

	//Save the RTF file to Word Docx format
	doc->SaveToFile(L"RtfToWord.docx", FileFormat::Docx2013);
	doc->Close();
	delete doc;
}

Convert Word to RTF in C++

The Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method can also be used to convert a Word file to RTF format. The steps to convert a Word file to RTF are very similar to that of the above example:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Save the document as an RTF file using Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main()
{
	//Initialize an instance of the document class
	Document* doc = new Document();
	//Load a Word file 
	doc->LoadFromFile(L"Input.docx");

	//Save the Word file to RTF format
	doc->SaveToFile(L"WordToRtf.docx", FileFormat::Rtf);
	doc->Close();
	delete doc;
}

Conclusion

This article demonstrated how to convert RTF to Word or Word to RTF in C++ applications using Spire.Doc for C++. Actually, this library also supports lots of other file format conversions, for example, it can convert RTF to PDF and HTML, as well as convert Word to HTML, PDF, images and more.

Design a site like this with WordPress.com
Get started