To convert a Word document to PDF in C#, you have a few common options depending on your environment and libraries available:
1. Using Microsoft Office Interop (requires MS Word installed)
using Microsoft.Office.Interop.Word;
public void ConvertWordToPdf(string inputFile, string outputFile)
{
Application wordApp = new Application();
Document wordDoc = null;
try
{
wordDoc = wordApp.Documents.Open(inputFile);
wordDoc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF);
}
finally
{
if (wordDoc != null)
{
wordDoc.Close();
}
wordApp.Quit();
}
}
Notes:
- Requires Microsoft Word installed on the machine.
- Not recommended for server environments because Office Interop is a COM-based technology better suited for desktop use.
- Add a reference to
Microsoft.Office.Interop.Word.
2. Using Open XML + a third-party library (like DocX + PDF libraries)
Unfortunately, Open XML SDK cannot convert to PDF directly. You need third-party libraries.
3. Using a third-party library such as Aspose.Words
Aspose.Words is a commercial library that can convert DOC/DOCX to PDF easily.
using Aspose.Words;
public void ConvertWordToPdf(string inputFile, string outputFile)
{
Document doc = new Document(inputFile);
doc.Save(outputFile, SaveFormat.Pdf);
}
- Requires license (free trial available).
- Very reliable and no dependency on Microsoft Word.
4. Using Free Spire.Doc library
Spire.Doc has a free version with some limitations but supports Word to PDF conversion.
using Spire.Doc;
public void ConvertWordToPdf(string inputFile, string outputFile)
{
Document document = new Document();
document.LoadFromFile(inputFile);
document.SaveToFile(outputFile, Spire.Doc.FileFormat.PDF);
}
Summary
| Method | Requires MS Word? | Server friendly | Cost |
|---|
| Microsoft.Office.Interop.Word | Yes | No | Free |
| Aspose.Words | No | Yes | Commercial |
| Spire.Doc | No | Yes | Free/Commercial |
If you want a minimal example that works on a desktop with Word installed, use Microsoft Interop.
If you want server-side conversion without Word, try Aspose.Words or Spire.Doc.
Let me know if you want sample projects or help with any method!