public void RemoveDefaultLayouts() { Transaction trans = _document.TransactionManager.TopTransaction; DBDictionary layoutDic = trans.GetObject(_document.LayoutDictionaryId, OpenMode.ForRead, false) as DBDictionary; string pattern = @"\d+ - .+"; LayoutManager acLayoutMgr = LayoutManager.Current; foreach (DBDictionaryEntry entry in layoutDic) { ObjectId layoutId = entry.Value; Layout layout = trans.GetObject(layoutId, OpenMode.ForRead) as Layout; if (!layout.LayoutName.StartsWith("Model")) { Match m = Regex.Match(layout.LayoutName, pattern); if (!m.Success) { acLayoutMgr.DeleteLayout(layout.LayoutName); if (Sheets.ContainsKey(layout.LayoutName)) { Sheets.Remove(layout.LayoutName); } } } } }
public void DelLayouts() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; LayoutManager LMR = LayoutManager.Current; ArrayList Layoutlist = new ArrayList(); using (Transaction Trans = db.TransactionManager.StartTransaction()) { try { //获取布局列表(剔除模型空间) DBDictionary Layouts = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; foreach (DBDictionaryEntry item in Layouts) { if (item.Key != "Model") { Layout layoutobject = Trans.GetObject(item.Value, OpenMode.ForRead) as Layout; Layoutlist.Add(layoutobject); } } Trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception Ex) { ed.WriteMessage("出错啦!{0}", Ex.ToString()); } finally { Trans.Dispose(); } } foreach (Layout LT in Layoutlist) { LMR.DeleteLayout(LT.LayoutName); } }
private void Delete(XamlLayout layout) { LayoutManager.DeleteLayout(layout); LayoutManager.SaveConfig(); }
public static void Main() { DocumentCollection mgr_doc = global::Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager; //Access and lock the current document and database Document doc = global::Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; HostApplicationServices.WorkingDatabase = db; AutoCADCommand.Audit(); AutoCADCommand.Purge(); // if the drawing has any AEC or Proxy objects, immediately // send out to AECTOACAD, audit, purge and then start work //doc.SendStringToExecute( // "AECTOACAD", // true, // true, // true); //Setup directories string curloc = Path.GetDirectoryName(db.Filename); //Creates a new directory for all files to be saved to //called "_Setup Files" and "Xrefs" string NewFol = "_Setup Files"; string NewSetups = "SETUP"; string setuploc = System.IO.Path.Combine(curloc, NewFol, NewSetups); string xrefloc = System.IO.Path.Combine(curloc, NewFol); //creates the setup directories if they don't already exist if (!Directory.Exists(xrefloc)) { Directory.CreateDirectory(xrefloc); } if (!Directory.Exists(setuploc)) { Directory.CreateDirectory(setuploc); } //Gather all the xrefs from the document, if there are any List <BlockTableRecord> xlist = Xref_List(doc); //Get a list of layouts/layoutids List <Layout> listoflayouts = Project_ListOfLayouts(doc); List <ObjectId> listoflayids = Project_ListOfLayoutIds(doc); // The objectIDs for the BlockTableRecords of the Model and PaperSpace layouts ObjectId mspace = listoflayids[0]; List <ObjectId> pspaces = listoflayids.GetRange(1, (listoflayids.Count() - 1)); DictOfViewPorts vp_dict = new DictOfViewPorts(); #region External Reference Exportation using (DocumentLock doclock = doc.LockDocument()) { //Start the process of saving out each of the unique //xrefs into another folder called "Xrefs" if (xlist.Count() > 0) { foreach (BlockTableRecord x in xlist) { using (Transaction tr = db.TransactionManager.StartTransaction()) { //if the file already exists somewhere else in the directory //just copy it from there to the base location instead Xref_ExporterCopy(x); } } } #endregion #region Viewport Information //get the info on all viewports in all layouts foreach (Layout layout in listoflayouts) { List <AutoCADViewport> list_vpinfo = Xref_ViewPortInfo(layout.ObjectId); vp_dict.Add(layout, list_vpinfo); } } #endregion #region Actual Setup File Creation #region Misc. Saving //doc is no longer locked //save the consultant drawing into the xref folder with its references try { doc.Database.SaveAs( (Path.Combine(xrefloc, (Path.GetFileName(db.Filename)))), true, DwgVersion.AC1800, db.SecurityParameters); } catch (global::Autodesk.AutoCAD.Runtime.Exception aex) { if (aex.ErrorStatus == ErrorStatus.FileAccessErr) { // error handling code } } catch { // error handling code } #endregion #region Xref Insertion & Layout Creation foreach (Layout l in listoflayouts) { if (!l.ModelType) { //create a new dwg based on the BR+A template //switch the active drawing to the newly made drawing string BRA = "G:\\Shared\\CADD\\ACAD2011\\Template\\BR+A.dwt"; Document newdoc = doc.CreateNew(BRA, setuploc, l.LayoutName); global::Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument = newdoc; HostApplicationServices.WorkingDatabase = newdoc.Database; try { global::Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("CLAYER", "x-xref"); newdoc.LayerManagement("Lock", "x-xref", false); } catch { // error handling code } //Insert the consultant drawing at 0,0,0 newdoc.Xref_Attach( (doc.Name), Path.GetFileNameWithoutExtension(doc.Name), "Model"); newdoc.Editor.Regen(); //insert the default titleblock based on the size of the previous document's layout string tblksize; int numoflays = 0; string tblk_dir = Path.GetDirectoryName("G:\\Shared\\CADD\\BLOCKLIB\\BR&A\\NYC\\BR+A-NY.dwg"); string TBLK = Path.Combine(xrefloc, "TBLK.dwg"); using (DocumentLock d_lock = newdoc.LockDocument()) { using (Transaction tr1 = newdoc.Database.TransactionManager.StartTransaction()) { numoflays++; tblksize = l.PaperSize(); // If the layout doesn't already exist in the drawing, create it LayoutManager newlaymgr = LayoutManager.Current; List <Layout> new_listoflayouts = Project_ListOfLayouts(newdoc); Layout curlay = new Layout(); PlotPaperUnit ppunits = PlotPaperUnit.Inches; if (!new_listoflayouts.Any(ln => ln.LayoutName.Equals(l.LayoutName))) { curlay = newdoc.Create_NewLayout(l.LayoutName); } else { curlay = new_listoflayouts[new_listoflayouts.FindIndex(ln => ln.LayoutName.Equals(l.LayoutName))]; } #endregion #region Title Block Switch Statements // case statements pick out specific titleblocks try { switch (tblksize) { case "11,17": //change the actual page size curlay.SetPageSize(11.00, 17.00, ppunits); // save the titleblock from the G Drive into the project folder // as TBLK.dwg and the titleblock info as well as TBLKinfo.dwg if (!File.Exists(TBLK)) { File.Copy((Path.Combine(tblk_dir, "11X17.dwg")), (Path.Combine(xrefloc, "TBLK.dwg")), false); File.Copy((Path.Combine(tblk_dir, "11X17INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo.dwg")), false); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } else { string other_tblk = Path.Combine(xrefloc, "TBLK_11X17.dwg"); File.Copy((Path.Combine(tblk_dir, "11X17.dwg")), (Path.Combine(xrefloc, "TBLK_11X17.dwg")), false); File.Copy((Path.Combine(tblk_dir, "11X17INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo_11X17.dwg")), false); //insert the titleblock newdoc.Xref_Attach(other_tblk, "TBLK_11X17", l.LayoutName); } break; case "24,36": //change the actual page size curlay.SetPageSize(24.00, 36.00, ppunits); // save the titleblock from the G Drive into the project folder // as TBLK.dwg and the titleblock info as well as TBLKinfo.dwg if (!File.Exists(TBLK)) { File.Copy((Path.Combine(tblk_dir, "24X36.dwg")), (Path.Combine(xrefloc, "TBLK.dwg")), false); File.Copy((Path.Combine(tblk_dir, "24X36INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo.dwg")), false); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } else { string other_tblk = Path.Combine(xrefloc, "TBLK_24X36.dwg"); File.Copy((Path.Combine(tblk_dir, "24X36.dwg")), (Path.Combine(xrefloc, "TBLK_24X36.dwg")), false); File.Copy((Path.Combine(tblk_dir, "24X36INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo_24X36.dwg")), false); //insert the titleblock newdoc.Xref_Attach(other_tblk, "TBLK_24X36", l.LayoutName); } break; case "30,42": //change the actual page size curlay.SetPageSize(30.00, 42.00, ppunits); // save the titleblock from the G Drive into the project folder // as TBLK.dwg and the titleblock info as well as TBLKinfo.dwg if (!File.Exists(TBLK)) { File.Copy((Path.Combine(tblk_dir, "30X42.dwg")), (Path.Combine(xrefloc, "TBLK.dwg")), false); File.Copy((Path.Combine(tblk_dir, "30X42INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo.dwg")), false); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } else { string other_tblk = Path.Combine(xrefloc, "TBLK_30X42.dwg"); File.Copy((Path.Combine(tblk_dir, "30X42.dwg")), (Path.Combine(xrefloc, "TBLK_30X42.dwg")), false); File.Copy((Path.Combine(tblk_dir, "30X42INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo_30X42.dwg")), false); //insert the titleblock newdoc.Xref_Attach(other_tblk, "TBLK_30X42", l.LayoutName); } break; case "30,48": //change the actual page size curlay.SetPageSize(30.00, 48.00, ppunits); // save the titleblock from the G Drive into the project folder // as TBLK.dwg and the titleblock info as well as TBLKinfo.dwg if (!File.Exists(TBLK)) { File.Copy((Path.Combine(tblk_dir, "30X48.dwg")), (Path.Combine(xrefloc, "TBLK.dwg")), false); File.Copy((Path.Combine(tblk_dir, "30X48INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo.dwg")), false); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } else { string other_tblk = Path.Combine(xrefloc, "TBLK_30X48.dwg"); File.Copy((Path.Combine(tblk_dir, "30X48.dwg")), (Path.Combine(xrefloc, "TBLK_30X48.dwg")), false); File.Copy((Path.Combine(tblk_dir, "30X48INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo_30X48.dwg")), false); //insert the titleblock newdoc.Xref_Attach(other_tblk, "TBLK_30X48", l.LayoutName); } break; default: case "36,48": //change the actual page size curlay.SetPageSize(36.00, 48.00, ppunits); // save the titleblock from the G Drive into the project folder // as TBLK.dwg and the titleblock info as well as TBLKinfo.dwg if (!File.Exists(TBLK)) { File.Copy((Path.Combine(tblk_dir, "36X48.dwg")), (Path.Combine(xrefloc, "TBLK.dwg")), false); File.Copy((Path.Combine(tblk_dir, "36X48INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo.dwg")), false); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } else { string other_tblk = Path.Combine(xrefloc, "TBLK_36X48.dwg"); File.Copy((Path.Combine(tblk_dir, "36X48.dwg")), (Path.Combine(xrefloc, "TBLK_36X48.dwg")), false); File.Copy((Path.Combine(tblk_dir, "36X48INF.dwg")), (Path.Combine(xrefloc, "TBLKinfo_36X48.dwg")), false); //insert the titleblock newdoc.Xref_Attach(other_tblk, "TBLK_36X48", l.LayoutName); } break; } } catch (IOException) { //change the actual page size curlay.SetPageSize(36.00, 48.00, ppunits); //insert the titleblock newdoc.Xref_Attach(TBLK, "TBLK", l.LayoutName); } //newdoc.Editor.Regen(); tr1.Commit(); } #endregion #region Layout Creation //switches to appropiate layout and calls it "Work" using (Transaction tr2 = mgr_doc.MdiActiveDocument.Database.TransactionManager.StartTransaction()) { LayoutManager newlaymgr = LayoutManager.Current; Layout curlay = new Layout(); List <Layout> new_listoflayouts = Project_ListOfLayouts(newdoc); if (new_listoflayouts.Any(ln => ln.LayoutName.Equals(l.LayoutName))) { for (int i = 0; i < new_listoflayouts.Count; i++) { if (new_listoflayouts[i].LayoutName.Equals(l.LayoutName)) { curlay = new_listoflayouts[i]; break; } } } else { newdoc.Create_NewLayout(l.LayoutName); for (int i = 0; i < new_listoflayouts.Count; i++) { if (new_listoflayouts[i].LayoutName.Equals(l.LayoutName)) { curlay = new_listoflayouts[i]; break; } } } if (curlay.LayoutName.ToUpper() != "LAYOUT1") { newlaymgr.DeleteLayout("Layout1"); } newlaymgr.RenameLayout(curlay.LayoutName, "Work"); // for each set of viewport info in the List of VP info foreach (AutoCADViewport vpinfo in vp_dict[l]) { // create a new vp with the corresponding info curlay.Viewport_Create(vpinfo, newdoc); //newdoc.Editor.Regen(); } tr2.Commit(); } newdoc.Editor.Regen(); //delete the extra viewport that gets created sometimes... using (Transaction tr3 = newdoc.TransactionManager.StartTransaction()) { LayoutManager newlaymgr1 = LayoutManager.Current; Layout layout = tr3.GetObject(newlaymgr1.GetLayoutId(newlaymgr1.CurrentLayout), OpenMode.ForWrite) as Layout; BlockTableRecord lay_btr = tr3.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord; ObjectIdCollection vp_ids = layout.GetViewports(); RXClass VPClass = RXObject.GetClass(typeof(Viewport)); foreach (ObjectId item in lay_btr) { if (item.ObjectClass == VPClass) { Viewport vp = tr3.GetObject(item, OpenMode.ForWrite) as Viewport; var laywidth = layout.GetWidth(); var layheight = layout.GetHeight(); if (vp.Number != 1 && (vp.Height > layheight || vp.Width > laywidth)) { vp.Erase(); } newdoc.Editor.Regen(); } } tr3.Commit(); } } #endregion #region Closing Area try { AutoCADCommand.Audit(); AutoCADCommand.Purge(); //save all the changes newdoc.Database.SaveAs( (newdoc.Name), true, DwgVersion.AC1800, db.SecurityParameters); } catch { break; } try { mgr_doc.MdiActiveDocument.CloseAndDiscard(); } catch { } } } try { //mgr_doc.MdiActiveDocument = mgr_doc.GetDocument(db); //mgr_doc.GetDocument(db).CloseAndDiscard(); //mgr_doc.Open("G:\\BRATEMP\\PDS\\BLANK.DWG",false); } catch (System.Runtime.InteropServices.COMException acadcom) { Console.WriteLine("Exception was {0} type and the inner exception was {1}", acadcom.ErrorCode, acadcom.InnerException); Console.ReadLine(); } }
// Содержание тома (Общие данные. Ведомость комплекта чертежей.) public void Contents() { // Создание файла содержания и титульных листов string fileContent = Path.Combine(_album.AlbumDir, "00_Содержание" + _album.StartOptions.Abbr + ".dwg"); File.Copy(_sheetsSet.SheetTemplateFileContent, fileContent); // Кол листов содержания = Суммарное кол лисчтов панелей / на кол строк в таблице на одном листе // Но на первом листе содержания первые 5 строк заняты (обложка, тит, общие данные, наруж стен панели, том1). //_dbFacade = HostApplicationServices.WorkingDatabase; using (_dbContent = new Database(false, true)) { _dbContent.ReadDwgFile(fileContent, FileShare.ReadWrite, false, ""); _dbContent.CloseInput(true); using (new AcadLib.WorkingDatabaseSwitcher(_dbContent)) { // Замена блока рамки из чертежа фасада, если он есть _album.AlbumInfo?.Frame?.ChangeBlockFrame(_dbContent, false); _album?.AlbumInfo?.CoverTitle?.ChangeCoverAndTitle(_dbContent); using (var t = _dbContent.TransactionManager.StartTransaction()) { int curContentLayoutNum = _countSheetsBeforContent + 1; Table tableContent; BlockReference blRefStamp; CopyContentSheet(t, curContentLayoutNum, out tableContent, out blRefStamp); // Определение кол-ва марок АР int countMarkArs = CalcMarksArNumber(_sheetsMarkSB); // Определение кол-ва листов содержания (только для панелей без учета лтстов обложек и тп.) _countContentSheets = CalcSheetsContentNumber(tableContent.Rows.Count, countMarkArs) + _album.StartOptions.NumberAddSheetContent; // Заполнение штампа на первом листе содержания FillingStampContent(blRefStamp, curContentLayoutNum - _countSheetsBeforContent, t); // текущая строка для записи листа int row = _firstRowInTableForSheets; // На первом листе содержания заполняем строки для Обложки, Тит, Общ дан, НСП, Том1. tableContent.Cells[row, 2].TextString = 1.ToString(); tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter; tableContent.Cells[row++, 1].TextString = "Обложка"; tableContent.Cells[row, 2].TextString = 2.ToString(); tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter; tableContent.Cells[row++, 1].TextString = "Титульный лист"; tableContent.Cells[row, 1].TextString = "Общие данные. Ведомость комплекта чертежей"; tableContent.Cells[row, 2].TextString = _countContentSheets > 1 ? "3-" + (3 + _countContentSheets - 1).ToString() : "3"; tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter; row++; tableContent.Cells[row++, 1].TextString = "Наружные стеновые панели"; tableContent.Cells[row++, 1].TextString = "ТОМ"; int curSheetArNum; if (_album.StartOptions.NumberFirstSheet == 0) { curSheetArNum = _countContentSheets + _countSheetsBeforContent;// номер для первого листа Марки АР } else { curSheetArNum = _album.StartOptions.NumberFirstSheet - 1; } ProgressMeter progressMeter = new ProgressMeter(); progressMeter.SetLimit(_sheetsMarkSB.Count); progressMeter.Start("Создание содержания "); foreach (var sheetMarkSB in _sheetsMarkSB) { progressMeter.MeterProgress(); foreach (var sheetMarkAR in sheetMarkSB.SheetsMarkAR) { tableContent.Cells[row, 1].TextString = sheetMarkAR.MarkArFullName + ". Раскладка плитки на фасаде"; sheetMarkAR.SheetNumber = ++curSheetArNum; tableContent.Cells[row, 2].TextString = curSheetArNum.ToString(); tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter; row++; CheckEndOfTable(t, ref curContentLayoutNum, ref tableContent, ref blRefStamp, ref row); tableContent.Cells[row, 1].TextString = sheetMarkAR.MarkArFullName + ". Раскладка плитки в форме"; tableContent.Cells[row, 2].TextString = curSheetArNum.ToString() + ".1"; sheetMarkAR.SheetNumberInForm = curSheetArNum.ToString() + ".1"; tableContent.Cells[row, 2].Alignment = CellAlignment.MiddleCenter; row++; CheckEndOfTable(t, ref curContentLayoutNum, ref tableContent, ref blRefStamp, ref row); } } progressMeter.Stop(); //Удаление пустых строк в таблице содержания if (tableContent.Rows.Count > row + 1) { tableContent.DeleteRows(row, tableContent.Rows.Count - row); } // Удаление последнего листа содержания (пустой копии) HostApplicationServices.WorkingDatabase = _dbContent; LayoutManager lm = LayoutManager.Current; //lm.CurrentLayout = getLayoutContentName(_countSheetsBeforContent + 1); //string layoutNameToDel = (_countSheetsBeforContent + (++_countContentSheets)).ToString("00") + "_" + Settings.Default.SheetTemplateLayoutNameForContent; lm.DeleteLayout(Settings.Default.SheetTemplateLayoutNameForContent); t.Commit(); } //HostApplicationServices.WorkingDatabase = _dbFacade; } _dbContent.SaveAs(fileContent, DwgVersion.Current); } }
// Создание файла марки СБ и листов с панелями марок АР public void CreateSheetMarkSB(SheetsSet sheetSet, int count) { // Создание файла панели Марки СБ и создание в нем листов с панелями Марки АР _fileMarkSB = CreateFileMarkSB(_markSB, sheetSet.Album.AlbumDir, sheetSet.SheetTemplateFileMarkSB, count); // Создание листов Марок АР using (Database dbMarkSB = new Database(false, true)) { //Database dbOrig = _markSB.IdBtr.Database; dbMarkSB.ReadDwgFile(_fileMarkSB, FileShare.ReadWrite, false, ""); dbMarkSB.CloseInput(true); using (new AcadLib.WorkingDatabaseSwitcher(dbMarkSB)) { using (var t = dbMarkSB.TransactionManager.StartTransaction()) { // Для нового режима работы - добавление описания панели // Пока оно одинаковое для всех листов с одной маркой СБ // Поэтому добавлю текст описания на первый лист, потом лист будет копироваться уже вместе с этим тестом. //if (_markSB.Album.StartOptions.NewMode) //{ var panelDesc = new PanelDescription(_markSB, dbMarkSB); try { panelDesc.CreateDescription(t); } catch (Exception ex) { Logger.Log.Error(ex, "panelDesc.CreateDescription();"); } //} // Замена блока рамки sheetSet?.Album?.AlbumInfo?.Frame?.ChangeBlockFrame(dbMarkSB, true); // Копирование всех определений блоков марки АР в файл Марки СБ CopyBtrMarksARToSheetMarkSB(dbMarkSB); // Слои для заморозки на видовых экранах панелей (Окна, Размеры в форме и на фасаде) // А так же включение и разморозка всех слоев. List <ObjectId> layersToFreezeOnFacadeSheet; List <ObjectId> layersToFreezeOnFormSheet; GetLayersToFreezeOnSheetsPanel(dbMarkSB, out layersToFreezeOnFacadeSheet, out layersToFreezeOnFormSheet); // Создание листов Марок АР Point3d pt = Point3d.Origin; foreach (var sheetMarkAR in _sheetsMarkAR) { sheetMarkAR.CreateLayout(dbMarkSB, pt, layersToFreezeOnFacadeSheet, layersToFreezeOnFormSheet); // Точка для вставки следующего блока Марки АР pt = new Point3d(pt.X + 15000, pt.Y, 0); } t.Commit(); } ////// Удаление шаблона листа из фала Марки СБ HostApplicationServices.WorkingDatabase = dbMarkSB; LayoutManager lm = LayoutManager.Current; //lm.CurrentLayout = _sheetsMarkAR[0].LayoutName; //lm.CurrentLayout = Settings.Default.SheetTemplateLayoutNameForMarkAR; lm.DeleteLayout(Settings.Default.SheetTemplateLayoutNameForMarkAR); } //HostApplicationServices.WorkingDatabase = dbOrig; dbMarkSB.SaveAs(_fileMarkSB, DwgVersion.Current); } }