[置顶] c# cad中插入另一个dwg的图块
1.在cad2012环境下:
须引用objectarx开发包
PromptPointResult ppr = ed.GetPoint("请选择插入点:");
Point3d pt = ppr.Value; //这里获得插入点
utility.WriteToEditor(pt.ToString());
blockPath = "b_sample.dwg";
using (Database blkDb = new Database(false, true))
{
//read drawing
blkDb.ReadDwgFile(blockPath , System.IO.FileShare.Read, true, null);
blkDb.CloseInput(true);
using (DocumentLock docLock = doc.LockDocument())//多文档要先这样,否则报至命错误
{
using (Transaction t = doc.TransactionManager.StartTransaction())
{
string name=“aa”;//aa是不与blockPath文件中的任何块重名的字符串
//insert it as a new block
ObjectId idBTR = doc.Database.Insert(aa, blkDb, false);
//create a ref to the block
BlockTable bt = (BlockTable)t.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
using (BlockReference bref = new BlockReference(pt, idBTR)) //pt是一个Point3D坐标,这里是插入进当前dwg文件中
{
btr.AppendEntity(bref);
t.AddNewlyCreatedDBObject(bref, true);
}
t.Commit(); 就是这样 谢谢
}
}
}
2.脱离CAD环境下
需引用TDWGNET开发包
using (new Services())
{
using (Database db = new Database(true, true))
{
using (Transaction ts = db.TransactionManager.StartTransaction())
{
using (BlockTable bt = ts.GetObject(db.BlockTableId,OpenMode.ForWrite) as BlockTable)
{
BlockTableRecord btr1 = new BlockTableRecord();
Database odb = new Database(false, false);
odb.ReadDwgFile("aaa.dwg", FileOpenMode.OpenForReadAndAllShare, true, null);
odb.CloseInput(true);
ObjectId objid = db.Insert("aa", odb, false);//这里插入进当前的dwg文件了
BlockTableRecord btr = new BlockTableRecord();//这里是插入另一个块
btr.Name = "000";
Circle c = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 100);
btr.AppendEntity(c);
ts.AddNewlyCreatedDBObject(c, true);
bt.Add(btr);
ts.AddNewlyCreatedDBObject(btr, true);
}
ts.Commit();
}
//using (Transaction ts = db.TransactionManager.StartTransaction())
//{
// using (BlockTable bt = (BlockTable)ts.GetObject(db.BlockTableId, OpenMode.ForRead))
// {
// BlockTableRecord btr=ts.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
// BlockReference br = new BlockReference(new Point3d(0, 0, 0), bt["aa"]);//这里是插入块于当前的dwg中
// btr.AppendEntity(br);
// ts.AddNewlyCreatedDBObject(br, true);
// }
// ts.Commit();
//}
db.SaveAs(path + "\\test.dwg", DwgVersion.Current);//保存文件
}
}
}