Ejemplo n.º 1
0
        private static void AddCircle(Gem.Point2d pnt, string layer)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.Circle acCircle = new Db.Circle();
                acCircle.SetDatabaseDefaults();
                acCircle.Center = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acCircle.Radius = SettingsParser.getInstance()._Scale.Circle;
                acCircle.Layer  = layer;
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acCircle);
                acTrans.AddNewlyCreatedDBObject(acCircle, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
Ejemplo n.º 2
0
        private static void SetDrawOrderInBlock(App.Document dwg, Db.ObjectId blkId)
        {
            using (Db.Transaction tran =
                       dwg.TransactionManager.StartTransaction())
            {
                Db.BlockReference bref = (Db.BlockReference)tran.GetObject(
                    blkId, Db.OpenMode.ForRead);

                Db.BlockTableRecord bdef = (Db.BlockTableRecord)tran.GetObject(
                    bref.BlockTableRecord, Db.OpenMode.ForWrite);

                Db.DrawOrderTable doTbl = (Db.DrawOrderTable)tran.GetObject(
                    bdef.DrawOrderTableId, Db.OpenMode.ForWrite);

                Db.ObjectIdCollection col = new Db.ObjectIdCollection();
                foreach (Db.ObjectId id in bdef)
                {
                    if (id.ObjectClass == Rtm.RXObject.GetClass(typeof(Db.Wipeout)))
                    {
                        col.Add(id);
                    }
                }

                if (col.Count > 0)
                {
                    doTbl.MoveToBottom(col);
                }


                tran.Commit();
            }
        }
Ejemplo n.º 3
0
        private static void AddText(Gem.Point2d pnt, string layer, string str)
        {
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                // Открытие таблицы Блоков для чтения
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;

                // Открытие записи таблицы Блоков пространства Модели для записи
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;

                Db.MText acMText = new Db.MText();
                acMText.SetDatabaseDefaults();
                acMText.Location = new Gem.Point3d(pnt.X, pnt.Y, 0);
                acMText.Contents = str;
                acMText.Height   = SettingsParser.getInstance()._Scale.Coord;
                acMText.Color    = Autodesk.AutoCAD.Colors.
                                   Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByLayer, 256);
                acMText.Layer = layer;
                acMText.SetDatabaseDefaults();
                // Добавление нового объекта в запись таблицы блоков и в транзакцию
                acBlkTblRec.AppendEntity(acMText);
                acTrans.AddNewlyCreatedDBObject(acMText, true);
                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
        public override List <string> GetObjectsInView()
        {
            var objs = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.BlockTable       blckTbl     = tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead) as AcadDb.BlockTable;
                AcadDb.BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[AcadDb.BlockTableRecord.ModelSpace], AcadDb.OpenMode.ForRead) as AcadDb.BlockTableRecord;
                foreach (AcadDb.ObjectId id in blckTblRcrd)
                {
                    var dbObj = tr.GetObject(id, AcadDb.OpenMode.ForRead);
                    if (dbObj is AcadDb.BlockReference)
                    {
                        var blckRef = (AcadDb.BlockReference)dbObj; // skip block references for now
                    }
                    else
                    {
                        objs.Add(dbObj.Handle.ToString());
                    }
                }
                // TODO: this returns all the doc objects. Need to check for visibility later.
                tr.Commit();
            }
            return(objs);
        }
Ejemplo n.º 5
0
        private void Search()
        {
            var acDoc = Application.DocumentManager.MdiActiveDocument;

            if (acDoc != null)
            {
                using (DocumentLock dlock = acDoc.LockDocument()) {
                    var acCurDb = acDoc.Database;
                    using (var tr = acCurDb.TransactionManager.StartTransaction()) {
                        var bt = (DB.BlockTable)tr.GetObject(acCurDb.BlockTableId, DB.OpenMode.ForRead, false);
                        foreach (DB.ObjectId objId in bt)
                        {
                            DB.BlockTableRecord btr = tr.GetObject(objId, DB.OpenMode.ForRead, false) as DB.BlockTableRecord;
                            if (btr != null)
                            {
                                if (btr.IsLayout)
                                {
                                    var layout = (DB.Layout)tr.GetObject(btr.LayoutId, DB.OpenMode.ForRead);
                                    foreach (DB.ObjectId objId2 in btr)
                                    {
                                        processObjectId(tr, layout, objId2);
                                    }
                                }
                            }
                        }
                        tr.Abort();
                    }
                }
            }
        }
Ejemplo n.º 6
0
        static public void SpaceOnAttributeName()
        {
            // Получение текущего документа и базы данных
            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            Ed.Editor    acEd    = acDoc.Editor;

            // старт транзакции
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.TypedValue[] acTypValAr = new Db.TypedValue[1];
                acTypValAr.SetValue(new Db.TypedValue((int)Db.DxfCode.Start, "INSERT"), 0);
                Ed.SelectionFilter acSelFtr = new Ed.SelectionFilter(acTypValAr);

                Ed.PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(acSelFtr);
                if (acSSPrompt.Status == Ed.PromptStatus.OK)
                {
                    Ed.SelectionSet acSSet = acSSPrompt.Value;
                    foreach (Ed.SelectedObject acSSObj in acSSet)
                    {
                        if (acSSObj != null)
                        {
                            if (acSSObj.ObjectId.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.BlockReference))))
                            {
                                Db.BlockReference acEnt = acTrans.GetObject(acSSObj.ObjectId,
                                                                            Db.OpenMode.ForRead) as Db.BlockReference;

                                Db.BlockTableRecord blr = acTrans.GetObject(acEnt.BlockTableRecord,
                                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                if (acEnt.IsDynamicBlock)
                                {
                                    blr = acTrans.GetObject(acEnt.DynamicBlockTableRecord,
                                                            Db.OpenMode.ForRead) as Db.BlockTableRecord;
                                }

                                if (blr.HasAttributeDefinitions)
                                {
                                    foreach (Db.ObjectId id in blr)
                                    {
                                        if (id.ObjectClass.IsDerivedFrom(Rtm.RXClass.GetClass(typeof(Db.AttributeDefinition))))
                                        {
                                            Db.AttributeDefinition acAttrRef = acTrans.GetObject(id,
                                                                                                 Db.OpenMode.ForWrite) as Db.AttributeDefinition;

                                            if (acAttrRef != null)
                                            {
                                                acAttrRef.Tag = acAttrRef.Tag.Replace('_', ' ');
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                acTrans.Commit();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This is Extension Method for the <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// class. It gets the localized name of the Model tab.
        /// </summary>
        /// <param name="mng">Target <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// instance.</param>
        /// <returns>Returns the name of current space.</returns>
        public static String GetModelTabLocalizedName(this Db.LayoutManager mng)
        {
            Db.Database db = cad.DocumentManager.MdiActiveDocument.Database;
            String      modelTabLocalizedName = String.Empty;

            using (Db.Transaction tr = db.TransactionManager.StartTransaction())
            {
                Db.BlockTable       bt  = tr.GetObject(db.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord btr = tr.GetObject(bt[Db.BlockTableRecord.ModelSpace], Db.OpenMode.ForRead)
                                          as Db.BlockTableRecord;
                modelTabLocalizedName = (tr.GetObject(btr.LayoutId, Db.OpenMode.ForRead) as Db.Layout).LayoutName;
            }
            return(modelTabLocalizedName);
        }
Ejemplo n.º 8
0
        private void rtext(FindReplacer findReplacer)
        {
            var acDoc = Application.DocumentManager.MdiActiveDocument;

            if (acDoc != null)
            {
                using (DocumentLock dlock = acDoc.LockDocument()) {
                    var acCurDb = acDoc.Database;
                    using (var tr = acCurDb.TransactionManager.StartTransaction()) {
                        int replaced = 0;

                        var bt = (DB.BlockTable)tr.GetObject(acCurDb.BlockTableId, DB.OpenMode.ForRead, false);
                        foreach (DB.ObjectId objId in bt)
                        {
                            DB.BlockTableRecord btr = (DB.BlockTableRecord)tr.GetObject(objId, DB.OpenMode.ForRead, false);
                            if (btr != null)
                            {
                                if (btr.IsLayout)
                                {
                                    foreach (DB.ObjectId objId2 in btr)
                                    {
                                        replaced += processObjectId(tr, objId2, findReplacer);
                                    }
                                }
                            }
                        }

                        acDoc.Editor.WriteMessage("\nзаменено: " + replaced + "\n");
                        if (replaced == 0)
                        {
                            tr.Abort();
                        }
                        else
                        {
                            tr.Commit();
                        }
                    }
                }
            }

            var cnt = findReplacer.Found.Count;

            if (cnt > 0)
            {
                var msg = string.Join("\n", findReplacer.Found.ToArray());
                Forms.MessageBox.Show(msg, "Почти найдено - " + cnt.ToString(),
                                      Forms.MessageBoxButtons.OK, Forms.MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 9
0
        //open -> opened -> modified -> (1) tr.Dispose() -> closed   -> (2) closed    (

        public void ClosedHandler(object sender, AcadDb.ObjectClosedEventArgs args)
        {
            using (var tr = AcadFuncs.GetActiveDb().TransactionManager.StartOpenCloseTransaction())
            {
                AcadDb.BlockTableRecord model_space = AcadFuncs.GetModelSpace(tr);
                model_space.UpgradeOpen();

                AcadDb.DBText text = new AcadDb.DBText();
                text.Position   = curr_pl.StartPoint;
                text.TextString = curr_pl.Length.ToString();

                model_space.AppendEntity(text);
                tr.AddNewlyCreatedDBObject(text, true);
                tr.Commit();
            }
        }
Ejemplo n.º 10
0
        private static void AddMLeader(Gem.Point2d pnt, Gem.Vector3d otstup,
                                       double scale, string layer,
                                       string mleaderStyleName, string str)
        {
            SettingsParser settings = SettingsParser.getInstance();

            App.Document acDoc   = App.Application.DocumentManager.MdiActiveDocument;
            Db.Database  acCurDb = acDoc.Database;
            using (Db.Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
            {
                Db.BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                                           Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[Db.BlockTableRecord.ModelSpace],
                                                                    Db.OpenMode.ForWrite) as Db.BlockTableRecord;
                Db.MLeader acML = new Db.MLeader();
                acML.SetDatabaseDefaults();
                acML.Layer        = layer;
                acML.MLeaderStyle = CheckLocalRepository.GetIDbyName <Db.MLeaderStyle>(acCurDb, mleaderStyleName);
                acML.ContentType  = Db.ContentType.MTextContent;
                Db.MText mText = new Db.MText();
                mText.SetDatabaseDefaults();
                mText.Contents           = str;
                mText.TextHeight         = scale;
                mText.BackgroundFill     = settings.MTextMask;
                mText.UseBackgroundColor = settings.MTextMask;


                if (settings.MTextMask)
                {
                    mText.BackgroundScaleFactor = settings.MTextMaskKoefficient;
                }

                mText.Location = (new Gem.Point3d(pnt.X, pnt.Y, 0) + otstup);
                acML.MText     = mText;
                int idx = acML.AddLeaderLine(new Gem.Point3d(pnt.X, pnt.Y, 0));

                acML.Scale = 1;


                acBlkTblRec.AppendEntity(acML);
                acTrans.AddNewlyCreatedDBObject(acML, true);
                acTrans.Commit();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// This is Extension Method for the <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// class. It gets the name of the current space in the current Database.
        /// </summary>
        /// <param name="mng">Target <c>Autodesk.AutoCAD.DatabaseServices.LayoutManager</c>
        /// instance.</param>
        /// <returns>Returns the name of current space.</returns>
        public static String GetCurrentSpaceName(this Db.LayoutManager mng)
        {
            SpaceEnum space = GetCurrentSpaceEnum(mng);

            Db.Database db = cad.DocumentManager.MdiActiveDocument.Database;
            String      modelSpaceLocalizedName = String.Empty;

            using (Db.Transaction tr = db.TransactionManager.StartTransaction())
            {
                Db.BlockTable       bt  = tr.GetObject(db.BlockTableId, Db.OpenMode.ForRead) as Db.BlockTable;
                Db.BlockTableRecord btr = tr.GetObject(bt[Db.BlockTableRecord.ModelSpace], Db.OpenMode.ForRead)
                                          as Db.BlockTableRecord;
                modelSpaceLocalizedName = (tr.GetObject(btr.LayoutId, Db.OpenMode.ForRead) as Db.Layout).LayoutName;
            }
            String result = space == SpaceEnum.Viewport ?
                            "Model" as String : mng.CurrentLayout;

            return(result);
        }
Ejemplo n.º 12
0
        static public void AddNewEnt(AcadDB.Entity ent)
        {
            AcadDB.Database db = GetActiveDB();

            using (AcadDB.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcadDB.BlockTableRecord model_space = GetModelSpace(tr);
                if (null == model_space)
                {
                    return;
                }

                model_space.UpgradeOpen();
                model_space.AppendEntity(ent);

                tr.AddNewlyCreatedDBObject(ent, true);

                tr.Commit();
            }
        }
Ejemplo n.º 13
0
        public override List <string> GetObjectsInView() // TODO: this returns all visible doc objects. handle views later.
        {
            var objs = new List <string>();

            using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                AcadDb.BlockTable       blckTbl     = tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead) as AcadDb.BlockTable;
                AcadDb.BlockTableRecord blckTblRcrd = tr.GetObject(blckTbl[AcadDb.BlockTableRecord.ModelSpace], AcadDb.OpenMode.ForRead) as AcadDb.BlockTableRecord;
                foreach (AcadDb.ObjectId id in blckTblRcrd)
                {
                    var dbObj = tr.GetObject(id, AcadDb.OpenMode.ForRead);
                    if (dbObj.Visible())
                    {
                        objs.Add(dbObj.Handle.ToString());
                    }
                }
                tr.Commit();
            }
            return(objs);
        }
Ejemplo n.º 14
0
        public void CreateNotification()
        {
            using (AcadDb.Transaction tr = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction())
            {
                AcadDb.Polyline pl = new AcadDb.Polyline();
                pl.AddVertexAt(0, new AcadGeo.Point2d(0.0, 0.0), 0.0, 0.0, 0.0);
                pl.AddVertexAt(1, new AcadGeo.Point2d(10.0, 0.0), 0.0, 0.0, 0.0);

                AcadDb.BlockTableRecord model_space = AcadFuncs.GetModelSpace(tr);

                model_space.UpgradeOpen();
                model_space.AppendEntity(pl);
                tr.AddNewlyCreatedDBObject(pl, true);

                pl.ObjectClosed += new AcadDb.ObjectClosedEventHandler(ClosedHandler);
                //pl.Modified += new EventHandler(ModifiedHandler);
                curr_pl = pl;

                tr.Commit();
            }
        }
Ejemplo n.º 15
0
        //public  void GetLengedPoints(T model)
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    ObjectIdCollection ids = new ObjectIdCollection();

        //    PromptSelectionResult ProSset = null;
        //    TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, MethodCommand.LegendLayer)};
        //    SelectionFilter sfilter = new SelectionFilter(filList);
        //    LayoutManager layoutMgr = LayoutManager.Current;

        //   string ss= layoutMgr.CurrentLayout;
        //    ProSset = doc.Editor.SelectAll(sfilter);
        ////  List<ObjectId> idss=  GetEntitiesInModelSpace();
        //    Database db = doc.Database;
        //    if (ProSset.Status == PromptStatus.OK)
        //    {
        //        using (Transaction tran = db.TransactionManager.StartTransaction())
        //        {
        //            SelectionSet sst = ProSset.Value;

        //            ObjectId[] oids = sst.GetObjectIds();
        //            model.LegendList = new Dictionary<int, List<System.Drawing.PointF>>();
        //            int ad = 0;
        //            List<string> aa = new List<string>();
        //            LayerModel lm = new LayerModel();
        //            LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
        //            foreach (ObjectId layerId in lt)
        //            {
        //                LayerTableRecord ltr = (LayerTableRecord)tran.GetObject(layerId, OpenMode.ForRead);
        //                if (ltr.Name == MethodCommand.LegendLayer)
        //                {
        //                    lm.Color =  System.Drawing.ColorTranslator.ToHtml(ltr.Color.ColorValue);
        //                }
        //            }
        //            for (int i = 0; i < oids.Length; i++)
        //            {
        //              //  if (idss.Contains(oids[i]))
        //              //  {
        //                    DBObject ob = tran.GetObject(oids[i], OpenMode.ForRead);
        //                if (!aa.Contains((ob as Polyline).BlockName)) { aa.Add((ob as Polyline).BlockName); }
        //                    if (ob is Polyline&&(ob as Polyline).BlockName.ToLower()== "*model_space")
        //                    {
        //                        lengedList.Add(ob as Polyline);
        //                        model.LegendList.Add(ad,PolylineMethod.GetPolyLineInfoPt(ob as Polyline));
        //                        ad++;
        //                    }
        //               // }


        //            }
        //            model.allLines = new List<LayerModel>();

        //            model.allLines.Add(lm);
        //        }
        //    }


        //}

        public List <Autodesk.AutoCAD.DatabaseServices.ObjectId> GetEntitiesInModelSpace()
        {
            List <Autodesk.AutoCAD.DatabaseServices.ObjectId> objects = new List <Autodesk.AutoCAD.DatabaseServices.ObjectId>();

            using (Autodesk.AutoCAD.DatabaseServices.Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
            {
                Autodesk.AutoCAD.DatabaseServices.BlockTable blockTable =
                    (Autodesk.AutoCAD.DatabaseServices.BlockTable)transaction.GetObject(
                        Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.WorkingDatabase.BlockTableId,
                        Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                Autodesk.AutoCAD.DatabaseServices.BlockTableRecord blockTableRecord =
                    (Autodesk.AutoCAD.DatabaseServices.BlockTableRecord)transaction.GetObject(
                        blockTable[Autodesk.AutoCAD.DatabaseServices.BlockTableRecord.ModelSpace],
                        Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                foreach (Autodesk.AutoCAD.DatabaseServices.ObjectId objId in blockTableRecord)
                {
                    objects.Add(objId);
                }
                transaction.Commit();
            }
            return(objects);
        }
Ejemplo n.º 16
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotOnePaper(Database db, Document doc, BlockReference br, String pcsFileName,
                                        String mediaName, String outputFileName)
        {
            ;

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }



            Ed.Editor ed = doc.Editor;

            try
            {
                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Extents3d extends = br.GeometryExtentsBestFit();
                        Point3d      pmin    = extends.MinPoint;
                        Point3d      pmax    = extends.MaxPoint;



                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo PltInfo = new Pt.PlotInfo())
                        {
                            PltInfo.Layout = model.LayoutId;

                            using (Db.PlotSettings PltSet = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                PltSet.CopyFrom(layout);

                                Db.PlotSettingsValidator PltSetVald = Db.PlotSettingsValidator
                                                                      .Current;


                                Db.Extents2d extents = new Db.Extents2d(
                                    pmin.X * (1 - 0.0001),
                                    pmin.Y * (1 + 0.001),
                                    pmax.X,
                                    pmax.Y
                                    );

                                Log4NetHelper.WriteInfoLog("左上角坐标:" + pmin.X + "," + pmin.Y + "\n");
                                Log4NetHelper.WriteInfoLog("右下角角坐标:" + pmax.X + "," + pmax.Y + "\n");



                                PltSetVald.SetZoomToPaperOnUpdate(PltSet, true);

                                PltSetVald.SetPlotWindowArea(PltSet, extents);
                                PltSetVald.SetPlotType(PltSet, Db.PlotType.Window);
                                PltSetVald.SetUseStandardScale(PltSet, true);
                                PltSetVald.SetStdScaleType(PltSet, Db.StdScaleType.ScaleToFit);
                                PltSetVald.SetPlotCentered(PltSet, true);
                                PltSetVald.SetPlotRotation(PltSet, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                PltSetVald.SetPlotConfigurationName(PltSet, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                PltInfo.OverrideSettings = PltSet;
                                Pt.PlotInfoValidator PltInfoVald = new Pt.PlotInfoValidator();
                                PltInfoVald.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                PltInfoVald.Validate(PltInfo);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(PltInfo, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, PltInfo, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                //  Hs.WorkingDatabase = previewDb;
            }
        }
Ejemplo n.º 17
0
        // This code based on Kean Walmsley's article:
        // http://through-the-interface.typepad.com/through_the_interface/2007/10/plotting-a-wind.html
        public static void PlotRegion(Db.ObjectId regionId, String pcsFileName,
                                      String mediaName, String outputFileName)
        {
            if (regionId.IsNull)
            {
                throw new ArgumentException("regionId.IsNull == true");
            }
            if (!regionId.IsValid)
            {
                throw new ArgumentException("regionId.IsValid == false");
            }

            if (regionId.ObjectClass.Name != "AcDbRegion")
            {
                throw new ArgumentException("regionId.ObjectClass.Name != AcDbRegion");
            }

            if (pcsFileName == null)
            {
                throw new ArgumentNullException("pcsFileName");
            }
            if (pcsFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("pcsFileName.Trim() == String.Empty");
            }

            if (mediaName == null)
            {
                throw new ArgumentNullException("mediaName");
            }
            if (mediaName.Trim() == String.Empty)
            {
                throw new ArgumentException("mediaName.Trim() == String.Empty");
            }

            if (outputFileName == null)
            {
                throw new ArgumentNullException("outputFileName");
            }
            if (outputFileName.Trim() == String.Empty)
            {
                throw new ArgumentException("outputFileName.Trim() == String.Empty");
            }

            Db.Database previewDb = Hs.WorkingDatabase;
            Db.Database db        = null;
            Ap.Document doc       = cad.DocumentManager.MdiActiveDocument;
            if (doc == null || doc.IsDisposed)
            {
                return;
            }

            Ed.Editor ed = doc.Editor;
            try
            {
                if (regionId.Database != null && !regionId.Database.IsDisposed)
                {
                    Hs.WorkingDatabase = regionId.Database;
                    db = regionId.Database;
                }
                else
                {
                    db = doc.Database;
                }

                using (doc.LockDocument())
                {
                    using (Db.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        Db.Region region = tr.GetObject(regionId,
                                                        Db.OpenMode.ForRead) as Db.Region;

                        Db.Extents3d        extends = region.GeometricExtents;
                        Db.ObjectId         modelId = Us.GetBlockModelSpaceId(db);
                        Db.BlockTableRecord model   = tr.GetObject(modelId,
                                                                   Db.OpenMode.ForRead) as Db.BlockTableRecord;

                        Db.Layout layout = tr.GetObject(model.LayoutId,
                                                        Db.OpenMode.ForRead) as Db.Layout;

                        using (Pt.PlotInfo pi = new Pt.PlotInfo())
                        {
                            pi.Layout = model.LayoutId;

                            using (Db.PlotSettings ps = new Db.PlotSettings(layout.ModelType)
                                   )
                            {
                                ps.CopyFrom(layout);

                                Db.PlotSettingsValidator psv = Db.PlotSettingsValidator
                                                               .Current;

                                Gm.Point2d bottomLeft = Gm.Point2d.Origin;
                                Gm.Point2d topRight   = Gm.Point2d.Origin;

                                region.GetVisualBoundary(0.1, ref bottomLeft,
                                                         ref topRight);

                                Gm.Point3d bottomLeft_3d = new Gm.Point3d(bottomLeft.X,
                                                                          bottomLeft.Y, 0);
                                Gm.Point3d topRight_3d = new Gm.Point3d(topRight.X, topRight.Y,
                                                                        0);

                                Db.ResultBuffer rbFrom = new Db.ResultBuffer(new Db.TypedValue(
                                                                                 5003, 1));
                                Db.ResultBuffer rbTo = new Db.ResultBuffer(new Db.TypedValue(
                                                                               5003, 2));

                                double[] firres = new double[] { 0, 0, 0 };
                                double[] secres = new double[] { 0, 0, 0 };

                                acedTrans(bottomLeft_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, firres);
                                acedTrans(topRight_3d.ToArray(), rbFrom.UnmanagedObject,
                                          rbTo.UnmanagedObject, 0, secres);

                                Db.Extents2d extents = new Db.Extents2d(
                                    firres[0],
                                    firres[1],
                                    secres[0],
                                    secres[1]
                                    );

                                psv.SetZoomToPaperOnUpdate(ps, true);

                                psv.SetPlotWindowArea(ps, extents);
                                psv.SetPlotType(ps, Db.PlotType.Window);
                                psv.SetUseStandardScale(ps, true);
                                psv.SetStdScaleType(ps, Db.StdScaleType.ScaleToFit);
                                psv.SetPlotCentered(ps, true);
                                psv.SetPlotRotation(ps, Db.PlotRotation.Degrees000);

                                // We'll use the standard DWF PC3, as
                                // for today we're just plotting to file
                                psv.SetPlotConfigurationName(ps, pcsFileName, mediaName);

                                // We need to link the PlotInfo to the
                                // PlotSettings and then validate it
                                pi.OverrideSettings = ps;
                                Pt.PlotInfoValidator piv = new Pt.PlotInfoValidator();
                                piv.MediaMatchingPolicy = Pt.MatchingPolicy.MatchEnabled;
                                piv.Validate(pi);

                                // A PlotEngine does the actual plotting
                                // (can also create one for Preview)
                                if (Pt.PlotFactory.ProcessPlotState == Pt.ProcessPlotState
                                    .NotPlotting)
                                {
                                    using (Pt.PlotEngine pe = Pt.PlotFactory.CreatePublishEngine()
                                           )
                                    {
                                        // Create a Progress Dialog to provide info
                                        // and allow thej user to cancel

                                        using (Pt.PlotProgressDialog ppd =
                                                   new Pt.PlotProgressDialog(false, 1, true))
                                        {
                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.DialogTitle, "Custom Plot Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelJobButtonMessage,
                                                "Cancel Job");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.CancelSheetButtonMessage,
                                                "Cancel Sheet");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetSetProgressCaption,
                                                "Sheet Set Progress");

                                            ppd.set_PlotMsgString(
                                                Pt.PlotMessageIndex.SheetProgressCaption,
                                                "Sheet Progress");

                                            ppd.LowerPlotProgressRange = 0;
                                            ppd.UpperPlotProgressRange = 100;
                                            ppd.PlotProgressPos        = 0;

                                            // Let's start the plot, at last
                                            ppd.OnBeginPlot();
                                            ppd.IsVisible = true;
                                            pe.BeginPlot(ppd, null);

                                            // We'll be plotting a single document
                                            pe.BeginDocument(pi, doc.Name, null, 1, true,
                                                             // Let's plot to file
                                                             outputFileName);
                                            // Which contains a single sheet
                                            ppd.OnBeginSheet();
                                            ppd.LowerSheetProgressRange = 0;
                                            ppd.UpperSheetProgressRange = 100;
                                            ppd.SheetProgressPos        = 0;
                                            Pt.PlotPageInfo ppi = new Pt.PlotPageInfo();
                                            pe.BeginPage(ppi, pi, true, null);
                                            pe.BeginGenerateGraphics(null);
                                            pe.EndGenerateGraphics(null);

                                            // Finish the sheet
                                            pe.EndPage(null);
                                            ppd.SheetProgressPos = 100;
                                            ppd.OnEndSheet();

                                            // Finish the document
                                            pe.EndDocument(null);

                                            // And finish the plot
                                            ppd.PlotProgressPos = 100;
                                            ppd.OnEndPlot();
                                            pe.EndPlot(null);
                                        }
                                    }
                                }
                                else
                                {
                                    ed.WriteMessage("\nAnother plot is in progress.");
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
            finally
            {
                Hs.WorkingDatabase = previewDb;
            }
        }
Ejemplo n.º 18
0
        /// <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();
        }
Ejemplo n.º 19
0
        public void CreateLayout()
        {
            using (AcadDb.Transaction tr = AcadFuncs.GetActiveDb().TransactionManager.StartTransaction())
            {
                AcadDb.LayoutManager layout_man = AcadDb.LayoutManager.Current;
                AcadDb.ObjectId      layout_id  = layout_man.CreateLayout("My_Layout");
                layout_man.SetCurrentLayoutId(layout_id);

                AcadDb.Layout layout = tr.GetObject(layout_id, AcadDb.OpenMode.ForRead) as AcadDb.Layout;
                if (null == layout)
                {
                    return;
                }

                AcadDb.BlockTableRecord blk_tbl_rcd = tr.GetObject(layout.BlockTableRecordId, AcadDb.OpenMode.ForRead)
                                                      as AcadDb.BlockTableRecord;
                if (null == blk_tbl_rcd)
                {
                    return;
                }

                AcadDb.ObjectIdCollection vp_ids = layout.GetViewports();
                AcadDb.Viewport           vp     = null;

                foreach (AcadDb.ObjectId vp_id in vp_ids)
                {
                    AcadDb.Viewport vp2 = tr.GetObject(vp_id, AcadDb.OpenMode.ForWrite) as AcadDb.Viewport;
                    if (null != vp2 && 2 == vp2.Number)
                    {
                        vp = vp2;
                        break;
                    }
                }

                if (null == vp)
                {
                    vp = new AcadDb.Viewport();
                    blk_tbl_rcd.UpgradeOpen();
                    blk_tbl_rcd.AppendEntity(vp);
                    tr.AddNewlyCreatedDBObject(vp, true);
                    vp.On     = true;
                    vp.GridOn = true;
                }

                vp.ViewCenter = new AcadGeo.Point2d(0.0, 0.0);
                double scale = 0;
                {
                    AcadEd.PromptDoubleOptions prmpt_pnt = new AcadEd.PromptDoubleOptions("Nhập scale:");
                    AcadEd.PromptDoubleResult  prmpt_ret = AcadFuncs.GetEditor().GetDouble(prmpt_pnt);
                    if (AcadEd.PromptStatus.Cancel == prmpt_ret.Status)
                    {
                        tr.Abort();
                        tr.Dispose();
                        return;
                    }

                    scale = prmpt_ret.Value;
                }
                vp.CustomScale = scale;
                vp.Locked      = true;

                tr.Commit();
            }
        }
Ejemplo n.º 20
0
        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;
                }
            }
        }