在本操作指南中,您将学习使用 C#** 将 Word 文档转换为图像的完整过程。为了执行文档转换,我们将在本文中使用最好的文档转换 API 之一将 DOCX 转换为 PNG。本指南还提供了配置环境的说明和一个工作示例代码,以演示 C# Word to Image converter 应用程序的实现。以下是在 C# 中将 Word 文件转换为图像的关键步骤和代码片段。
使用 C# 将 Word 文档转换为图像的步骤
- 从 .NET 应用程序中的 NuGet 包管理器安装 GroupDocs.Conversion for .NET 包以将 Word 文档转换为图像
- 添加对 GroupDocs.Conversion 命名空间的引用以开发 Word 到图像的转换功能
- 创建 Converter 类的实例以加载输入 Word 文件
- 创建 ImageConvertOptions 类的对象,用于定义输出 PNG 文件的转换选项
- 最后,调用 Convert 方法从 Word 生成图像并将其存储在磁盘上
通过按顺序使用上述步骤,可以快速创建 Word to Image C# 应用程序。可以通过从 NuGet 网站配置所需的包并在代码中添加必要的命名空间来启动文档转换过程。之后,您需要通过初始化 Converter 类来加载输入的 Word 文件,并创建 ImageConvertOptions 类的实例,用于定义自定义转换后的图像文件的各种参数。最后,Convert 方法将用于执行转换为所需格式并将转换后的文件保存到磁盘。
使用 C# 将 Word 文档转换为图像的代码
using System; | |
using GroupDocs.Conversion.Options.Convert; | |
namespace ConvertWordDocumentToImageUsingCSharp | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) // Main function to convert Word document to Image using C# | |
{ | |
// Remove the watermark in output Image document by adding license | |
string licensePath = "GroupDocs.Conversion.lic"; | |
GroupDocs.Conversion.License lic = new GroupDocs.Conversion.License(); | |
lic.SetLicense(licensePath); | |
// Load the source Word file for conversion to Image | |
var converter = new GroupDocs.Conversion.Converter("sample.docx"); | |
// Set the conversion options for Image document to customize the output file | |
ImageConvertOptions options = new ImageConvertOptions(); | |
options.PageNumber = 1; | |
options.PagesCount = 1; | |
// Convert and save the DOCX in PNG format | |
converter.Convert("converted.png", options); | |
Console.WriteLine("Done"); | |
} | |
} | |
} |
在前面的代码片段中,我们开发了代码来实现本教程的 C# Word to Image 功能。文档转换通过几行代码完成,并使用文档转换库的一些 API 调用。此外,此示例代码不依赖任何其他软件。此外,您可以在任何常见操作系统上使用此示例,包括 Windows、macOS 和 Linux。
我们已经讨论了使用 C# 将 word 转换为 PNG 的文档转换过程,并为其开发了一个示例。最近,我们发表了一篇使用 C# 将 Word 文档转换为文本的文章,请查看 如何在 C# 中将 Word 文档转换为文本 指南了解更多信息。