AutoCad二次开发-插入DWG参照 Teigha库
近日需要运用Oda的teigha库进行不开AutoCad进行dwg地图参照和绑定,查看了SDK终于实现这一需求,故将实现方法分享出来。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teigha.DatabaseServices;
using Teigha.Runtime;
namespace HelloTeigha
{
internal class Program
{
private static string _desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
static void Main(string[] args)
{
var sourceFile = Path.Combine(_desktop, "SourceDwg.dwg");
var targetFile = Path.Combine(_desktop, "Target.dwg");
var Target_tz = Path.Combine(_desktop, "AX-04-P03.dwg");
using (var service = new Services())
using (var database = new Database(false, true))
{
database.ReadDwgFile(sourceFile, FileOpenMode.OpenForReadAndReadShare, true, "");
using (var transaction = database.TransactionManager.StartTransaction())
using (var blockTable = database.BlockTableId.GetObject(OpenMode.ForWrite) as BlockTable)
using (var modelSpace = blockTable[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord)
{
try
{
if (File.Exists(Target_tz))
{
var referId = database.AttachXref(Target_tz, "AX-04-P03");
var blockRefer = new BlockReference(new Teigha.Geometry.Point3d(0, 0, 0), referId);
modelSpace.AppendEntity(blockRefer);
transaction.AddNewlyCreatedDBObject(blockRefer, true);
database.BindXrefs(new ObjectIdCollection() { referId }, true);
transaction.Commit();
database.SaveAs(sourceFile, DwgVersion.AC1024);
}
}
catch (System.Exception)
{
}
}
}
}
}
}