如何使用IronWord在 C# 中将 DOCX 转换为 PDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWord 通过其 ToPdf 方法实现无缝的 DOCX 到 PDF 转换,支持需要标准化 PDF 输出格式的自动化文档工作流、报告分发和归档流程。

快速入门:使用 C# 将 DOCX 转换为 PDF

使用 IronWord,通过单次方法调用即可加载 DOCX 文件并将其转换为 PDF。

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronWord

    PM > Install-Package IronWord
  2. 复制并运行这段代码。

    using IronWord;
    
    WordDocument doc = new WordDocument("report.docx");
    doc.ToPdf("report.pdf");
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronWord

    arrow pointer

如何将 DOCX 文件转换为 PDF?

ToPdf方法在处理所有PDF生成复杂性的同时,完整保留了文档的格式、图片、表格和文本样式。 将您的 DOCX 文件加载到 new WordDocument("file.docx") 中,调用 ToPdf() 并指定输出路径,转换将自动完成。

:path=/static-assets/word/content-code-examples/how-to/word-to-pdf-basic.cs
using IronWord;

// Load existing DOCX file
WordDocument doc = new WordDocument("input.docx");

// Convert to PDF
doc.ToPdf("output.pdf");
$vbLabelText   $csharpLabel

提示ToPdf 方法在转换过程中保持文档的完整原貌,包括字体、颜色、图像和布局。

这种方法适用于自动报告分发、发票生成或任何需要标准化 PDF 输出的工作流程。 转换后的 PDF 在所有平台和设备上的显示效果完全相同,因此非常适合用于官方文档、法律存档以及对外观一致性要求极高的客户交付物。


如何将多个 DOCX 文件转换为 PDF?

对于大批量文档处理,批量转换会自动处理整个目录。 使用 Directory.GetFiles() 检索所有 DOCX 文件,然后遍历每个文件并应用相同的转换方法。 使用 try-catch 块进行错误处理,可确保损坏的文件不会导致整个批处理操作停止。

:path=/static-assets/word/content-code-examples/how-to/word-to-pdf-batch.cs
using IronWord;
using System;
using System.IO;

// Get all DOCX files from input directory
string[] docxFiles = Directory.GetFiles("input-folder", "*.docx");

foreach (string filePath in docxFiles)
{
    try
    {
        // Load DOCX file
        WordDocument doc = new WordDocument(filePath);

        // Generate output PDF path
        string fileName = Path.GetFileNameWithoutExtension(filePath);
        string outputPath = $"output-folder/{fileName}.pdf";

        // Convert to PDF
        doc.ToPdf(outputPath);

        Console.WriteLine($"Converted: {fileName}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed: {Path.GetFileName(filePath)} - {ex.Message}");
    }
}
$vbLabelText   $csharpLabel

以上示例演示了使用控制台日志记录进行进度跟踪的实用批处理方法。 这种模式适用于归档迁移项目、自动化工作流管道或计划报告生成,在这些项目中,需要转换数百个 DOCX 文件而无需人工干预。

处理大批量数据时,转换前请验证源文件是否存在,并保持一致的输出命名约定。 考虑采用并行处理来提高性能,但要监控系统资源,以防止并发操作期间内存耗尽。

Ahmad Sohail
全栈开发者

Ahmad 是一名全栈开发人员,拥有扎实的 C#、Python 和 Web 技术基础。他对构建可扩展的软件解决方案深感兴趣,并喜欢探索设计和功能在实际应用中如何结合。

在加入 Iron Software 团队之前,Ahmad 致力于自动化项目和 API 集成,专注于提高性能和开发人员体验。

在业余时间,他喜欢尝试 UI/UX 想法,贡献开源工具,并偶尔从事技术写作和文档工作,以便让复杂主题更易于理解。

准备开始了吗?
Nuget 下载 36,374 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronWord
运行示例 观看您的数据变成 Word 文档。