最近写了个工具,将指定目录下的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也不相同:
private static AcadApplication _app = null;
#region 初始化CAD程序
#region CAD ProgramID对照表
//AutoCAD 2004
//R16
//AutoCAD.Application.16
//AutoCAD 200
//R16.
//AutoCAD.Application.16.
//AutoCAD 2006
//R16.
//AutoCAD.Application.16.
//AutoCAD 2007
//R17
//AutoCAD.Application.17
//AutoCAD 2008
//R17.
//AutoCAD.Application.17.
//AutoCAD 2009
//R17.
//AutoCAD.Application.17.
//AutoCAD 2010
//R18
//AutoCAD.Application.18
//AutoCAD 20
//R18.
//AutoCAD.Application.18.
#endregion
string programID = "AutoCAD.Application.18.0";
try
{
//如果CAD已经打开,就直接获取
_app = (AcadApplication)Marshal.GetActiveObject(programID);
}
catch
{
try
{
//创建新的实例
_app = (AcadApplication)new AcadDocument().Application;
}
catch (Exception ex)
{
return;
}
}
#endregion
然后加载CAD文件并转换为图片格式,转换完成后需要关闭对应的CAD文件释放占用:
AcadDocument doc = null;
string destPath = string.Empty;
try
{
doc = _app.Documents.Open(pFile.FullName, true);
doc.SetVariable("sdi", );
doc.SetVariable("Filedia", );
doc.SetVariable("RASTERPREVIEW", );
doc.SetVariable("BACKGROUNDPLOT", );
doc.ActiveLayout.ConfigName = "PublishToWeb JPG.pc3";
doc.ActiveLayout.UseStandardScale = true;
doc.ActiveLayout.StandardScale = AcPlotScale.acScaleToFit;
doc.ActiveLayout.PlotType = AcPlotType.acExtents;
doc.ActiveLayout.CenterPlot = true;
doc.ActiveLayout.PlotRotation = AcPlotRotation.ac0degrees;
doc.ActiveLayout.PlotType = Autodesk.AutoCAD.Interop.Common.AcPlotType.acExtents;
doc.Plot.QuietErrorMode = true;
destPath = Path.Combine(pFile.Directory.FullName, Path.GetFileNameWithoutExtension(pFile.Name) + ".jpg");
doc.Plot.PlotToFile(destPath, "PublishToWeb JPG.pc3"); }
catch (System.Exception e)
{
return false;
}
finally
{
if (doc != null) doc.Close(false);
}
在全部处理完成后需要关闭CAD应用:
#region 关闭CAD程序
try
{
_app.Quit();
}
catch (Exception ex)
{
return;
}
#endregion