[CommandMethod("copyLayout")]
public void copyLayoutToNewDwg()
{
Layout layout = new Layout();
string layoutNameInCurDwg = "Layout1";
LayoutManager lytMgr = default(LayoutManager);
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor();
ObjectId layoutId = default(ObjectId);
//Get orignal drawing
Database db = Application.DocumentManager.MdiActiveDocument.Database;
//create a new drawing
Database newDb = new Database(true, false);
using (Transaction tr = newDb.TransactionManager.StartTransaction()) {
//Make the working database the new database
HostApplicationServices.WorkingDatabase = newDb;
// Create a new Layout
LayoutManager newLytMgr = LayoutManager.Current();
ObjectId newLayoutId = newLytMgr.CreateLayout("newLayout");
Layout newLayout = tr.GetObject(newLayoutId, OpenMode.ForWrite);
//Make the original database the working database
HostApplicationServices.WorkingDatabase = db;
using (Transaction tr2 = db.TransactionManager.StartTransaction()) {
// Get the dictionary of the original database
DBDictionary lytDict = tr2.GetObject(db.LayoutDictionaryId, OpenMode.ForRead);
//Make sure the layout existes in the original database
if (!lytDict.Contains(layoutNameInCurDwg)) {
ed.WriteMessage("Layout named \"Layout1\" does not exist in current dwg");
return;
}
//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
BlockTableRecord blkTableRec = default(BlockTableRecord);
blkTableRec = tr2.GetObject(layout.BlockTableRecordId, OpenMode.ForRead);
//Get the object ids of the objects in the existing block table record
ObjectIdCollection objIdCol = new ObjectIdCollection();
foreach (ObjectId objId in blkTableRec) {
objIdCol.Add(objId);
}
// Clone the objects to the new layout
IdMapping idMap = new IdMapping();
newDb.WblockCloneObjects(objIdCol, newLayout.BlockTableRecordId, idMap, DuplicateRecordCloning.MangleName, false);
tr2.Commit();
}
tr.Commit();
newDb.SaveAs("c:\\newLayout.dwg", DwgVersion.Newest);
}
}