Forem

Cover image for How to Convert Word to PDF in C# with Advanced Formatting Options
Calvince Moth for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

How to Convert Word to PDF in C# with Advanced Formatting Options

TL;DR: This guide demonstrates how to efficiently convert Word documents to PDF using the .NET Word Library in C#, with advanced customization options like font embedding, accessible PDFs, and support for complex scripts.

Converting Word documents to PDF is crucial for preserving document fidelity, enabling cross-platform sharing, and ensuring compatibility across diverse environments.

The Syncfusion .NET Word Library (DocIO) simplifies this process, allowing seamless Word-to-PDF conversion with just a few lines of C# code. This standalone library functions independently, eliminating the need for Microsoft Word or interop dependencies, ensuring a lightweight and efficient solution.

This Word-to-PDF conversion is available in multiple environments, such as:

  • Windows
  • Linux
  • macOS
  • Mobile devices
  • Docker
  • Cloud computing environments

With advanced customization options, the DocIO allows us to embed fonts, convert Word document headings to PDF bookmarks, preserve accessibility, and handle complex scripts effortlessly. It supports all major Word document elements, including text, formatting, images, tables, hyperlinks, fields, headers, footers, and more. You can convert commonly used Word file formats such as DOC, DOCX, and RTF into PDF.

Advanced options

Let’s get started with the implementation!

Getting started

Step 1: First, create a new C# .NET Core Console App in Visual Studio.

Create a new .NET Core Console app

Step 2: Then, install the Syncfusion.DocIORenderer.Net.Core NuGet package as a reference to the app from NuGet Gallery.

Install the Syncfusion.DocIORenderer.Net.Core NuGet package

Step 3: Finally, include the following namespaces in the Program.cs file.

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf;
Enter fullscreen mode Exit fullscreen mode

Now the project is ready! Let’s write the code to convert a Word document into PDF.

// Open the Word document file stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    // Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        // Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            // Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                // Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

By executing this code example, we will get output like in the following screenshot.

Converting Word document to PDF in C# using .NET Word Library


Converting Word document to PDF in C# using .NET Word Library

Now, explore the advanced features!

Embed fonts in PDF

You may want to ensure the fonts are correctly displayed when sharing PDFs across different platforms. Embedding fonts ensures the PDF renders exactly as intended, even if the viewer’s system lacks the required fonts.

Embed fonts subset

Embed the font glyphs from the TrueType fonts only for the characters used in the Word document.

Refer to the following code example.

DocIORenderer render = new DocIORenderer();
//Set to true to embed TrueType fonts in the PDF.
render.Settings.EmbedFonts = true;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Embedding font subset in Word to PDF conversion


Embedding font subset in Word to PDF conversion

Embed complete font

Let’s embed the entire TrueType font used in the document to ensure consistent content display, regardless of whether the font is installed on the system.

Refer to the following code example.

DocIORenderer render = new DocIORenderer();
//Set to true to embed the complete TrueType fonts in the PDF.
render.Settings.EmbedCompleteFonts = true;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Embedding complete font in Word to PDF conversion


Embedding complete font in Word to PDF conversion

Accessible PDF document(PDF/UA)

Preserving structured tags is essential for PDFs to comply with accessibility standards (such as 508 compliance). This enables users with visual impairments to navigate the document using a screen.

To generate an accessible PDF with structured tags, enable the AutoTag setting during the conversion process.

Refer to the following code example.

DocIORenderer render = new DocIORenderer();
//Enable this flag to generate an accessible PDF with structured tags.
render.Settings.AutoTag = true;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Accessible PDF document (PDF/UA)


Accessible PDF document (PDF/UA)

PDF conformance level (PDF/A)

Suppose your PDF needs to comply with specific standards, such as PDF/A, for long-term archiving. In that case, setting the conformance level ensures the document meets the required industry standards for preservation and access.

To set the conformance level, assign the appropriate level to the PdfConformanceLevel property during Word to PDF conversion.

DocIORenderer render = new DocIORenderer();
//Set the conformance for PDF/A-3a conversion.
render.Settings.PdfConformanceLevel = PdfConformanceLevel.Pdf_A3A;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Setting PDF conformance level (PDF/A) in Word to PDF conversion


Setting PDF conformance level (PDF/A) in Word to PDF conversion

Editable PDF form fields

When converting forms from Word to PDF, you may want to preserve their interactivity. This setting ensures that form fields, such as checkboxes, text fields, and dropdowns, remain editable in the resulting PDF. It’s ideal for generating fillable PDFs from Word documents.

To keep form fields editable in the PDF, set the PreserveFormFields property to true, as shown in the following code example.

DocIORenderer render = new DocIORenderer();
//Set to true to preserve Word document form fields as editable PDF form fields.
render.Settings.PreserveFormFields = true;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Preserving editable PDF form fields in Word to PDF conversion


Preserving editable PDF form fields in Word to PDF conversion

Convert Word document headings to PDF bookmarks

Converting Word document headings into PDF bookmarks enhances navigation for lengthy reports or manuals. This feature is especially helpful in creating interactive PDFs, allowing users to quickly jump to specific sections by clicking on the bookmarks.

Refer to the following code example to convert Word document headings to PDF bookmarks.

DocIORenderer render = new DocIORenderer();
//Set ExportBookmarks to preserve Word document headings as PDF bookmarks.
render.Settings.ExportBookmarks = Syncfusion.DocIO.ExportBookmarkType.Headings;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Converting Word document headings to PDF bookmarks


Converting Word document headings to PDF bookmarks

Optimize identical images

In documents with repeated images (like logos), optimizing identical images reduces memory usage, improving performance during PDF conversion without compromising image quality.

Refer to the following code example.

DocIORenderer render = new DocIORenderer();
//Set true to optimize the memory usage for identical images.
render.Settings.OptimizeIdenticalImages = true;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Reducing file size by optimizing identical images in Word to PDF conversion


Reducing file size by optimizing identical images in Word to PDF conversion

Disable alternate chunks

Word documents containing embedded Word files (alternate chunks) need this setting to ensure that embedded content is also preserved in the converted PDF.

Refer to the following code example.

DocIORenderer render = new DocIORenderer();
//Set to false to disable the conversion of alternate chunks in the Word document to PDF.
render.Settings.EnableAlternateChunks = false;
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Disabling alternate chunks in Word to PDF conversion


Disabling alternate chunks in Word to PDF conversion

Complex script text handling

Preserving the script ensures the correct rendering of characters and text direction for multilingual documents, especially those written in languages that use complex scripts (e.g., Arabic and Hebrew).

Refer to the following code example.

DocIORenderer renderer = new DocIORenderer();

// Set the AutoDetectComplexScript property to true to automatically detect complex scripts.
renderer.Settings.PreserveComplexScriptText = true;

PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Preserving complex script text in Word to PDF conversion


Preserving complex script text in Word to PDF conversion

Hyphenation in Word-to-PDF conversion

When converting justified text with long words, hyphenation helps maintain the text’s alignment without creating awkward spaces. This setting enables hyphenation based on the document’s language dictionary.

Refer to the following code example.

//Instantiates DocIORenderer instance for Word to PDF conversion
DocIORenderer renderer = new DocIORenderer();
//Reads the language dictionary for hyphenation
FileStream dictionaryStream = new FileStream("hyphen_en_US.dic", FileMode.Open);
//Adds the hyphenation dictionary of the specified language
Hyphenator.Dictionaries.Add("en-US", dictionaryStream);
//Convert Word document into PDF document
PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Hyphenation in Word to PDF conversion


Hyphenation in Word to PDF conversion

Track changes in Word-to-PDF conversion

For collaborative documents, preserving track changes helps reviewers see revisions and suggestions, which is essential for document review and approval.

Refer to the following code example.

// Open the file as Stream
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    // Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        // Set revision types to preserve track changes in Word when converting to PDF.
        wordDocument.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;

        // Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            // Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                // Save the PDF file to the file system.    
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Preserving track changes in Word to PDF conversion


Preserving track changes in Word to PDF conversion

Change the track changes color

In collaborative documents, distinguishing different types of revisions (insertions, deletions, and formatting changes) through color coding makes it easier to track and analyze modifications. Customizing colors helps reviewers quickly identify changes.

You can customize the colors used to mark revisions in a Word document before converting it to PDF.

Refer to the following code example.

//Open the Word document file stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    //Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        //Set revision types to preserve track changes in Word when converting to PDF.
        wordDocument.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;
        //Set the color to be used for revision bars that identify document lines containing revised information.
        wordDocument.RevisionOptions.RevisionBarsColor = RevisionColor.Blue;
        //Set the color to be used for inserted content Insertion.
        wordDocument.RevisionOptions.InsertedTextColor = RevisionColor.ClassicBlue;
        //Set the color to be used for deleted content Deletion.
        wordDocument.RevisionOptions.DeletedTextColor = RevisionColor.ClassicRed;
        //Set the color to be used for content with changes in formatting properties.
        wordDocument.RevisionOptions.RevisedPropertiesColor = RevisionColor.DarkYellow;
        //Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            //Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                //Save the PDF file to the file system.    
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Customizing track changes color in Word to PDF conversion


Customizing track changes color in Word to PDF conversion

Show or hide revisions in balloons

When finalizing a document for sharing or printing, you may want to hide tracked changes in balloons to make the document look cleaner. This is particularly useful when preparing a finalized version for submission or review without showing the messy edits.

By setting the appropriate option, you can hide tracked changes in balloons while converting a Word document to a PDF.

Refer to the following code example.

// Open the Word document file stream.
using (FileStream inputStream = new FileStream(Path.GetFullPath("Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
    // Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        // Set revision options to preserve track changes (deletions, insertions, and formatting) when converting to PDF.
        wordDocument.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;

        // Disable showing revisions in balloons (will not be visible in the PDF).
        wordDocument.RevisionOptions.ShowInBalloons = RevisionType.None;

        // Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            // Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                // Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
} 
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Hiding revisions in balloons in Word to PDF conversion


Hiding revisions in balloons in Word to PDF conversion

Comments in Word-to-PDF conversion

If your Word document contains comments, such as feedback or annotations, you can retain them in the PDF for further review or collaboration.

Refer to the following code example.

// Open the Word document file stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    // Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        // Set the display mode for document comments to be shown in balloons.
        wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons;

        // Set the color to be used for comment balloons in PDF.
        wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue;

        // Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            // Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                // Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Preserving comments in Word to PDF conversion


Preserving comments in Word to PDF conversion

Restrict permissions in a PDF document

For sensitive documents, restricting permissions ensures that users cannot print, copy, or modify the PDF. This is useful for securing confidential or proprietary information.

Refer to the following code example to convert a Word document into a PDF and apply security settings to restrict permissions, including printing and copying.

//Instantiation of DocIORenderer for Word to PDF conversion
DocIORenderer render = new DocIORenderer();
//Convert Word document into PDF document
PdfDocument pdfDocument = render.ConvertToPDF(wordDocument);
//Set document security settings for the PDF.
PdfSecurity security = pdfDocument.Security;
//Set encryption to 256-bit AES for stronger protection.
security.KeySize = PdfEncryptionKeySize.Key256Bit;
security.Algorithm = Syncfusion.Pdf.Security.PdfEncryptionAlgorithm.AES;
//Set the owner password for the PDF.
security.OwnerPassword = "syncfusion";
//Restrict content actions such as printing and copying.
security.Permissions = ~(PdfPermissionsFlags.CopyContent | PdfPermissionsFlags.Print);

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Restricting permissions in a PDF document


Restricting permissions in a PDF document

Fallback Fonts

When converting Word documents to PDF, missing glyphs from the specified font can lead to improperly rendered text. To resolve this, the Word (DocIO) library allows users to specify fallback fonts. When the primary font does not contain the necessary glyph, the library automatically switches to a fallback font, ensuring the text is correctly rendered in the output PDF. This is particularly important for documents containing multilingual content or uncommon characters.

Users can configure fallback fonts in the following ways:

  • Initialize default fallback fonts.
  • Set custom fonts as a fallback for specific script types, including Arabic, Hebrew, Chinese, Japanese, and more.
  • Set custom fonts as fallback fonts for a particular range of Unicode text.

Initialize default fallback fonts

This option ensures that when specific fonts required for certain scripts are missing, the library uses pre-defined fallback fonts for these scripts. This method is useful for handling common scripts like Arabic, Hebrew, Chinese, and Japanese.

Refer to the following code example.

//Open the file as stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    //Load an existing Word document file stream.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        //Initialize the default fallback fonts collection.
        wordDocument.FontSettings.FallbackFonts.InitializeDefault();
        //Instantiation of DocIORenderer for Word to PDF conversion.
        using (DocIORenderer render = new DocIORenderer())
        {
            //Convert Word document into PDF document.
            using (PdfDocument pdfDocument = render.ConvertToPDF(wordDocument))
            {
                //Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }         
            }         
        }
    }   
}

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Default fallback fonts in Word to PDF conversion


Default fallback fonts in Word to PDF conversion

Fallback fonts based on script type

This method lets you set custom fallback fonts for specific script types. For example, if your document includes Arabic, Hebrew, or Chinese text, you can specify a fallback font for each of these scripts to ensure proper rendering if the primary font is unavailable.

Refer to the following code example.

//Open the file as stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    //Load an existing Word document file stream.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        //Add fallback font for the "Arabic" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Arabic, "Arial, Times New Roman");
        //Add fallback font for the "Hebrew" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Hebrew, "Arial, Courier New");
        //Add fallback font for the "Hindi" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Hindi, "Mangal, Nirmala UI");
        //Add fallback font for the "Chinese" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Chinese, "DengXian, MingLiU");
        //Add fallback font for the "Japanese" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Japanese, "Yu Mincho, MS Mincho");
        //Add fallback font for the "Thai" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Thai, "Tahoma, Microsoft Sans Serif");
        //Add fallback font for the "Korean" script type.
        wordDocument.FontSettings.FallbackFonts.Add(ScriptType.Korean, "Malgun Gothic, Batang");
        //Instantiation of DocIORenderer for Word to PDF conversion.
        using (DocIORenderer render = new DocIORenderer())
        {
            //Convert Word document into PDF document.
            using (PdfDocument pdfDocument = render.ConvertToPDF(wordDocument))
            {
                //Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }   
}

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Applying fallback fonts based on script type in Word to PDF conversion


Applying fallback fonts based on script type in Word to PDF conversion

Fallback fonts for a range of Unicode text

This option allows you to specify fallback fonts for a particular range of Unicode characters, ensuring that characters in specific languages or scripts are properly rendered. You can target specific Unicode ranges, such as, Arabic, Hindi, Chinese, or Japanese characters.

Refer to the following code example.

//Open the file as stream.
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    //Load an existing Word document file stream.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        //Add fallback font for "Arabic" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x0600, 0x06ff, "Arial"));
        //Add fallback font for "Hebrew" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x0590, 0x05ff, "Times New Roman"));
        //Add fallback font for "Hindi" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x0900, 0x097F, "Nirmala UI"));
        //Add fallback font for "Chinese" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x4E00, 0x9FFF, "DengXian"));
        //Add fallback font for "Japanese" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x3040, 0x309F, "MS Gothic"));
        //Add fallback font for "Thai" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0x0E00, 0x0E7F, "Tahoma"));
        //Add fallback font for "Korean" specific unicode range.
        wordDocument.FontSettings.FallbackFonts.Add(new FallbackFont(0xAC00, 0xD7A3, "Malgun Gothic"));
        //Instantiation of DocIORenderer for Word to PDF conversion.
        using (DocIORenderer render = new DocIORenderer())
        {
            //Convert Word document into PDF document.
            using (PdfDocument pdfDocument = render.ConvertToPDF(wordDocument))
            {
                //Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }   
}

Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Applying fallback fonts for a range of Unicode text in Word to PDF conversion


Applying fallback fonts for a range of Unicode text in Word to PDF conversion

Font substitution

When converting Word documents to PDF, the fonts used in the document must be installed on the machine. If the required fonts are missing, the DocIO library uses the default font, which may lead to discrepancies in the rendered PDF due to differences in font glyphs. This can cause layout and design issues, especially for documents relying on specific fonts.

To avoid this problem, the .NET Word Library allows you to specify alternate fonts to use when the original fonts are unavailable.

Use alternate fonts from installed fonts

In document automation, custom fonts in Word templates may not be installed on all production machines, causing layout issues in the generated PDFs.

By handling the SubstituteFont event in the .NET Word Library, users can substitute missing fonts with appropriate alternatives from the installed fonts. This ensures that the visual integrity of the document is preserved, even if the exact font is unavailable.

Refer to the following code example.

//Open the file as Stream
using (FileStream inputStream = new FileStream(Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    //Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        //Hook the font substitution event to handle unavailable fonts.
        //This event will be triggered when a font used in the document is not found in the production environment.
        wordDocument.FontSettings.SubstituteFont += FontSettings_SubstituteFont;
        //Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            //Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                //Unhook the font substitution event after the conversion is complete.
                wordDocument.FontSettings.SubstituteFont -= FontSettings_SubstituteFont;
                //Save the PDF file to file system.    
                using (FileStream outputStream = new FileStream(Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The FontSettings_SubstituteFont event handler is triggered whenever a font used in the Word document is not available during the PDF conversion. In this handler:

  • If the original font is Arial Unicode MS, it is substituted with Arial.
  • If any other font is missing, it is substituted with Times New Roman.

Refer to the following code example.

private static void FontSettings_SubstituteFont(object sender, SubstituteFontEventArgs args) 

{ 

 //Check if the original font is "Arial Unicode MS" and substitute it with "Arial". 

    if (args.OriginalFontName == "Arial Unicode MS") 

        args.AlternateFontName = "Arial"; 

    else 

        //Subsitutue "Times New Roman" for any other missing fonts. 

        args.AlternateFontName = "Times New Roman"; 
} 
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Using alternate fonts from installed fonts in Word to PDF conversion


Using alternate fonts from installed fonts in Word to PDF conversion

Use alternate fonts without installing

In scenarios where there is no permission to install fonts on production machines, such as in secure enterprise environments, the .NET Word Library offers a solution. Instead of installing custom fonts, you can provide font streams directly through the SubstituteFont event. This is especially useful for handling proprietary or non-standard fonts during Word-to-PDF conversion.

By hooking into the SubstituteFont event, you can ensure that missing fonts are replaced with the appropriate alternative fonts from streams, maintaining the document’s appearance without requiring font installation.

Refer to the following code example.

// Open the file as Stream
using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.ReadWrite))
{
    // Load an existing Word document.
    using (WordDocument wordDocument = new WordDocument(inputStream, FormatType.Docx))
    {
        // Hook the font substitution event to handle unavailable fonts.
        // This event will be triggered when a font used in the document is not found in the production environment.
        wordDocument.FontSettings.SubstituteFont += FontSettings_SubstituteFont;

        // Create an instance of DocIORenderer.
        using (DocIORenderer renderer = new DocIORenderer())
        {
            // Convert Word document into PDF document.
            using (PdfDocument pdfDocument = renderer.ConvertToPDF(wordDocument))
            {
                // Unhook the font substitution event after the conversion is complete.
                wordDocument.FontSettings.SubstituteFont -= FontSettings_SubstituteFont;

                // Save the PDF file to the file system.
                using (FileStream outputStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.ReadWrite))
                {
                    pdfDocument.Save(outputStream);
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this method, when the Arial Unicode MS font is missing in a Word document, an appropriate alternate font is substituted. Depending on the font style (Italic, Bold, or Regular), a corresponding font file (e.g., Arial_italic.TTF, Arial_bold.TTF, or Arial.TTF ) is provided via a file stream.

Refer to the following code example.

private static void FontSettings_SubstituteFont(object sender, SubstituteFontEventArgs args)
{
    // Check if the original font is "Arial Unicode MS" and substitute it with "Arial".
    if (args.OriginalFontName == "Arial Unicode MS")
    {
        switch (args.FontStyle)
        {
            case FontStyle.Italic:
                args.AlternateFontStream = new FileStream(Path.GetFullPath(@"Data/Arial_italic.TTF"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                break;

            case FontStyle.Bold:
                args.AlternateFontStream = new FileStream(Path.GetFullPath(@"Data/Arial_bold.TTF"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                break;

            default:
                args.AlternateFontStream = new FileStream(Path.GetFullPath(@"Data/Arial.TTF"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                break;
        }
    }
} 
Enter fullscreen mode Exit fullscreen mode

Refer to the following image.

Using alternate fonts without installation in Word to PDF conversion


Using alternate fonts without installation in Word to PDF conversion

GitHub reference

You can find all the examples for converting Word document to PDF with advanced options using the .NET Word Library in the GitHub repository.

Conclusion

Thanks for reading! Syncfusion .NET Word Library offers customizable settings to fine-tune the Word to PDF conversion process, allowing you to optimize performance, enhance accessibility, and preserve document fidelity across platforms. Whether you’re working with Word documents on any .NET platform, the Word to PDF converter simplifies the process for .NET developers.

Take a moment to peruse the Word to PDF conversion documentation, where you can find other options and features, all with code examples. You can convert an existing Word document or create a one from scratch, perform mail merge using the DocIO library, and then convert it to a PDF as required. If you are new to our DocIO library, it is highly recommended to follow our getting started guide.

Are you already a Syncfusion user? You can download the product setup here. If you’re not yet a Syncfusion user, you can download a 30-day free trial.

If you have questions, contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Related Blogs

Top comments (0)