How to Convert Word (DOC or DOCX) to PDF in C# .NET

convert word to pdf in c#

Converting Word documents to PDF is a common requirement in many C# applications, but relying on Microsoft Office Interop can be cumbersome and inefficient. Fortunately, third-party libraries like Spire.Doc for .NET provide a powerful and seamless alternative for high-quality conversions without Interop dependencies. Whether you need to preserve formatting, secure PDFs with passwords, or optimize file size, Spire.Doc offers a flexible solution with minimal code.

In this guide, we’ll explore how to convert Word to PDF in C# using Spire.Doc, covering basic conversions, advanced customization, and best practices for optimal results.

C# .NET Library for Converting Word to PDF

Spire.Doc for .NET is a robust API that enables developers to create, edit, and convert Word documents programmatically. It supports converting Word (DOC, DOCX) to PDF while preserving formatting, images, hyperlinks, and other elements.

With Spire.Doc, you can benefit from:

  • High-fidelity conversion with minimal formatting loss
  • Support for password-protected PDFs
  • Customizable PDF settings (PDF/A compliance, font embedding, etc.)
  • Batch conversion of multiple Word files

To get started, download Spire.Doc from the official website and reference the DLLs in your project. Or, you can install it via NuGet through the following command:

PM> Install-Package Spire.Doc

Simple Steps to Convert DOCX to PDF in C#

Converting Word documents to PDFs with default settings is remarkably straightforward. The example below shows how to load a DOCX file and save it as a PDF:

  • 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\\Input.docx");

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

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

Result:

Comparsion of the input Word file and the ouput PDF file generated from Word.

Advanced Word to PDF Conversion Options

To gain greater control over the conversion process, Spire.Doc offers the ToPdfParameterList class. With this class, you can:

  • Convert to PDF/A (a standardized archival format)
  • Apply password protection and permission restrictions
  • Embed fonts to ensure consistent rendering
  • Preserve bookmarks for better navigation
  • Disable hyperlinks if necessary

Here’s a summary of available options:

Option Implemented by
Convert to PDF/A PdfConformanceLevel
Protect PDF with a passoword PdfSecurity
Restrict permessions (e.g., printing) PdfSecurity
Embed all fonts IsEmbeddedAllFonts
Embed specific fonts EmbeddedFontNameList
Preserve bookmarks CreateWordsBookmarks
Create bookmarks from headings CreateWordBookmarksUsingHeadings
Disable hyperlinks DisableLink

Example 1: Convert Word to Password-Protected PDF

The following code encrypts the output PDF using an open password, ensuring that the document is protected from unauthorized access:

  • 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\\Input.docx");

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

            // Set an open password
            parameters.PdfSecurity.Encrypt("openPsd");

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

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

Example 2: Embed Fonts in PDF Generated from Word

The following code embeds all fonts used in a Word document into the generated PDF, ensuring that the document maintains its intended appearance regardless of the viewer's system fonts:

  • 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();
        }
    }
}

Adjust Word Documents for Optimal Conversion

To achieve the best PDF output, you may need to prepare your Word document before conversion. Consider the following adjustments:

Example: Reduce PDF Size by Compressing Images

The following code reduces image quality to 50%, resulting in a smaller PDF:

  • C#
using Spire.Doc;

namespace SetImageQualityWhenConverting
{
    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\\Input.docx");

            // Reduce image quality to 50%
            doc.JPEGQuality = 50;

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

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

Conclusion

Converting Word documents to PDF in C# doesn’t have to be complicated—Spire.Doc for .NET simplifies the process and offers extensive customization options, from basic conversions to advanced features like PDF encryption, font embedding, and image compression, all without Interop.

By following the techniques outlined in this guide, you can efficiently integrate Word-to-PDF functionality into your applications. For further assistance, explore Spire.Doc’s documentation or leverage its free trial to test its capabilities.

FAQs

Q1: How do I convert multiple Word files to PDFs in C#?

A: You can create a loop in your code to process multiple files at once. For example:

  • C#
string[] files = Directory.GetFiles("input_folder", "*.docx");
foreach (string file in files)
{
    Document document = new Document();
    document.LoadFromFile(file);
    document.SaveToPDF(Path.ChangeExtension(file, ".pdf"), FileFormat.PDF);
    document.Dispose();
}

Q2: How to merge multiple Word files into a single PDF?

A: You can merge Word files first (using Spire.Doc), and then convert the combined document to PDF. For example:

  • C#
Document mergedDoc = new Document();
string[] filesToMerge = Directory.GetFiles("input_folder ", "*.docx");
foreach (string file in filesToMerge)
{
    mergedDoc.InsertTextFromFile(file, FileFormat.Docx);
}
mergedDoc.SaveToFile("Merged.pdf", FileFormat.PDF);
mergedDoc.Dispose();

Q3: Why is my converted PDF missing text or formatting?

A: This issue may arise from missing custom fonts on your system. To resolve it, install the required fonts on the machine performing the conversion. Alternatively, you can embed the fonts directly into the PDF using Spire.Doc during the conversion process.

Q4: Is Spire.Doc free for Word-to-PDF conversion?

A: No, Spire.Doc is a paid library. However, a free version is available with limited functionality, allowing users to convert only the first three pages of a Word document to PDF. This option is ideal for small projects or personal use.

Get a Free License

To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.