Another Friday afternoon, another DevNote migrated. This VB.NET sample copies a Layout from one drawing to another using CopyFrom and WblockCloneObjects.
<CommandMethod("copyLayout")> _
Sub copyLayoutToNewDwg()
Dim layout As New Layout
Dim layoutNameInCurDwg As String = "Layout1"
Dim lytMgr As LayoutManager
Dim ed As Editor =
Application.DocumentManager.MdiActiveDocument.Editor()
Dim layoutId As ObjectId
'Get orignal drawing
Dim db As Database =
Application.DocumentManager.MdiActiveDocument.Database
'create a new drawing
Dim newDb As Database = New Database(True, False)
Using tr As Transaction = newDb.TransactionManager.StartTransaction()
'Make the working database the new database
HostApplicationServices.WorkingDatabase = newDb
' Create a new Layout
Dim newLytMgr As LayoutManager = LayoutManager.Current()
Dim newLayoutId As ObjectId = newLytMgr.CreateLayout("newLayout")
Dim newLayout As Layout = tr.GetObject(newLayoutId, OpenMode.ForWrite)
'Make the original database the working database
HostApplicationServices.WorkingDatabase = db
Using tr2 As Transaction = db.TransactionManager.StartTransaction()
' Get the dictionary of the original database
Dim lytDict As DBDictionary =
tr2.GetObject(db.LayoutDictionaryId, OpenMode.ForRead)
'Make sure the layout existes in the original database
If Not lytDict.Contains(layoutNameInCurDwg) Then
ed.WriteMessage("Layout named ""Layout1"" does not exist in current dwg")
Return
End If
'Get the layout in the original database
lytMgr = LayoutManager.Current()
layoutId = lytMgr.GetLayoutId(layoutNameInCurDwg)
layout = tr2.GetObject(layoutId, OpenMode.ForRead)
newLayout.CopyFrom(layout)
'Get the block table record of the existing layout
Dim blkTableRec As BlockTableRecord
blkTableRec =
tr2.GetObject(layout.BlockTableRecordId, OpenMode.ForRead)
'Get the object ids of the objects in the existing block table record
Dim objIdCol As New ObjectIdCollection()
For Each objId As ObjectId In blkTableRec
objIdCol.Add(objId)
Next
' Clone the objects to the new layout
Dim idMap As IdMapping = New IdMapping()
newDb.WblockCloneObjects(objIdCol,
newLayout.BlockTableRecordId,
idMap,
DuplicateRecordCloning.MangleName,
False)
tr2.Commit()
End Using
tr.Commit()
newDb.SaveAs("c:\newLayout.dwg", DwgVersion.Newest)
End Using
End Sub
