C# CAD批量转换为图片 - Nightroad

时间:2024-01-30 07:50:38

C# CAD批量转换为图片

最近写了个工具,将指定目录下的CAD文件批量转换为图片格式。

首先需要添加对应的引用 :

在AutoCAD2008的环境下对应AutoCAD 2008 Type Library 和 AutoCAD/ObjectDBX  Common 17.0 Type Library 这两个引用,

笔者由于是AutoCAD2010,只找到了AutoCAD 2010 Type Library 没能找到第二个,百度后得知添加对文件“C:\Program Files\Common Files\Autodesk Shared\axdb18enu.tlb”的引用就可以了。

初始化AutoCAD,根据版本不同对应的ProgramID也不相同:

 1 private static AcadApplication _app = null; 

 1 #region 初始化CAD程序
 2 #region CAD ProgramID对照表
 3 //AutoCAD 2004
 4 //R16
 5 //AutoCAD.Application.16
 6 //AutoCAD 200
 7 //R16.
 8 //AutoCAD.Application.16.
 9 //AutoCAD 2006
10 //R16.
11 //AutoCAD.Application.16.
12 //AutoCAD 2007
13 //R17
14 //AutoCAD.Application.17
15 //AutoCAD 2008
16 //R17.
17 //AutoCAD.Application.17.
18 //AutoCAD 2009
19 //R17.
20 //AutoCAD.Application.17.
21 //AutoCAD 2010
22 //R18
23 //AutoCAD.Application.18
24 //AutoCAD 20
25 //R18.
26 //AutoCAD.Application.18.
27 #endregion
28 string programID = "AutoCAD.Application.18.0";
29 try
30 {
31     //如果CAD已经打开,就直接获取  
32     _app = (AcadApplication)Marshal.GetActiveObject(programID);
33 }
34 catch
35 {
36     try
37     {
38         //创建新的实例  
39         _app = (AcadApplication)new AcadDocument().Application;
40     }
41     catch (Exception ex)
42     {
43         return;
44     }
45 }
46 #endregion

然后加载CAD文件并转换为图片格式,转换完成后需要关闭对应的CAD文件释放占用:

 1 AcadDocument doc = null;
 2 string destPath = string.Empty;
 3 try
 4 {
 5     doc = _app.Documents.Open(pFile.FullName, true);
 6     doc.SetVariable("sdi", 0);
 7     doc.SetVariable("Filedia", 0);
 8     doc.SetVariable("RASTERPREVIEW", 1);
 9     doc.SetVariable("BACKGROUNDPLOT", 0);
10     doc.ActiveLayout.ConfigName = "PublishToWeb JPG.pc3";
11     doc.ActiveLayout.UseStandardScale = true;
12     doc.ActiveLayout.StandardScale = AcPlotScale.acScaleToFit;
13     doc.ActiveLayout.PlotType = AcPlotType.acExtents;
14     doc.ActiveLayout.CenterPlot = true;
15     doc.ActiveLayout.PlotRotation = AcPlotRotation.ac0degrees;
16     doc.ActiveLayout.PlotType = Autodesk.AutoCAD.Interop.Common.AcPlotType.acExtents;
17     doc.Plot.QuietErrorMode = true;
18     destPath = Path.Combine(pFile.Directory.FullName, Path.GetFileNameWithoutExtension(pFile.Name) + ".jpg");
19     doc.Plot.PlotToFile(destPath, "PublishToWeb JPG.pc3");
20 
21 }
22 catch (System.Exception e)
23 {
24     return false;
25 }
26 finally
27 {
28     if (doc != null) doc.Close(false);
29 }

在全部处理完成后需要关闭CAD应用:

#region 关闭CAD程序
try
{
    _app.Quit();
}
catch (Exception ex)
{
    return;
}
#endregion