private void SaveAsDxf(string source, string dest) { try { if (dest == null) { throw new ArgumentNullException(nameof(dest)); } _logger.AddLog(String.Format("Drawing to Open: {0}", source)); Autodesk.AutoCAD.DatabaseServices.Database oldDb = HostApplicationServices.WorkingDatabase; using (Autodesk.AutoCAD.DatabaseServices.Database db = new Autodesk.AutoCAD.DatabaseServices.Database(false, true)) { db.ReadDwgFile(source, FileOpenMode.OpenForReadAndWriteNoShare, true, null); db.CloseInput(true); HostApplicationServices.WorkingDatabase = db; var filename = Path.GetFileName(dest); var destPath = Path.GetDirectoryName(dest); var dxfout = Path.Combine(destPath, filename.Replace(".DWG", ".DXF")); HostApplicationServices.WorkingDatabase = oldDb; db.DxfOut(dxfout, 16, DwgVersion.Current); } } catch (Exception ex) { _logger.LogException(ex); } }
/// <summary> /// insert signatures /// </summary> /// <param name="dwgPath"></param> /// <param name="dwgNameList"></param> public void InsertSign(string dwgPath, List <string> dwgNameList) { AdeskAppSvr.Document doc = AdeskAppSvr.Application.DocumentManager.MdiActiveDocument; this.Hide(); AdeskDBSvr.Database CurrDB = doc.Database;//current database AdeskEdIn.Editor ed = doc.Editor; AdeskEdIn.PromptPointResult prPointRes_Base = ed.GetPoint(new AdeskEdIn.PromptPointOptions("选择插入的基点")); AdeskEdIn.PromptPointResult prPointRes_opp = ed.GetPoint(new AdeskEdIn.PromptPointOptions("选择基点的对角点")); //In order to make the signs look nicely , calculate the base point and its opposite point AdeskGeo.Point3d P_base = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.1); AdeskGeo.Point3d P_opp = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.9); //sign's width and height double SignWidth = P_opp.X - P_base.X; double SignHeight = P_opp.Y - P_base.Y; //distance between each other double distanceW = prPointRes_opp.Value.X - prPointRes_Base.Value.X; double distanceH = prPointRes_opp.Value.Y - prPointRes_Base.Value.Y; //scale of signature. 36 is the width of sign, and 17 is the height. you should adjust them in your condition. double scaleWidth = SignWidth / 36; double scaleHeight = SignHeight / 17; //today string date = System.DateTime.Today.ToLocalTime().ToString().Split(' ')[0]; try { for (int i = 0; i < dwgNameList.Count; i++) { using (AdeskDBSvr.Database tmpdb = new AdeskDBSvr.Database(false, false)) { //read drawing tmpdb.ReadDwgFile(dwgPath + dwgNameList[i], FileShare.Read, true, null); //insert it as a new block AdeskDBSvr.ObjectId idBTR = CurrDB.Insert(this.ICCardList[i], tmpdb, false); using (AdeskDBSvr.Transaction trans = CurrDB.TransactionManager.StartTransaction()) { AdeskDBSvr.BlockTable bt = (AdeskDBSvr.BlockTable)trans.GetObject(CurrDB.BlockTableId, AdeskDBSvr.OpenMode.ForRead); AdeskDBSvr.BlockTableRecord btr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(bt[AdeskDBSvr.BlockTableRecord.ModelSpace], AdeskDBSvr.OpenMode.ForWrite); //insert point AdeskGeo.Point3d inPt = new AdeskGeo.Point3d(P_base.X, P_base.Y - i * distanceH, P_base.Z); #region signature date //signature date AdeskDBSvr.MText SignDate = new AdeskDBSvr.MText(); AdeskDBSvr.TextStyleTable TextStyleTB = (AdeskDBSvr.TextStyleTable)trans.GetObject(CurrDB.TextStyleTableId, AdeskDBSvr.OpenMode.ForWrite); AdeskDBSvr.TextStyleTableRecord TextStyleTBRec = new AdeskDBSvr.TextStyleTableRecord(); TextStyleTBRec.Font = new AdeskGra.FontDescriptor("宋体", true, false, 0, 0); TextStyleTB.Add(TextStyleTBRec); trans.AddNewlyCreatedDBObject(TextStyleTBRec, true); //trans.Commit(); SignDate.TextStyle = TextStyleTBRec.Id; SignDate.Contents = date; SignDate.TextHeight = SignHeight / 2; SignDate.Width = SignWidth / 3; //date's location should fit the frame SignDate.Location = new AdeskGeo.Point3d((inPt.X + distanceW), (inPt.Y + 1.5 * SignDate.TextHeight), inPt.Z); btr.AppendEntity(SignDate); trans.AddNewlyCreatedDBObject(SignDate, true); #endregion try { //create a ref to the block using (AdeskDBSvr.BlockReference bref = new AdeskDBSvr.BlockReference(inPt, idBTR)) { bref.ScaleFactors = new AdeskGeo.Scale3d(scaleWidth, scaleHeight, 1.0); btr.AppendEntity(bref); trans.AddNewlyCreatedDBObject(bref, true); } trans.Commit(); } catch (System.Exception err) { MessageBox.Show("one: " + err.Message); } } } } } catch (Autodesk.AutoCAD.Runtime.Exception err) { MessageBox.Show("insert: " + err.Message); } this.Show(); }
public static void PurgeDgnLinetypesExt() { var doc = Application.DocumentManager.MdiActiveDocument; var ed = doc.Editor; var pofo = new PromptOpenFileOptions("\nSelect file to purge"); // Use the command-line version if FILEDIA is 0 or // CMDACTIVE indicates we're being called from a script // or from LISP short fd = (short)Application.GetSystemVariable("FILEDIA"); short ca = (short)Application.GetSystemVariable("CMDACTIVE"); pofo.PreferCommandLine = (fd == 0 || (ca & 36) > 0); pofo.Filter = "DWG (*.dwg)|*.dwg|All files (*.*)|*.*"; // Ask the user to select a DWG file to purge var pfnr = ed.GetFileNameForOpen(pofo); if (pfnr.Status == PromptStatus.OK) { // Make sure the file exists // (it should unless entered via the command-line) if (!File.Exists(pfnr.StringResult)) { ed.WriteMessage( "\nCould not find file: \"{0}\".", pfnr.StringResult ); return; } try { // We'll just suffix the selected filename with "-purged" // for the output location. This file will be overwritten // if the command is called multiple times var output = Path.GetDirectoryName(pfnr.StringResult) + "\\" + Path.GetFileNameWithoutExtension(pfnr.StringResult) + "-purged" + Path.GetExtension(pfnr.StringResult); // Assume a post-R12 drawing using (var db = new ACADDB.Database(false, true)) { // Read the DWG file into our Database object db.ReadDwgFile( pfnr.StringResult, FileOpenMode.OpenForReadAndReadShare, false, "" ); // No graphical changes, so we can keep the preview // bitmap db.RetainOriginalThumbnailBitmap = true; // We'll store the current working database, to reset // after the purge operation var wdb = HostApplicationServices.WorkingDatabase; HostApplicationServices.WorkingDatabase = db; // Purge unused DGN linestyles from the drawing // (returns false if nothing is erased) if (PurgeDgnLinetypesInDb(db, ed)) { // Check the version of the drawing to save back to var ver = (db.LastSavedAsVersion == DwgVersion.MC0To0 ? DwgVersion.Current : db.LastSavedAsVersion ); // Now we can save db.SaveAs(output, ver); ed.WriteMessage( "\nSaved purged file to \"{0}\".", output ); } // Still need to reset the working database HostApplicationServices.WorkingDatabase = wdb; } } catch (ACADRT.Exception ex) { ed.WriteMessage("\nException: {0}", ex.Message); } } }
internal static bool CloneFromRepository <T>(Db.Database db, string strName, string RepositorySourcePath) { bool returnValue = false; using (Db.Database dbSource = new Db.Database(false, true)) { try { dbSource.ReadDwgFile(RepositorySourcePath, System.IO.FileShare.Read, true, null); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { App.Application.DocumentManager.MdiActiveDocument.Editor. WriteMessage("\nError reading file repository: " + ex.Message); return(returnValue); } Db.ObjectIdCollection sourceIds = new Db.ObjectIdCollection(); using (Db.Transaction tr1 = dbSource.TransactionManager. StartTransaction()) { Db.ObjectId destDbMsId = Db.ObjectId.Null; if (typeof(T) == typeof(Db.MLeaderStyle)) { destDbMsId = db.MLeaderStyleDictionaryId; } else if (typeof(T) == typeof(Db.LayerTableRecord)) { destDbMsId = db.LayerTableId; } Db.ObjectId destId = GetIDbyName <T>(dbSource, strName); if (destId != Db.ObjectId.Null && destDbMsId != Db.ObjectId.Null) { sourceIds.Add(destId); if (sourceIds.Count > 0) { Db.IdMapping mapping = new Db.IdMapping(); try { //Клонируем с заменой dbSource.WblockCloneObjects(sourceIds, destDbMsId, mapping, Db.DuplicateRecordCloning.Replace, false); returnValue = true; } catch (Rtm.Exception ex) { App.Application.DocumentManager.MdiActiveDocument.Editor. WriteMessage(@"\nError during clone from the repository: " + ex.Message); } } } else { App.Application.DocumentManager.MdiActiveDocument.Editor. WriteMessage("\nError during clone from repository. " + "At the repository there is no Object with the specified name!"); } tr1.Commit(); } } return(returnValue); } //CloneFromRepository
/// <summary> /// insert signatures /// </summary> /// <param name="dwgPath">Signature drawings' path</param> /// <param name="dwgNameList">Signature drawing list</param> public void InsertSign(string dwgPath, List<string> dwgNameList) { AdeskAppSvr.Document doc = AdeskAppSvr.Application.DocumentManager.MdiActiveDocument; AdeskDBSvr.Database CurrDB = doc.Database; AdeskEdIn.Editor ed = doc.Editor; AdeskEdIn.PromptPointResult prPointRes_Base = ed.GetPoint(new AdeskEdIn.PromptPointOptions("ѡ�����Ļ���")); AdeskEdIn.PromptPointResult prPointRes_opp = ed.GetPoint(new AdeskEdIn.PromptPointOptions("ѡ�����ĶԽǵ�")); //In order to make the signs look nicely , calculate the base point and its opposite point AdeskGeo.Point3d P_base = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.1); AdeskGeo.Point3d P_opp = CalPoint(prPointRes_Base.Value, prPointRes_opp.Value, 0.9); //sign's width and height double SignWidth = P_opp.X - P_base.X; double SignHeight = P_opp.Y - P_base.Y; //distance between each other double distanceW = prPointRes_opp.Value.X - prPointRes_Base.Value.X; double distanceH = prPointRes_opp.Value.Y - prPointRes_Base.Value.Y; //current date string date = System.DateTime.Today.ToLocalTime().ToString().Split(' ')[0]; try { for (int i = 0; i < dwgNameList.Count; i++) { using (AdeskDBSvr.Database tmpdb = new AdeskDBSvr.Database(false, false)) { //read drawing tmpdb.ReadDwgFile(dwgPath + dwgNameList[i], FileShare.Read, true, null); //insert Signature drawing as a new block into current drawing AdeskDBSvr.ObjectId idBTR = CurrDB.Insert(this.ICCardList[i], tmpdb, false); //scale of signature. 36 is the width of sign, and 17 is the height. you should adjust them in your condition. double WidthOfSign; double HeightOfSign; double scaleWidth = SignWidth / 36; double scaleHeight = SignHeight / 17; using (AdeskDBSvr.Transaction trans = CurrDB.TransactionManager.StartTransaction()) { AdeskDBSvr.BlockTable bt = (AdeskDBSvr.BlockTable)trans.GetObject(CurrDB.BlockTableId, AdeskDBSvr.OpenMode.ForRead); AdeskDBSvr.BlockTableRecord btr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(bt[AdeskDBSvr.BlockTableRecord.ModelSpace], AdeskDBSvr.OpenMode.ForWrite); AdeskDBSvr.BlockTableRecord InBtr = (AdeskDBSvr.BlockTableRecord)trans.GetObject(idBTR, AdeskDBSvr.OpenMode.ForRead); foreach (AdeskDBSvr.ObjectId tmpid in InBtr) { AdeskDBSvr.DBObject dbo = trans.GetObject(tmpid, AdeskDBSvr.OpenMode.ForRead); if (dbo is AdeskDBSvr.Ole2Frame) { AdeskDBSvr.Ole2Frame mOle = (AdeskDBSvr.Ole2Frame)dbo; WidthOfSign = mOle.WcsWidth; HeightOfSign = mOle.WcsHeight; scaleWidth = SignWidth / WidthOfSign; scaleHeight = SignHeight / HeightOfSign; break; } } //insert point of each signature and date from top to bottom AdeskGeo.Point3d inPt = new AdeskGeo.Point3d(P_base.X, P_base.Y - i * distanceH, P_base.Z); #region signature date //signature date AdeskDBSvr.MText SignDate = new AdeskDBSvr.MText(); AdeskDBSvr.TextStyleTable TextStyleTB = (AdeskDBSvr.TextStyleTable)trans.GetObject(CurrDB.TextStyleTableId, AdeskDBSvr.OpenMode.ForWrite); AdeskDBSvr.TextStyleTableRecord TextStyleTBRec = new AdeskDBSvr.TextStyleTableRecord(); TextStyleTBRec.Font = new AdeskGra.FontDescriptor("����", true, false, 0, 0); TextStyleTB.Add(TextStyleTBRec); trans.AddNewlyCreatedDBObject(TextStyleTBRec, true); SignDate.TextStyle = TextStyleTBRec.Id; SignDate.Contents = date; SignDate.TextHeight = SignHeight / 2; SignDate.Width = SignWidth / 3; //date's location should fit the frame SignDate.Location = new AdeskGeo.Point3d((inPt.X + distanceW), (inPt.Y + 1.5 * SignDate.TextHeight), inPt.Z); btr.AppendEntity(SignDate); trans.AddNewlyCreatedDBObject(SignDate, true); #endregion try { //create a ref to the block using (AdeskDBSvr.BlockReference bref = new AdeskDBSvr.BlockReference(inPt, idBTR)) { bref.ScaleFactors = new AdeskGeo.Scale3d(scaleWidth, scaleHeight, 1.0); btr.AppendEntity(bref); trans.AddNewlyCreatedDBObject(bref, true); } trans.Commit(); } catch (System.Exception err) { MessageBox.Show("one: " + err.Message); } } } } } catch (Autodesk.AutoCAD.Runtime.Exception err) { MessageBox.Show("insert: " + err.Message); } }
public static void LoadandProcessPolys() { using (DatabaseCommands commands = new DatabaseCommands()) { var TemplatePath = commands.GetTemplatePath(); #region Get Dwgs to Process var dwgs = commands.LoadandProcessPolys(); if (dwgs == null) { throw new ArgumentNullException(nameof(dwgs)); } IList <DrawingStack> DwDrawingStacks = new List <DrawingStack>(); foreach (var dwg in dwgs) { if (DwDrawingStacks != null) { DwDrawingStacks.Add(dwg); } } #endregion GDwgPath = commands.GetGlobalDWGPath(); GCloudPath = commands.GetGlobalPointCloudPath(); foreach (DrawingStack dwg in DwDrawingStacks) { m_PolylineChildren.Clear(); var acDocMgr = ACAD.Application.DocumentManager; Document acNewDoc = null; Document acDoc = ACAD.Application.DocumentManager.MdiActiveDocument; if (acDocMgr.Count == 1) { acNewDoc = acDocMgr.Add(TemplatePath); using (acDocMgr.MdiActiveDocument.LockDocument()) { acDocMgr.MdiActiveDocument = acDoc; acDocMgr.CurrentDocument.CloseAndDiscard(); acDocMgr.MdiActiveDocument = acNewDoc; } } using (acDocMgr.MdiActiveDocument.LockDocument()) { if (acDoc != null) { ACADDB.Database acDbNewDoc = acNewDoc.Database; //var ed = doc.Editor; string gpath = Convert.ToString(GDwgPath); if (gpath != null) { string path = Path.Combine(gpath, dwg.PolylineDwgName); if (path == null) { throw new ArgumentNullException(nameof(path)); } if (!File.Exists(path)) { DatabaseLogs.FormatLogs("File Not Found", path); return; } try { using (ACADDB.Database db = new ACADDB.Database(false, true)) { // Read the DWG file into our Database object db.ReadDwgFile( path, ACADDB.FileOpenMode.OpenForReadAndReadShare, false, "" ); // No graphical changes, so we can keep the preview // bitmap db.RetainOriginalThumbnailBitmap = true; // We'll store the current working database, to reset // after the purge operation var wdb = ACADDB.HostApplicationServices.WorkingDatabase; ACADDB.HostApplicationServices.WorkingDatabase = db; // Purge unused DGN linestyles from the drawing // (returns false if nothing is erased) collection = Process.GetIdsByTypeTypeValue( "POLYLINE", "LWPOLYLINE", "POLYLINE2D", "POLYLINE3d"); NumberofPolylines = collection.Count; Process.CopyPolylinesBetweenDatabases(db, collection); // Still need to reset the working database datetime = (DateTime)dwg.DateStamp; ACADDB.HostApplicationServices.WorkingDatabase = wdb; string output = SetOutPutFolder(dwg, commands); // PLineToLayers.ProcessLayers(collection, wdb); string fileName = System.IO.Path.GetFileNameWithoutExtension(dwg.PolylineDwgName); outdxf = Path.Combine(output, String.Format("{0}{1}", fileName, ".dxf")); outdwg = Path.Combine(output, dwg.PolylineDwgName); collection.Clear(); //Before Simplification Create Breakline Data OriginalCollection = RefreshSelectionOfPolylines(collection); m_PolylineChildren = CreatePolylineChildren(OriginalCollection); } } catch (Exception e) { DatabaseLogs.FormatLogs("Exception: {0}", e.Message); } } } } PGA.SimplifyPolylines.Commands.SimplifyPolylines(); using (acDocMgr.MdiActiveDocument.LockDocument()) { try { Document acDocument = ACAD.Core.Application.DocumentManager.MdiActiveDocument; ACADDB.Database acDbNewDoc = acDocument.Database; // if (collection != null) collection.Clear(); //collection = RefreshSelectionOfPolylines(collection); collection = OriginalCollection; NumberofPolylines = collection.Count; //Check Polyline Count //Change Layer Names AssignNames.ChangeLayers(); // collection.Clear(); // get the copied collection of this drawing ///collection = RefreshSelectionOfPolylines(collection); //NumberofPolylines = collection.Count; //Get the Distinct LIDAR Points //var p3d = ProcessLidarFile( // PlineToPoints(collection), datetime, dwg.Hole.ToString()); var lidarFile = RetrieveLidarFile(datetime, dwg.Hole.ToString()); //Get the Nearest Neighbor to add to Point Set var neighbors = IncludeIntersectingNeighbor(lidarFile, OriginalCollection); Point3dCollection totalpoints = MergePoint3DCollections(lidarFile, neighbors); var p5d = ProcessLidarFile( PlineToPoints(collection), datetime, dwg.Hole.ToString(), totalpoints); //var p5d = ProcessLidarFileSubtractRegions( // PlineToPoints(collection), datetime, dwg.Hole.ToString(), totalpoints,collection); //Insert into DB InsertPointCloudToDB(dwg, datetime, p5d, PlineToPoints(collection)); //Create all the Distinct surfaces CreateTinForDistinctSurfaces(p5d, collection); acDbNewDoc.SaveAs(outdwg, ACADDB.DwgVersion.Current); acDbNewDoc.DxfOut(outdxf, 16, ACADDB.DwgVersion.Current); } catch (ACADRT.Exception ex) { DatabaseLogs.FormatLogs("Exception: {0}", ex.Message); } } } } }
void OpenDwgFromDatabaseLink(string fileName) { Document doc = Application.DocumentManager.MdiActiveDocument; if (!System.IO.File.Exists(fileName)) { throw new FileNotFoundException(fileName); } // Create a database and try to load the file ACADDB.Database db = new ACADDB.Database(false, true); using (db) { try { db.ReadDwgFile( fileName, System.IO.FileShare.Read, false, "" ); } catch (System.Exception) { COMS.MessengerManager.AddLog(String.Format( "Unable to read drawing file.", db.FingerprintGuid.ToString()) ); return; } try { ACADDB.Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Open the blocktable, get the modelspace ACADDB.BlockTable bt = (ACADDB.BlockTable)tr.GetObject( db.BlockTableId, ACADDB.OpenMode.ForRead ); ACADDB.BlockTableRecord btr = (ACADDB.BlockTableRecord)tr.GetObject( bt[ACADDB.BlockTableRecord.ModelSpace], ACADDB.OpenMode.ForRead ); // Iterate through it, dumping objects foreach (ACADDB.ObjectId objId in btr) { ACADDB.Entity ent = (ACADDB.Entity)tr.GetObject( objId, ACADDB.OpenMode.ForRead ); // Let's get rid of the standard namespace const string prefix = "Autodesk.AutoCAD.DatabaseServices."; string typeString = ent.GetType().ToString(); if (typeString.Contains(prefix)) { typeString = typeString.Substring(prefix.Length); } //ed.WriteMessage( // "\nEntity " + // ent.ObjectId.ToString() + // " of type " + // typeString + // " found on layer " + // ent.Layer + // " with colour " + // ent.Color.ToString() // ); } } } catch (System.Exception) { COMS.MessengerManager.AddLog(String.Format( "Unable to read drawing file.", db.FingerprintGuid.ToString()) ); return; } } }
private void DeletePoly2D3DObjects(string source, string dest, string drawingName) { bool eraseOrig = true; try { if (drawingName == null) { throw new ArgumentNullException(nameof(drawingName)); } _logger.AddLog(String.Format("Drawing to Open: {0}", source)); Autodesk.AutoCAD.DatabaseServices.Database oldDb = HostApplicationServices.WorkingDatabase; using (Autodesk.AutoCAD.DatabaseServices.Database db = new Autodesk.AutoCAD.DatabaseServices.Database(false, true)) { db.ReadDwgFile(source, FileOpenMode.OpenForReadAndWriteNoShare, true, null); db.CloseInput(true); HostApplicationServices.WorkingDatabase = db; using (Transaction tr = db.TransactionManager.StartTransaction()) { // Collect our exploded objects in a single collection var selected = BBC.Common.AutoCAD.AcadUtilities. GetAllObjectIdsInModel(db, false); DBObjectCollection objs = new DBObjectCollection(); // Loop through the selected objects foreach (ObjectId so in selected) { // Open one at a time Entity ent = (Entity)tr.GetObject( so, OpenMode.ForRead ); ; if (ent.GetType() == typeof(Polyline3d) || ent.GetType() == typeof(Polyline2d) || ent.GetType() == typeof(Acad.Polyline) || ent.GetType() == typeof(Line)) { if (eraseOrig) { ent.UpgradeOpen(); ent.Erase(); } } } tr.Commit(); } var output = Path.Combine(_sdir, "S-" + drawingName + ".DWG"); var dxfout = output.Replace(".DWG", ".DXF"); db.SaveAs(output, DwgVersion.Current); HostApplicationServices.WorkingDatabase = oldDb; db.DxfOut(dxfout, 16, DwgVersion.Current); } } catch (Exception ex) { _logger.LogException(ex); } }