最近做一个项目,要求将dwg文件转化为pdf,开发工具VS2010 + AutoCad 2011,
在网上查了很多代码都有各种问题,解决重重的问题,终于实现了批量转化。
1.首先引入com组件
AutoCAD 2011 Type Library
AutoCAD/ObjectDBX Common18.0 Type Library
2.创建/获取CAD实例
- private static AcadApplication _app = null;
- private static void Initialization()
- {
- string programID = "AutoCAD.Application.18.1";
- try
- {
- //如果CAD已经打开,就直接获取
- _app = (AcadApplication)Marshal.GetActiveObject(programID);
- }
- catch
- {
- try
- {
- //创建新的实例
- _app = (AcadApplication)new AcadDocument().Application;
- }
- catch
- {
- throw;
- }
- }
- }
关于AutoCAD2011对应的版本是AutoCAD.Application.18.1
关于创建CAD实例的方法,网上流传的版本是
app = new AcadApplication();
app = new AcadApplicationClass();
经过测试上述两种方法对于AutoCad 2011都报错。。
所以采取了_app = (AcadApplication)new AcadDocument().Application;
3.dwg批量转换成pdf
- public static void Dwg2Pdf(IEnumerable<FileInfo> files)
- {
- Initialization();
- AcadDocument doc = null;
- string destPath = string.Empty;
- try
- {
- foreach (var f in files)
- {
- doc = _app.Documents.Open(f.FullName,true);
- doc.SetVariable("sdi", 0);
- doc.SetVariable("Filedia", 0);
- doc.SetVariable("RASTERPREVIEW", 1);
- doc.SetVariable("BACKGROUNDPLOT", 0);
- doc.ActiveLayout.ConfigName = _cfg.AUTOCAD_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(f.Directory.FullName, Path.GetFileNameWithoutExtension(f.Name) + ".pdf");
- doc.Plot.PlotToFile(destPath);
- if (doc != null) doc.Close(false);
- }
- }
- catch (System.Exception e)
- {
- throw e;
- }
- finally
- {
- try
- {
- doc.Close(false);
- _app.Quit();
- }
- catch { }
- }
- }
需要注意几点
1.doc.SetVariable("BACKGROUNDPLOT", 0);一定要设置为0,否则只能转换第一个文件,第二个文件就报错。
2.doc.ActiveLayout.ConfigName不同版本的CAD都不一样,有的是DWGtoPDF.pc3也有的是DWG to PDF.pc3