Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Converting documents programmatically has become an essential feature in many applications. Especially in the business world, converting Word documents to PDF files is a routine task. Thankfully, with C# and Microsoft Interop, you can seamlessly convert Word files to PDF. This tutorial will discuss the process of converting Word to PDF programmatically using C#.
Before diving into the code to convert .DOCX to PDF using C#, ensuring you have the necessary environment set up is crucial. Below are the prerequisites you need:
Make sure you have Microsoft Word installed on your computer. The Interop services will use Word's built-in capabilities to handle the Word document and PDF conversion.
A version of Visual Studio is necessary for creating, compiling, and running the C# program. If you don't already have Visual Studio, you can download the community version, which is free, from Microsoft's official website.
Microsoft.Office.Interop.Word
This package is essential to provide the necessary functionalities for your C# program to interact with Word documents. It will be installed later using NuGet Package Manager, but knowing its importance in the conversion process is good.
Prepare a Word document or .docx
file that you'd like to convert. Ensure you know its path on your machine, as you'll need to specify it in the C# program.
Ensure you can read the Word file and write the resulting PDF file to the desired directory. Running Visual Studio as an administrator can sometimes resolve permission-related issues.
With these prerequisites, you can set up your environment and convert your Word documents to PDF files.
Microsoft.Office.Interop.Word
" and install it. This package will allow our application to communicate with Word and convert Word files.To convert a Word document to PDF using C#, we will employ the capabilities of Microsoft Interop services. The code snippet below accomplishes this task, and a detailed explanation follows.
using System;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
// Create an instance of Microsoft Word application
var wordApp = new Word.Application();
// Open the Word document
var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");
// Specify the path where the PDF should be saved
var outputPath = @"path_where_you_want_to_save_pdf.pdf";
// Convert the Word document to PDF
wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);
// Close the Word document and quit the Word application
wordDocument.Close();
wordApp.Quit();
// Output a success message
Console.WriteLine("Word document converted to PDF successfully!");
}
}
using System;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
// Create an instance of Microsoft Word application
var wordApp = new Word.Application();
// Open the Word document
var wordDocument = wordApp.Documents.Open(@"path_to_your_word_file.docx");
// Specify the path where the PDF should be saved
var outputPath = @"path_where_you_want_to_save_pdf.pdf";
// Convert the Word document to PDF
wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF);
// Close the Word document and quit the Word application
wordDocument.Close();
wordApp.Quit();
// Output a success message
Console.WriteLine("Word document converted to PDF successfully!");
}
}
Imports System
Imports Word = Microsoft.Office.Interop.Word
Friend Class Program
Shared Sub Main()
' Create an instance of Microsoft Word application
Dim wordApp = New Word.Application()
' Open the Word document
Dim wordDocument = wordApp.Documents.Open("path_to_your_word_file.docx")
' Specify the path where the PDF should be saved
Dim outputPath = "path_where_you_want_to_save_pdf.pdf"
' Convert the Word document to PDF
wordDocument.ExportAsFixedFormat(outputPath, Word.WdExportFormat.wdExportFormatPDF)
' Close the Word document and quit the Word application
wordDocument.Close()
wordApp.Quit()
' Output a success message
Console.WriteLine("Word document converted to PDF successfully!")
End Sub
End Class
The beginning of our code includes a crucial namespace alias Word
to refer to the Microsoft.Office.Interop.Word
namespace easily. The System
namespace provides classes fundamental to C# programming, and it's a staple in almost all C# applications.
The real action begins inside the Main
method. We first create a new instance of the Word application using new Word.Application()
. This step is akin to launching MS Word, but everything happens in the background, unseen by the user. Once the application instance is initialized, we instruct it to open a Word document with the wordApp.Documents.Open
method. Specifying the path to your Word document in place of "path_to_your_word_file.docx"
is crucial.
Now, having the document open, we determine where we want our PDF to be saved. This is specified in the outputPath
variable. It's essential to note that the path should be adjusted to where you'd like your converted output PDF file to reside.
The magic of converting the Word document to PDF happens with the line wordDocument.ExportAsFixedFormat(...)
. The Interop services provide a built-in method, enabling the conversion without hassle. The method takes two primary arguments: the path where the PDF should be saved and the export format, which in our case is PDF.
Following the conversion, closing resources we've used is good practice. Thus, wordDocument.Close()
ensures that the document we opened is now closed, while wordApp.Quit()
ensures that the instance of the Word application we launched in the background is terminated.
Lastly, our program communicates the result to the user with a simple console message. The Console.WriteLine()
method provides feedback, signaling that the conversion process was successfully executed.
Thus, Microsoft.Office.Interop.Word
provides a suitable solution to handle and convert Word documents.
While Microsoft.Office.Interop
provides a feasible solution for document conversion, there's a more efficient and robust alternative available to work with Excels: IronXL.
IronXL simplifies the process of handling Excel files in C#. Not only does it outperform Interop in terms of speed and ease of use, but it also requires no additional installations like Microsoft Office. Interested in exploring further? Check out their detailed tutorial on how to read Excel files using C#.
IronXL library can be installed using the following command in the NuGet Package Manager console:
Install-Package IronWord
using IronXL;
class ExcelConverter
{
static void Main()
{
// Load an Excel file into an IronXL WorkBook object
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Export the Excel file in various formats
workBook.SaveAs("sample.xls");
workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.tsv");
workBook.SaveAsCsv("sample.csv");
workBook.SaveAsJson("sample.json");
workBook.SaveAsXml("sample.xml");
// Export the Excel file as HTML
workBook.ExportToHtml("sample.html");
string htmlString = workBook.ExportToHtmlString();
// Export the Excel file as Binary, Byte array, Data set, Stream
byte[] binary = workBook.ToBinary();
byte[] byteArray = workBook.ToByteArray();
System.Data.DataSet dataSet = workBook.ToDataSet(); // Allow easy integration with DataGrids, SQL and EF
Stream stream = workBook.ToStream();
}
}
using IronXL;
class ExcelConverter
{
static void Main()
{
// Load an Excel file into an IronXL WorkBook object
WorkBook workBook = WorkBook.Load("sample.xlsx");
// Export the Excel file in various formats
workBook.SaveAs("sample.xls");
workBook.SaveAs("sample.xlsx");
workBook.SaveAs("sample.tsv");
workBook.SaveAsCsv("sample.csv");
workBook.SaveAsJson("sample.json");
workBook.SaveAsXml("sample.xml");
// Export the Excel file as HTML
workBook.ExportToHtml("sample.html");
string htmlString = workBook.ExportToHtmlString();
// Export the Excel file as Binary, Byte array, Data set, Stream
byte[] binary = workBook.ToBinary();
byte[] byteArray = workBook.ToByteArray();
System.Data.DataSet dataSet = workBook.ToDataSet(); // Allow easy integration with DataGrids, SQL and EF
Stream stream = workBook.ToStream();
}
}
Imports IronXL
Friend Class ExcelConverter
Shared Sub Main()
' Load an Excel file into an IronXL WorkBook object
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Export the Excel file in various formats
workBook.SaveAs("sample.xls")
workBook.SaveAs("sample.xlsx")
workBook.SaveAs("sample.tsv")
workBook.SaveAsCsv("sample.csv")
workBook.SaveAsJson("sample.json")
workBook.SaveAsXml("sample.xml")
' Export the Excel file as HTML
workBook.ExportToHtml("sample.html")
Dim htmlString As String = workBook.ExportToHtmlString()
' Export the Excel file as Binary, Byte array, Data set, Stream
Dim binary() As Byte = workBook.ToBinary()
Dim byteArray() As Byte = workBook.ToByteArray()
Dim dataSet As System.Data.DataSet = workBook.ToDataSet() ' Allow easy integration with DataGrids, SQL and EF
Dim stream As Stream = workBook.ToStream()
End Sub
End Class
As shown in the above sample code, the IronXL library helps to read Excel files without using Interop. You can further use the IronXL library to load your workbook and export it with SaveAs
method to different formats such as XLS, XLSX, XLSM, CSV, TSV, JSON, XML. It also allows for the export of data types like HTML strings, binaries, byte arrays, data sets, and memory streams directly in code.
In today's digital era, document conversions, especially Word documents to PDF, have become indispensable for many applications. One can achieve this using C# and the capabilities provided by Microsoft Interop.
However, staying updated with superior tools like IronXL is essential, which offers enhanced performance and simplifies the process. If you're considering trying out IronXL, they offer a free trial. Once you've experienced its prowess, the licensing starts from a reasonable $749, providing value for your investment and ensuring smooth document handling in your applications.
You need Microsoft Word installed, Visual Studio, the Microsoft.Office.Interop.Word package, a Word document for conversion, and sufficient permissions for reading and writing files.
Open Visual Studio, create a new C# Console Application, install the Microsoft.Office.Interop.Word package via NuGet Package Manager, and prepare your Word document for conversion.
Yes, the sample code involves creating a Word application instance, opening a Word document, specifying the PDF output path, exporting the document to PDF, and then closing the application.
Microsoft.Office.Interop.Word provides the necessary functionalities to interact with Word documents and convert them to PDF programmatically within a C# application.
IronXL is a library that simplifies handling Excel files in C#. Unlike Interop, it doesn't require Microsoft Office installation and offers faster performance and ease of use.
You can install IronXL using the command Install-Package IronXL.Excel in the NuGet Package Manager console.
IronXL can convert Excel files into various formats including XLS, XLSX, XLSM, CSV, TSV, JSON, XML, HTML, and others like binary and byte arrays.
A developer might choose IronXL for its speed, ease of use, no requirement for Microsoft Office installation, and its ability to handle a wider range of file formats.