Tuesday, 18 January 2011 04:01

Decrypt Word Document in C#, VB.NET

Word Decryption is a process to decode encrypted Word document. It requires a password or secret key. If readers want to open and read a protected Word, they need to decrypt this Word document firstly. This guide demonstrates an easy and convenient solution to decrypt Word in C# and VB.NET via Spire.Doc for .NET.

Spire.Doc for .NET, specially developed for programmers to manipulate Word without Word Automation, provides users a method Document.LoadFromFile(String fileName, FileFormat fileFormat, String password) of Document class to open encrypted Word document. It also provides another method Document.RemoveEncryption() to decrypt Word without any protection. Through these two methods, users can decrypt Word easily with Spire.Doc for .NET. Download and install Spire.Doc for .NET. Then follow the code to decrypt.

[C#]
using Spire.Doc;

namespace DecryptWord
{
    class Decryption
    {
        static void Main(string[] args)
        {
            //Load Encrypted Word
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Student Transcript.docx", FileFormat.Docx,"123456");

            //Decrypt
            document.RemoveEncryption();
            
            //Save and Launch
            document.SaveToFile("decryption.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("decryption.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace DecryptWord
    Friend Class Decryption
        Shared Sub Main(ByVal args() As String)
            'Load Encrypted Word
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Student Transcript.docx", FileFormat.Docx, "123456")

            'Decrypt
            document.RemoveEncryption()

            'Save and Launch
            document.SaveToFile("decryption.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("decryption.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, professional Word component, is specially designed for developers to fast generate, write, modify and save Word documents in .NET, Silverlight and WPF with C# and VB.NET. Also, it supports conversion between Word and other popular formats, such as PDF, HTML, Image, Text and so on, in .NET and WPF platform.

Wednesday, 03 April 2024 02:22

C#: Convert Word to PDF

In today's digital era, the skill of converting Word documents to PDF has become indispensable for individuals and organizations alike. The ability to transform Word files into the PDF format has a wide range of applications, including submitting official reports, distributing e-books, and archiving important files. Through this conversion process, documents can be seamlessly shared, accessed, and preserved for the long term, ensuring convenience, compatibility, and enhanced document management.

In this article, you will learn how to convert Word to PDF in C# and how to set conversion options as well using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert Word to PDF in C#

Converting a Word document to a standard PDF using Spire.Doc is a simple task. To get started, you can utilize the LoadFromFile() or LoadFromStream() method from the Document object to load a Word document from a given file path or stream. Then, you can effortlessly convert it as a PDF file by employing the SaveToFile() method.

To convert Word to PDF in C#, follow these steps.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ConvertWordToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Save the document to PDF
            doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert Word to PDF/A in C#

PDF/A is a specialized format that focuses on preserving electronic documents for long-term use, guaranteeing that the content remains accessible and unaltered as time goes on.

To specify the conformance level of the resulting PDF when converting a document, you can make use of the PdfConformanceLevel property found within the ToPdfParameterList object. By passing this object as an argument to the SaveToFile() method, you can indicate the desired conformance level during the conversion process.

The steps to convert Word to PDF/A in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Set the conformance level for the generated PDF using PdfConformanceLevel property of the ToPdfParameterList object.
  • Save the Word document to PDF/A using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace ConvertWordToPdfa
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters  = new ToPdfParameterList();

            // Set the conformance level for PDF
            parameters.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1A;

            // Save the document to a PDF file
            doc.SaveToFile("ToPdfA.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert Word to Password-Protected PDF in C#

Transforming a Word document into a PDF that is protected by a password is a straightforward and efficient method to safeguard sensitive information and maintain its confidentiality and security.

To accomplish this, you can utilize the PdfSecurity.Encrypt() method, which is available within the ToPdfParameterList object. This method enables you to specify both an open password and a permission password for the resulting PDF file. By passing the ToPdfParameterList object as a parameter to the SaveToFile() method, these encryption settings will be implemented during the saving process.

The steps to convert Word to password-protected PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Set the open password and permission password for the generated PDF using ToPdfParameterList.PdfSecurity.Encrypt() method.
  • Save the Word document to a password protected PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace ConvertWordToPasswordProtectedPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Set open password and permission password for PDF
            parameters.PdfSecurity.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.None, PdfEncryptionKeySize.Key128Bit);

            // Save the document to PDF
            doc.SaveToFile("PasswordProtected.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert a Specific Section in Word to PDF in C#

Being able to convert a specific section of a Microsoft Word document to a PDF can be highly advantageous when you want to extract a portion of a larger document for sharing or archiving purposes.

With the assistance of Spire.Doc, users can create a new Word document that contains the desired section from the source document by employing the Section.Clone() method and the Sections.Add() method. This new document can be then saved as a PDF file.

The following are the steps to convert a specific section of a Word document to PDF in C#.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create another Document object for holding one section from the source document.
  • Create a copy of a desired section of the source document using Section.Clone() method.
  • Add the copy to the new document using Sections.Add() method.
  • Save the new Word document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ConvertSectionToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Get a specific section of the document
            Section section = doc.Sections[1];

            // Create a new document object
            Document newDoc = new Document();

            // Clone the default style to the new document
            doc.CloneDefaultStyleTo(newDoc);

            // Clone the section to the new document
            newDoc.Sections.Add(section.Clone());

            // Save the new document to PDF
            newDoc.SaveToFile("SectionToPDF.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
            newDoc.Dispose();
        }
    }
}

Change Page Size while Converting Word to PDF in C#

When converting a Word document to PDF, it may be necessary to modify the page size to align with standard paper sizes like Letter, Legal, Executive, A4, A5, B5, and others. Alternatively, you might need to customize the page dimensions to meet specific requirements.

By making use of the PageSetup.PageSize property, you can adjust the page size of the Word document to either a standard paper size or a custom paper size. This page configuration will be applied during the conversion process, ensuring that the resulting PDF file reflects the desired page dimensions.

The steps to change the page size while convert Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Iterate through the sections in the document, and change the page size of each section to a standard paper size or a custom size using PageSetup.PageSize property.
  • Save the Word document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangePageSize
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Iterate through the sections in the document
            foreach (Section section in doc.Sections)
            {
                // Change the page size of each section to Letter
                section.PageSetup.PageSize = PageSize.Letter;

                // Change the page size of each section to a custom size
                // section.PageSetup.PageSize = new SizeF(500, 800);
            }

            // Save the document to PDF
            doc.SaveToFile("ChangePageSize.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Set Image Quality while Converting Word to PDF in C#

When converting a Word document to PDF, it's essential to consider the quality of the images within the document. Balancing image integrity and file size is crucial to ensure an optimal viewing experience and efficient document handling.

Using Spire.Doc, you have the option to configure the image quality within the document by utilizing the JPEGQuality property of the Document object. For instance, by setting the value of JPEGQuality to 50, the image quality can be reduced to 50% of its original quality.

The steps to set image quality while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document for a given file path.
  • Set the image quality using Document.JPEGQuality property.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace SetImageQuality
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Set the image quality to 50% of the original quality
            doc.JPEGQuality = 50;

            // Preserve original image quality
            // doc.JPEGQuality = 100;

            // Save the document to PDF
            doc.SaveToFile("SetImageQuality.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Embed Fonts while Converting Word to PDF in C#

When fonts are embedded in a PDF, it ensures that viewers will see the exact font styles and types intended by the creator, regardless of whether they have the fonts installed on their system.

To include all the fonts used in a Word document in the resulting PDF, you can enable the embedding feature by setting the ToPdfParameterList.IsEmbeddedAllFonts property to true. Alternatively, if you prefer to specify a specific list of fonts to embed, you can make use of the EmbeddedFontNameList property.

The steps to embed fonts while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Embed all fonts in the generated PDF by settings IsEmbeddedAllFonts property to true.
  • Save the Word document to PDF with fonts embedded using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace EmbedFonts
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Embed all the fonts used in Word in the generated PDF
            parameters.IsEmbeddedAllFonts = true;

            // Save the document to PDF
            doc.SaveToFile("EmbedFonts.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Create Bookmarks while Converting Word to PDF in C#

Including bookmarks in a PDF document while converting from Microsoft Word can greatly enhance the navigation and readability of the resulting PDF, especially for long or complex documents.

When utilizing Spire.Doc to convert a Word document to PDF, you have the option to automatically generate bookmarks based on existing bookmarks or headings. You can accomplish this by enabling either the CreateWordsBookmarks property or the CreateWordBookmarksUsingHeadings property of the ToPdfParameterList object.

The steps to create bookmark while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Generate bookmarks in PDF based on the existing bookmarks of the Word document by settings CreateWordsBookmarks property to true.
  • Save the Word document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace CreateBookmarkWhenConverting
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Create bookmarks in PDF from existing bookmarks in Word
            parameters.CreateWordBookmarks = true;

            // Create bookmarks from Word headings
            // parameters.CreateWordBookmarksUsingHeadings= true;

            // Save the document to PDF
            doc.SaveToFile("CreateBookmarks.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Disable Hyperlinks while Converting Word to PDF in C#

While converting a Word document to PDF, there are instances where it may be necessary to deactivate hyperlinks. This can be done to prevent accidental clicks or to maintain a static view of the document without any navigation away from its pages.

To disable hyperlinks during the conversion process, simply set the DisableLink property of the ToPdfParameterList object to true. By doing so, the resulting PDF will not contain any active hyperlinks.

The steps to disable hyperlinks while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Disable hyperlinks by settings DisableLink property to true.
  • Save the Word document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace DisableHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Disable hyperlinks
            parameters.DisableLink = true;

            // Save the document to PDF
            doc.SaveToFile("DisableHyperlinks.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Thursday, 13 January 2011 09:49

Insert Image Header and Footer for Word

Word header and footer presents additional information of Word document, which can be text, image or page number. This guide focuses on introducing how to insert image header and footer for Word document in C# and VB.NET.

Header/Footer plays an important role in Word document, which uses text, image or page number to demonstrate some additional information about this document. The information can be company name, logo, author name, document title etc. This guide will demonstrate detailed process to insert image header/footer in Word with C# and VB.NET via Spire.Doc for .NET. The following screenshot displays Word image header/footer result after programming.

Insert Image Header/Footer

Spire.Doc for .NET provides a HeaderFooter. class to enable developers to generate a new header or footer. Firstly, initialize a header instance of HeaderFooter class and then invoke AddParagraph() method to add a paragraph body for this header/footer instance. Next, invoke Paragraph.AppendPicture(Image image) method to append a picture for header/footer paragraph. If you want to add text for paragraph as well, please invoke Paragraph.AppendText(string text) method. Also, you can set format for header/footer paragraph, appended image and text to have a better layout. Code as following:

[C#]
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ImageHeaderFooter
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");

            //Initialize a Header Instance
            HeaderFooter header = document.Sections[0].HeadersFooters.Header;
            //Add Header Paragraph and Format 
            Paragraph paragraph = header.AddParagraph();
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            //Append Picture for Header Paragraph and Format
            DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"E:\Logo\doclog.png"));
            headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom;

            //Initialize a Footer Instance
            HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
            //Add Footer Paragraph and Format
            Paragraph paragraph2 = footer.AddParagraph();
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left;
            //Append Picture and Text for Footer Paragraph
            DocPicture footerimage = paragraph2.AppendPicture(Image.FromFile(@"E:\Logo\logo.jpeg"));
            TextRange TR = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.");
            TR.CharacterFormat.FontName = "Arial";
            TR.CharacterFormat.FontSize = 10;
            TR.CharacterFormat.TextColor = Color.Black;

            //Save and Launch
            document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("ImageHeaderFooter.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace ImageHeaderFooter
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")

            'Initialize a Header Instance
            Dim header As HeaderFooter = document.Sections(0).HeadersFooters.Header
            'Add Header Paragraph and Format 
            Dim paragraph As Paragraph = header.AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right
            'Append Picture for Header Paragraph and Format
            Dim headerimage As DocPicture = paragraph.AppendPicture(Image.FromFile("E:\Logo\doclog.png"))
            headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom

            'Initialize a Footer Instance
            Dim footer As HeaderFooter = document.Sections(0).HeadersFooters.Footer
            'Add Footer Paragraph and Format
            Dim paragraph2 As Paragraph = footer.AddParagraph()
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left
            'Append Picture and Text for Footer Paragraph
            Dim footerimage As DocPicture = paragraph2.AppendPicture(Image.FromFile("E:\Logo\logo.jpeg"))
            Dim TR As TextRange = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.")
            TR.CharacterFormat.FontName = "Arial"
            TR.CharacterFormat.FontSize = 10
            TR.CharacterFormat.TextColor = Color.Black

            'Save and Launch
            document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("ImageHeaderFooter.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to perform Word tasks, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.

Thursday, 14 April 2022 06:38

C#/VB.NET: Align Text in Word

Text alignment is a paragraph formatting attribute that determines the appearance of the text in a whole paragraph. There are four types of text alignments available in Microsoft Word: left-aligned, center-aligned, right-aligned, and justified. In this article, you will learn how to programmatically set different text alignments for paragraphs in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Align Text in Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Get a specified paragraph using Section.Paragraphs[] property.
  • Get the paragraph format using Paragraph.Format property
  • Set text alignment for the specified paragraph using ParagraphFormat.HorizontalAlignment property.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

namespace AlignText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();

            //Load a sample Word document
            doc.LoadFromFile(@"D:\Files\sample.docx");

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

            //Get the first paragraph and make it center-aligned
            Paragraph p = section.Paragraphs[0];
            p.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Get the second paragraph and make it left-aligned
            Paragraph p1 = section.Paragraphs[1];
            p1.Format.HorizontalAlignment = HorizontalAlignment.Left;

            //Get the third paragraph and make it right-aligned
            Paragraph p2 = section.Paragraphs[2];
            p2.Format.HorizontalAlignment = HorizontalAlignment.Right;

            //Get the fourth paragraph and make it justified
            Paragraph p3 = section.Paragraphs[3];
            p3.Format.HorizontalAlignment = HorizontalAlignment.Justify;

            //Save the document
            doc.SaveToFile("WordAlignment.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Align Text in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Thursday, 13 January 2011 08:01

Set Word Font in C#, VB.NET

Word Font setting allows users to change text font style and size in a document. With wonderful font settings, the document layout and appearance will be more appealed. What’s more, in order to make some special words, phrases or paragraphs more obvious, users can set different font styles or size. For example, the title is often set as different font style with bigger size from body.

Spire.Doc for .NET, a professional .NET Word component, enables users to set font in Word document. This guide will shows how to set by using C#, VB.NET via Spire.Doc for .NET and the following screenshot presents result after setting.

Word Text Font Style

  • Load the document and get the paragraph which you want to set font.
  • Then, declare a new paragraph style and set FontName and FontSize properties of this style.
  • Finally, apply the style for paragraph and save document. Code as following:
[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Humor Them.docx");

            //Get Paragraph
            Section s = document.Sections[0];
            Paragraph p = s.Paragraphs[1];

            //Set Font Style and Size
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "FontStyle";
            style.CharacterFormat.FontName = "Century Gothic";
            style.CharacterFormat.FontSize = 20;
            document.Styles.Add(style);
            p.ApplyStyle(style.Name);

            //Save and Launch
            document.SaveToFile("font.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("font.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordImage
    Friend Class ImageinWord
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\Humor Them.docx")

            'Get Paragraph
            Dim s As Section = document.Sections(0)
            Dim p As Paragraph = s.Paragraphs(1)

            'Set Font Style and Size
            Dim style As New ParagraphStyle(document)
            style.Name = "FontStyle"
            style.CharacterFormat.FontName = "Century Gothic"
            style.CharacterFormat.FontSize = 20
            document.Styles.Add(style)
            p.ApplyStyle(style.Name)

            'Save and Launch
            document.SaveToFile("font.docx", FileFormat.Docx2010)
            System.Diagnostics.Process.Start("font.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a professional Word component, can be used to generate, load, write, edit and save Word documents for .NET, Silverlight and WPF.

Friday, 25 March 2022 07:48

C#/VB.NET: Change Font Color in Word

If you want to emphasize a specific paragraph or text in your Word document, you can change its font color. This article will demonstrate how to change font color in Word in C# and VB.NET using Spire.Doc for .NET library.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Change Font Color of a Paragraph in C# and VB.NET

The following are the steps to change the font color of a paragraph in a Word document:

  • Create a Document instance.
  • Load the Word document using Document.LoadFromFile() method.
  • Get the desired section using Document.Sections[sectionIndex] property.
  • Get the desired paragraph that you want to change the font color of using Section.Paragraphs[paragraphIndex] property.
  • Create a ParagraphStyle instance.
  • Set the style name and font color using ParagraphStyle.Name and ParagraphStyle.CharacterFormat.TextColor properties.
  • Add the style to the document using Document.Styles.Add() method.
  • Apply the style to the paragraph using Paragraph.ApplyStyle() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontColorForParagraph
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

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

            //Change text color of the first Paragraph
            Paragraph p1 = section.Paragraphs[0];
            ParagraphStyle s1 = new ParagraphStyle(document);
            s1.Name = "Color1";
            s1.CharacterFormat.TextColor = Color.RosyBrown;
            document.Styles.Add(s1);
            p1.ApplyStyle(s1.Name);

            //Change text color of the second Paragraph
            Paragraph p2 = section.Paragraphs[1];
            ParagraphStyle s2 = new ParagraphStyle(document);
            s2.Name = "Color2";
            s2.CharacterFormat.TextColor = Color.DarkBlue;
            document.Styles.Add(s2);
            p2.ApplyStyle(s2.Name);

            //Save the result document
            document.SaveToFile("ChangeParagraphTextColor.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Change Font Color in Word

Change Font Color of a Specific Text in C# and VB.NET

The following are the steps to change the font color of a specific text in a Word document:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Find the text that you want to change font color of using Document.FindAllString() method.
  • Loop through all occurrences of the searched text and change the font color for each occurrence using TextSelection.GetAsOneRange().CharacterFormat.TextColor Property.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontColorForText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Find the text that you want to change font color for
            TextSelection[] text = document.FindAllString("Spire.Doc for .NET", false, true);
            //Change the font color for the searched text
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.TextColor = Color.Red;
            }

            //Save the result document
            document.SaveToFile("ChangeCertainTextColor.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Change Font Color in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Thursday, 11 April 2024 02:32

C#: Find and Replace Text in Word Documents

When it comes to editing documents, making changes to the text is a common task. Microsoft Word provides a robust feature called "Find and Replace" that streamlines the text editing process. With this feature, you can effortlessly locate specific words, phrases, or characters within your document and replace them in one simple action. This eliminates the need for repetitive manual searching and time-consuming edits, saving you valuable time and effort, especially when you need to make widespread changes in lengthy documents. In this article, we will explain how to find and replace text in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find Text and Replace All Its Instances with New Text

Spire.Doc for .NET provides the Document.Replace() method that enables you to find and replace specific text in a Word document. With this method, you can seamlessly replace all instances of the target text with new content. Additionally, you have the flexibility to specify whether the search should be case-sensitive and whether whole-word matching should be considered. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Replace all instances of specific text with new text using Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

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

            //Replace all instances of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceAllText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find Text and Replace Its First Instance with New Text

To replace the first instance of a specific text in a Word document using Spire.Doc for .NET, you can utilize the Document.ReplaceFirst property. By setting this property to true before calling the Document.Replace() method, you can change the text replacement mode to exclusively replace the first instance. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Change the text replacement mode to replace the first instance only by setting the Document.ReplaceFirst property to true.
  • Call the Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method to replace text.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

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

            //Change the text replacement mode to replace the first instance only
            document.ReplaceFirst = true;

            //Replace the first instance of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceFirstText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Image

Sometimes, you may need to replace text with images for visual representation or design purposes. In Spire.Doc for .NET, replacing text with image can be achieved by inserting the image at the position of the target text and then removing the text from the document. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find specific text in the document using Document.FindAllString() method.
  • Loop through the matched text.
  • For each matched text, get the paragraph where it is located and get the position of the text in the paragraph.
  • Instantiate an object of the DocPicture class, and then load an image using DocPicture.LoadImage() method.
  • Insert the image into the paragraph at the position of the text and then remove the text from the paragraph.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

            //Find specific text in the document
            TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);

            int index = 0;
            Paragraph ownerParagraph = null;

            //Loop through the matched text
            foreach (TextSelection selection in selections)
            {
                //Get the paragraph where the text is located
                ownerParagraph = selection.GetAsOneRange().OwnerParagraph;

                //Get the index position of the text in the paragraph
                index = ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange());

                //Load an image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage("img.png");

                //Insert the image into the paragraph at the index position of the text
                ownerParagraph.ChildObjects.Insert(index, pic);

                //Remove the text from the paragraph
                ownerParagraph.ChildObjects.Remove(selection.GetAsOneRange());
            }

            //Save the result document
            document.SaveToFile("ReplaceTextWithImage.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find and Replace Text using Regular Expression

Regular expressions offer a robust toolset for performing complex search and replace operations within documents. The Document.Replace() method can leverage regular expressions to search for specific text, allowing you to perform advanced search and replace operations based on specific criteria. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Instantiate an object of the Regex class to match text based on specific criteria.
  • Replace the matched text with new text using Document.Replace(Regex pattern, string replace) method.
  • Save the resulting document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using System.Text.RegularExpressions;

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

            //Create a regex to match the text that starts with #
            Regex regex = new Regex(@"\#\w+\b");

            //Replace the matched text with new text
            document.Replace(regex, "Spire.Doc");

            //Save the result document
            document.SaveToFile("ReplaceTextWithRegex.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Content from Another Word Document

In addition to replacing text with new text or image, Spire.Doc for .NET also enables you to replace text with content from another Word document. This can be beneficial when you are working on a predefined Word template and need to incorporate contents from other Word documents into it. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Load another Word document into an IDocument object.
  • Replace specific text in the sample document with content from another document using Document.Replace(string matchString, IDocument matchDoc, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Interface;

namespace ReplaceTextWithDocument
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Template.docx");

            //Load another Word document
            IDocument document1 = new Document("Report.docx");

            //Replace specific text in the sample document with content from another document
            document.Replace("Annual Sales", document1, false, true);

            //Save the result document
            document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Tuesday, 31 May 2022 07:20

C#/VB.NET: Convert Word to XML

XML is a markup language and file format designed mainly to store and transmit arbitrary content. XML files have the feature of simplicity, generality, and usability, making them popular, especially among web servers. XML and HTML are two important markup languages on the web, but XML focuses on storing and transmitting data while HTML focuses on displaying webpages. This article demonstrates how to convert Word documents to XML files with the help of Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert a Word Document to an XML File

The detailed steps are as follows:

  • Create an object of Document class.
  • Load the Word document from disk using Document.LoadFromFile().
  • Save the Word document as an XML file using Document.SaveToFile().
  • C#
  • VB.NET
using System;
using Spire.Doc;

namespace WordtoXML
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an object of Document class
            Document document = new Document();

            //Load a Word document from disk
            document.LoadFromFile(@"D:\testp\test.docx");

            //Save the Word document as an XML file
            document.SaveToFile("Sample.xml", FileFormat.Xml);
        }
    }
}

C#/VB.NET: Convert Word to XML

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Wednesday, 03 August 2022 07:10

C#/VB.NET: Insert Hyperlinks to Word Documents

A hyperlink within a Word document enables readers to jump from its location to a different place within the document, or to a different file or website, or to a new email message. Hyperlinks make it quick and easy for readers to navigate to related information. This article demonstrates how to add hyperlinks to text or images in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert Hyperlinks When Adding Paragraphs to Word

Spire.Doc offers the Paragraph.AppendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.

  • Create a Document object.
  • Add a section and a paragraph to it.
  • Insert a hyperlink based on text using Paragraph.AppendHyerplink(string link, string text, HyperlinkType type) method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Insert a hyperlink based on the image using Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace InsertHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Word document
            Document doc = new Document();

            //Add a section
            Section section = doc.AddSection();

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add an email link
            paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add a file link
            string filePath = @"C:\Users\Administrator\Desktop\report.xlsx";
            paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add another section and create a bookmark 
            Section section2 = doc.AddSection();
            Paragraph bookmarkParagrapg = section2.AddParagraph();
            bookmarkParagrapg.AppendText("Here is a bookmark");
            BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
            bookmarkParagrapg.Items.Insert(0, start);
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark");

            //Link to the bookmark
            paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add an image link
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
            Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
            paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink);

            //Save to file
            doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Insert Hyperlinks to Word Documents

Add Hyperlinks to Existing Text in Word

Adding hyperlinks to existing text in a document is a bit more complicated. You’ll need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Find all the occurrences of the target string in the document using Document.FindAllString() method, and get the specific one by its index from the collection.
  • Get the string’s own paragraph and its position in it.
  • Remove the string from the paragraph.
  • Create a hyperlink field and insert it to position where the string is located.
  • Save the document to another file using Document.SaveToFle() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;

namespace AddHyperlinksToExistingText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Load a Word file
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");

            //Find all the occurrences of the string ".NET Framework" in the document
            TextSelection[] selections = document.FindAllString(".NET Framework", true, true);

            //Get the second occurrence
            TextRange range = selections[1].GetAsOneRange();
      
            //Get its owner paragraph
            Paragraph parapgraph = range.OwnerParagraph;

            //Get its position in the paragraph
            int index = parapgraph.Items.IndexOf(range);

            //Remove it from the paragraph
            parapgraph.Items.Remove(range);

            //Create a hyperlink field
            Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
            field.Type = Spire.Doc.FieldType.FieldHyperlink;
            Hyperlink hyperlink = new Hyperlink(field);
            hyperlink.Type = HyperlinkType.WebLink;
            hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework";
            parapgraph.Items.Insert(index, field);

            //Insert a field mark "start" to the paragraph
            IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
            (start as FieldMark).Type = FieldMarkType.FieldSeparator;
            parapgraph.Items.Insert(index + 1, start);
            
            //Insert a text range between two field marks
            ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
            textRange.Text = ".NET Framework";
            textRange.CharacterFormat.Font = range.CharacterFormat.Font;
            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
            textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
            parapgraph.Items.Insert(index + 2, textRange);

            //Insert a field mark "end" to the paragraph
            IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
            (end as FieldMark).Type = FieldMarkType.FieldEnd;
            parapgraph.Items.Insert(index + 3, end);

            //Save to file
            document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Hyperlinks to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Word encryption, one method to protect Word document, requires users to give the document a password. Without the password, encrypted document cannot be opened. Solution in this guide demonstrates how to encrypt Word document with custom password in C# and VB.NET via Spire.Doc for .NET.

Spire.Doc for .NET, specializing in performing Word processing tasks for .NET, provides a Document.Encrypt method which enables users to encrypt Word. The overload passed to this method is string password. Firstly, load the Word document which is needed to protect. Secondly, invoke Document.Encrypt method to encrypt with password. Thirdly, save the encrypt document and launch for viewing. After debugging, a dialog box pops up and requires the password. Enter the password to open the document and the document information will be shown as following to tell users that it is encrypted.

Encrypt Word Document

Download and install Spire.Doc for .NET and use the following code to encrypt Word.

[C#]
using Spire.Doc;

namespace Encryption
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx");

            //Encrypt
            document.Encrypt("eiceblue");

            //Save and Launch
            document.SaveToFile("Encryption.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Encryption.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace Encryption
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx")

            'Encrypt
            document.Encrypt("eiceblue")

            'Save and Launch
            document.SaveToFile("Encryption.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Encryption.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.