在本分步指南中,我们将了解如何在 C# 中从 DXF 文件中提取文本。 C# 中的 DXF 到 TXT 转换可以通过从各种类型的实体中提取文本来轻松完成。在本教程中,我们仅从 CadText 实体中提取文本。但是,该过程对于其他实体也是相同的。
在 C# 中从 DXF 文件中提取文本的步骤
- 从 NuGet.org 获取 Aspose.CAD for .NET 包
- 在运行代码之前包含所需的命名空间
- 使用 SetLicense 方法设置 Aspose 许可证
- 使用 Image 类加载 DXF 文件
- 将对象转换为 CadImage 类型
- 遍历所有实体以获取文本
- 检查 CadText 实体类型并获取 DefaultValue 属性
- 最后,将提取的文本输出保存为 TXT 文件
在 DXF CAD 图形格式中,文本仅存储在实体内部;例如 CadText、CadMText、CadInsertObject、CadAttDef 或 CadAttrib 等。因此要提取文本,您需要首先获取每个实体,然后从中检索文本。为简单起见,我们在本教程中从 CadText 实体中提取文本。但是您可以对其他类型的实体使用相同的方法和代码,只需将对象转换为特定的实体类型。
在 C# 中从 DXF 文件中提取文本的代码
using System; | |
using System.IO; | |
//Add reference to Aspose.CAD for .NET API | |
//Use following namespaces to extract text from DXF file | |
using Aspose.CAD; | |
using Aspose.CAD.FileFormats.Cad; | |
using Aspose.CAD.FileFormats.Cad.CadObjects; | |
using Aspose.CAD.FileFormats.Cad.CadConsts; | |
namespace ExtractTextFromDXFFile | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before extracting text from DXF file format | |
//using Aspose.CAD for .NET | |
Aspose.CAD.License AsposeCADLicense = new Aspose.CAD.License(); | |
AsposeCADLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
CadImage DXFCADImagFile = (CadImage) Image.Load("InputDXFCADImagingFile.dxf"); | |
//string to store extracted text from the DXF file | |
string TextExtractedFromDXFFile = ""; | |
// Search for text in the entities section | |
foreach (CadBaseEntity CadEntity in DXFCADImagFile.Entities) | |
{ | |
if (CadEntity.TypeName == CadEntityTypeName.TEXT) | |
{ | |
CadText CadTextObject = (CadText)CadEntity; | |
TextExtractedFromDXFFile += CadTextObject.DefaultValue; | |
} | |
} | |
//Save the text extracted from DXF file using File Stream | |
FileStream FStream = new FileStream("ExtractTextFromDXFFormat.txt", FileMode.Create); | |
StreamWriter SWriter = new StreamWriter(FStream); | |
//Write extracted text to the file | |
SWriter.WriteLine(TextExtractedFromDXFFile); | |
SWriter.Flush(); | |
//Close file objects | |
SWriter.Close(); | |
FStream.Close(); | |
} | |
} | |
} |
在上述从 DXF 文件格式中提取文本的 C# 代码示例中,我们将提取的文本保存在字符串变量中,最后使用文件流将所有提取的文本保存在 TXT 文件中。在从 CAD file formats 提取文本的整个过程中,您不需要在系统上安装 AutoCAD,并且该 API 在任何 C# 应用程序(包括 Web、桌面和 ASP.NET 等)中都可以在没有 AutoCAD 的情况下工作。