使用 IRONWORD 如何在 C# 中將 Word 轉換為 PDF Jordi Bardia 更新日期:8月 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 文件,提供適合分享和列印的固定格式。 將 Word 文件轉換為 PDF 在 C# 中需要哪些前置條件? 在 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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。 相關文章 更新日期 9月 18, 2025 ASP .NET Core 導入和導出 Word 文件 本指南探討如何使用 IronWord 庫導入現有的 Word 文件,顯示其內容,並從頭開始創建文件 閱讀更多 更新日期 7月 28, 2025 VS 2022 程式化創建新 Word 文件(教程) 在今天的教程中,我將簡單解釋如何使用 IronWord 程式化創建 Microsoft Word 文檔,並提供簡單範例。 閱讀更多 更新日期 6月 22, 2025 如何使用 C# 對齊 Word 中的文本 讓我們深入了解 IronWord NuGet 包,了解如何使用此包對齊文本或段落 閱讀更多 C# 編輯 Word(代碼示例開發者教程)C# 開啟 Word 文檔
更新日期 7月 28, 2025 VS 2022 程式化創建新 Word 文件(教程) 在今天的教程中,我將簡單解釋如何使用 IronWord 程式化創建 Microsoft Word 文檔,並提供簡單範例。 閱讀更多