跨图形实体拷贝

当需要将外部DWG图纸中的某些内容拷贝到当前图形时,可以在后台加载DWG,进而从后台数据库中拷贝对象。
本文提供一个示例。

将外部图纸的所有实体拷贝到当前图形

可以通过IdMapping拿到原实体和拷贝实体的ObjectId,从而进行后续操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public static bool CopyAllEntity(this Document destinationDoc, string sourceDwgPath, out List<ObjectId> newIds, bool isReplace = false)
{
// 返回拷贝实体的Id
newIds = new List<ObjectId>();
Database curdb = destinationDoc.Database;
using (Database db = new Database(false, true))
{
db.ReadDwgFile(sourceDwgPath, FileShare.ReadWrite, true, null);
Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
ObjectIdCollection blockIds = new ObjectIdCollection();
using (Transaction tran = tm.StartTransaction())
{
BlockTable bt = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false);
foreach (ObjectId btrId in btr)
blockIds.Add(btrId);
tran.Commit();
}

IdMapping mapping = new IdMapping();
using (DocumentLock docLock = destinationDoc.LockDocument())
{
using (Transaction trans = destinationDoc.TransactionManager.StartTransaction())
{
BlockTable bt2 = (BlockTable)trans.GetObject(curdb.BlockTableId, OpenMode.ForWrite, false);
DuplicateRecordCloning cloning = isReplace ? DuplicateRecordCloning.Replace : DuplicateRecordCloning.Ignore;
db.WblockCloneObjects(blockIds, bt2[BlockTableRecord.ModelSpace], mapping, cloning, false);
trans.Commit();
}
}
// 实体Id映射关系存储在IdMapping中
foreach (IdPair ids in mapping)
newIds.Add(ids.Value);
}
return true;
}

评论