使用 IRONWORD 如何在 C# 中将 Word 转换为 PDF Jordi Bardia 已更新:八月 31, 2025 Download IronWord NuGet 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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#. Prerequisites 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: Microsoft Word Installation 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. Visual Studio 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. Install package 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. Word Document for Conversion 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. Sufficient Permissions 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. Setting Up the Environment Open your Visual Studio. Create a new C# Console Application. Go to NuGet Package Manager > Manage NuGet Packages for Solution. Search for "Microsoft.Office.Interop.Word" and install it. This package will allow our application to communicate with Word and convert Word files. Sample Code to Convert Word Document to PDF 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 $vbLabelText $csharpLabel Code Explanation 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. Word to PDF C# Using IronPDF and IronWord If you're building a .NET application that involves document automation, one common task you'll face is converting Word documents to PDF format. Whether you're working with .docx document templates, invoices, reports, or contracts, converting DOCX files to PDF ensures consistent formatting, secure delivery, and cross-platform compatibility. This article explains how to easily convert Word to PDF using two powerful tools from IronSoftware: IronPDF and IronWord. You'll learn how they differ, when to use each tool, and how to implement them in C# for fast, reliable Word to PDF generation. Why Convert Word to PDF in .NET? Before we dive into how you can use these libraries to achieve this task, let's first take a look at why exactly converting your Word documents to PDF can elevate your workspace and documents. So why should you convert DOCX files to PDF format? It ensures visual consistency across various platforms Locks formatting and prevents unintentional edits It's ideal for archiving legal or financial documents It makes it easier to print and share your files It is often the required format for many business workflows Overview of the Tools: IronPDF and IronWord IronWord IronWord is a .NET library purpose-built for reading and editing Word documents. With IronWord, you can load .docx documents directly edit them to fit your needs, no need for Microsoft Office Interop or Microsoft Word installations, before using IronPDF to handle the DOCX to PDF conversion. Let's now take a look at IronWord in action, by creating a new document object and adding text to it: using IronWord; using IronWord.Models; using IronWord.Models.Abstract; WordDocument doc = new WordDocument(); TextContent text = new TextContent("This is some example text."); text.Style = new TextStyle() { Color = Color.Red, TextFont = new Font() { FontFamily = "Roboto", FontSize = 72, } }; doc.AddText(text); doc.Save("example.docx"); using IronWord; using IronWord.Models; using IronWord.Models.Abstract; WordDocument doc = new WordDocument(); TextContent text = new TextContent("This is some example text."); text.Style = new TextStyle() { Color = Color.Red, TextFont = new Font() { FontFamily = "Roboto", FontSize = 72, } }; doc.AddText(text); doc.Save("example.docx"); Imports IronWord Imports IronWord.Models Imports IronWord.Models.Abstract Private doc As New WordDocument() Private text As New TextContent("This is some example text.") text.Style = New TextStyle() With { .Color = Color.Red, .TextFont = New Font() With { .FontFamily = "Roboto", .FontSize = 72 } } doc.AddText(text) doc.Save("example.docx") $vbLabelText $csharpLabel Output Word document IronPDF IronPDF is a full-featured PDF library for .NET, packed full of tools for PDF generation and manipulation. While one of it's crowning features is its high-quality HTML to PDF conversion capabilities, it is also capable of handling Word to PDF C# conversion tasks. For .NET developers looking to generate PDFs or edit existing PDF documents, IronPDF has you covered for all your needs. So just how easy is IronPDF to use? Let's look at the following code example to see how it works when converting Word documents to PDF: using IronPdf; var renderer = new DocxToPdfRenderer(); var pdf = renderer.RenderDocxAsPdf("sample.docx"); pdf.SaveAs("example.pdf"); using IronPdf; var renderer = new DocxToPdfRenderer(); var pdf = renderer.RenderDocxAsPdf("sample.docx"); pdf.SaveAs("example.pdf"); Imports IronPdf Private renderer = New DocxToPdfRenderer() Private pdf = renderer.RenderDocxAsPdf("sample.docx") pdf.SaveAs("example.pdf") $vbLabelText $csharpLabel PDF Output Combined Workflow: IronWord and IronPDF While IronWord cannot directly export to PDF, it's perfect for preparing Word documents programmatically. Here's a common flow: Word to PDF Pipeline in C# Load or create a Word document with IronWord Edit or fill in dynamic data (e.g. replace tokens) Save the .docx file Use IronPDF to convert the document to PDF format After, you can go on to use IronPDF to make any further adjustments to the newly rendered PDF, such as adding watermarks or annotations This hybrid workflow offers maximum flexibility with minimal dependencies, ideal for web apps, cloud services, and desktop applications alike. So how does this look in action? Using IronWord for Document Creation First we'll use IronWord to create an example Word document. using IronWord; using IronWord.Models; using IronWord.Models.Abstract; WordDocument doc = new WordDocument(); TextContent title = new TextContent("Example Report."); TextContent text = new TextContent("Report created using IronWord, you can use this to create dynamic text and tables."); title.Style = new TextStyle() { TextFont = new Font() { FontSize = 72 }, IsBold = true, }; Paragraph paragraph = new Paragraph(); paragraph.AddText(title); paragraph.AddText(text); doc.AddParagraph(paragraph); doc.Save("example.docx"); using IronWord; using IronWord.Models; using IronWord.Models.Abstract; WordDocument doc = new WordDocument(); TextContent title = new TextContent("Example Report."); TextContent text = new TextContent("Report created using IronWord, you can use this to create dynamic text and tables."); title.Style = new TextStyle() { TextFont = new Font() { FontSize = 72 }, IsBold = true, }; Paragraph paragraph = new Paragraph(); paragraph.AddText(title); paragraph.AddText(text); doc.AddParagraph(paragraph); doc.Save("example.docx"); Imports IronWord Imports IronWord.Models Imports IronWord.Models.Abstract Private doc As New WordDocument() Private title As New TextContent("Example Report.") Private text As New TextContent("Report created using IronWord, you can use this to create dynamic text and tables.") title.Style = New TextStyle() With { .TextFont = New Font() With {.FontSize = 72}, .IsBold = True } Dim paragraph As New Paragraph() paragraph.AddText(title) paragraph.AddText(text) doc.AddParagraph(paragraph) doc.Save("example.docx") $vbLabelText $csharpLabel Output Using IronPDF for Word to PDF C# Conversion In just 3 simple lines of code, we'll be able to easily convert our Word document to PDF. using IronPdf; var renderer = new DocxToPdfRenderer(); var pdf = renderer.RenderDocxAsPdf("example.docx"); pdf.SaveAs("output.pdf"); using IronPdf; var renderer = new DocxToPdfRenderer(); var pdf = renderer.RenderDocxAsPdf("example.docx"); pdf.SaveAs("output.pdf"); Imports IronPdf Private renderer = New DocxToPdfRenderer() Private pdf = renderer.RenderDocxAsPdf("example.docx") pdf.SaveAs("output.pdf") $vbLabelText $csharpLabel Output Just like that, we were able to create a custom Word document with IronWord, before implementing IronPDF to convert it to PDF format in just a few lines of code. Deployment-Ready: Works Everywhere Both IronPDF and IronWord works in: ASP.NET Core and Blazor Azure App Services and Azure Functions Compatible with .NET framework, .NET 6, 7, 8, 9, and .NET Core Easily integrated into Linux, Docker, and server environments Desktop (WPF/WinForms) and console applications No Office install required. No COM interop. Just clean, modern .NET libraries. Common Use Cases Use Case IronWord IronPDF Load/edit .docx files Yes No Replace text/tokens in Word Yes No Save .docx documents Yes No Convert HTML to PDF No Yes Generate final PDF output No Yes Server-side rendering Yes Yes Pro Tip: Using Razor Views to Output Word-Like PDF documents Even if you're not using IronWord, IronPDF supports Razor templates directly. You can use Razor Pages to output Word-styled layouts with CSS, then render to PDF: @model InvoiceModel <html> <body> <h1>Invoice for @Model.CustomerName</h1> <p>Amount Due: @Model.TotalAmount</p> </body> </html> @model InvoiceModel <html> <body> <h1>Invoice for @Model.CustomerName</h1> <p>Amount Due: @Model.TotalAmount</p> </body> </html> 'INSTANT VB TODO TASK: The following line uses invalid syntax: '@model InvoiceModel <html> <body> <h1> Invoice for @Model.CustomerName</h1> <p> Amount Due: @Model.TotalAmount</p> </body> </html> $vbLabelText $csharpLabel IronPDF can render that into a polished, print-ready PDF. Summary: Unlock the Full Power of Word to PDF in .NET By including IronPDF and IronWord in your .NET projects, you get a powerful, Office-free workflow for handling documents in .NET. Create dynamic Word documents with custom styling and tables, or convert your documents into pixel-perfect PDF files. No matter the task, with these libraries you'll always have powerful tools for handling Word and PDF tasks at your fingertips. This pairing is perfect for generating invoices, reports, contracts, and any document that starts in Word but needs to end in a secure, consistent PDF format. Whether you're building desktop software or deploying to Azure, IronWord and IronPDF give you full control over document automation - fast, reliable, and production-ready. If you want to see more of these libraries in action, be sure to check out their documentation, where you can find plenty of code examples for both IronPDF and IronWord to learn more about their features and how they work. Get Started Today Install both libraries via the NuGet Package Manager to quickly implement them within your Visual Studio projects. Want to try before you buy? Download the free trial for IronPDF and IronWord today and start creating powerful documents right away. 常见问题解答 如何使用 C# 将 Word 文档转换为 PDF? 您可以使用 Microsoft.Office.Interop.Word 包在 C# 中将 Word 文档转换为 PDF。这涉及创建 Word 应用程序实例、加载文档并使用 ExportAsFixedFormat 方法将其保存为 PDF。 ExportAsFixedFormat 方法在 Word 转 PDF 转换中有什么作用? Microsoft.Office.Interop.Word 中的 ExportAsFixedFormat 方法用于将 Word 文档导出为 PDF 文件,提供适用于共享和打印的固定格式。 在 C# 中将 Word 文档转换为 PDF 的先决条件是什么? 要在 C# 中将 Word 文档转换为 PDF,您需要安装 Microsoft Word、Visual Studio,并通过 NuGet 包管理器提供 Microsoft.Office.Interop.Word 包。 为什么在转换后关闭 Word 应用程序很重要? 在转换后关闭 Word 应用程序对于释放系统资源和避免内存泄漏至关重要。确保应用程序不会在后台保持开启,从而消耗不必要的资源。 处理 Excel 文件比使用 Microsoft Interop 更高效的替代方法是什么? IronXL 是在 C# 中处理 Excel 文件的更高效替代方法。它无需安装 Microsoft Office,并提供更快的性能和广泛的支持文件格式。 如何为我的 C# 应用程序安装 IronXL 库? 要在 C# 应用程序中安装 IronXL,请使用 NuGet 包管理器控制台并执行命令 Install-Package IronXL.Excel。 IronXL 在处理 Excel 文件时可以处理哪些文件格式? IronXL 可以转换和处理多种格式的 Excel 文件,包括 XLS、XLSX、XLSM、CSV、TSV、JSON、XML、HTML 以及二进制和字节数组。 使用 IronXL 相对于 Microsoft Interop 服务的优势是什么? IronXL 提供了无需安装 Microsoft Office、处理速度更快、易于使用、支持更多文件格式等优势,优于 Microsoft Interop 服务。 Jordi Bardia 立即与工程团队聊天 软件工程师 Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。 相关文章 已更新九月 18, 2025 ASP .NET Core 导入和导出 Word 文件 本指南探讨了如何使用 IronWord 库导入现有的 Word 文档、显示其内容并从头创建文档 阅读更多 已更新七月 28, 2025 VS 2022 编程创建新 Word 文档 (教程) 在今天的教程中,我将简要解释如何使用 IronWord 编程创建 Microsoft Word 文档并提供简短示例。 阅读更多 已更新六月 22, 2025 如何使用 C# 在 Word 中对齐文本 深入了解 IronWord NuGet 包以及使用该包对齐文本或段落的方法 阅读更多 C# 编辑 Word(代码示例开发者教程)C# 打开 Word 文档
已更新七月 28, 2025 VS 2022 编程创建新 Word 文档 (教程) 在今天的教程中,我将简要解释如何使用 IronWord 编程创建 Microsoft Word 文档并提供简短示例。 阅读更多