Exemple #1
0
 public static void CreateTextStyle(string TextStyleName, string FontName, double ObliqueAng, out string message)
 {
     try
     {
         using (Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
         {
             Database             db    = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
             TextStyleTable       tst1  = (TextStyleTable)transaction.GetObject(db.TextStyleTableId, OpenMode.ForWrite, true, true);
             TextStyleTableRecord tstr1 = new TextStyleTableRecord
             {
                 Name           = TextStyleName,
                 FileName       = FontName,
                 XScale         = 1,
                 ObliquingAngle = Tools.Deg2Rad(ObliqueAng),
                 Annotative     = AnnotativeStates.True
             };
             tst1.Add(tstr1);
             transaction.TransactionManager.AddNewlyCreatedDBObject(tstr1, true);
             transaction.Commit();
             //RmTSid = tstr1.ObjectId;
             //return true;
             message = string.Empty;
         }
     }
     catch (Autodesk.AutoCAD.Runtime.Exception e)
     {
         message = e.Message.ToString();
     }
 }
Exemple #2
0
        /// <summary>
        /// 删除文字样式
        /// </summary>
        /// <param name="db">数据库对象</param>
        /// <param name="styleName">文字样式名</param>
        /// <returns>如果删除成功返回true,否则返回false</returns>
        public static bool DeleteTextStyle(this Database db, string styleName)
        {
            var trans = db.TransactionManager;
            //打开文字样式表
            TextStyleTable st = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForRead);

            //如果不存在名为styleName的文字样式,则返回
            if (!st.Has(styleName))
            {
                return(false);
            }
            //获取名为styleName的文字样式表记录的Id
            ObjectId styleId = st[styleName];

            //如果要删除的文字样式为当前文字样式,则返回(不能删除当前文字样式)
            if (styleId == db.Textstyle)
            {
                return(false);
            }
            //以写的方式打开名为styleName的文字样式表记录
            TextStyleTableRecord str = (TextStyleTableRecord)trans.GetObject(styleId, OpenMode.ForWrite);

            //删除名为styleName的文字样式
            str.Erase(true);
            return(true);//删除文字样式成功
        }
Exemple #3
0
        /// <summary>
        /// 设置单行文本的属性为当前文字样式的属性
        /// </summary>
        /// <param name="txt">单行文本对象</param>
        public static void SetFromTextStyle(this DBText txt)
        {
            //打开文字样式表记录
            TextStyleTableRecord str = (TextStyleTableRecord)txt.TextStyleId.GetObject(OpenMode.ForRead);

            //必须保证文字为写的状态
            if (!txt.IsWriteEnabled)
            {
                txt.UpgradeOpen();
            }
            txt.Oblique    = str.ObliquingAngle; //设置倾斜角(弧度)
            txt.Annotative = str.Annotative;     //设置文字的注释性
            //文字方向与布局是否匹配
            txt.SetPaperOrientation(Convert.ToBoolean(str.PaperOrientation));
            txt.WidthFactor = str.XScale;   //设置宽度比例
            txt.Height      = str.TextSize; //设置高度
            if (str.FlagBits == 2)
            {
                txt.IsMirroredInX = true;//颠倒
            }
            else if (str.FlagBits == 4)
            {
                txt.IsMirroredInY = true; //反向
            }
            else if (str.FlagBits == 6)   //颠倒并反向
            {
                txt.IsMirroredInX = txt.IsMirroredInY = true;
            }
            txt.DowngradeOpen();//为了安全切换为读的状态
        }
        /// <summary>
        /// 获取文字样式ID
        /// </summary>
        /// <param name="textStyleName">文字样式名</param>
        /// <param name="createIfNotExist">自动创建</param>
        /// <returns>结果</returns>
        public static ObjectId GetTextStyleId(string textStyleName, bool createIfNotExist = false)
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                TextStyleTable tsTab = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForRead);
                if (tsTab.Has(textStyleName))
                {
                    return(tsTab[textStyleName]);
                }
                else
                {
                    if (createIfNotExist)
                    {
                        tsTab.UpgradeOpen();
                        TextStyleTableRecord tstr = new TextStyleTableRecord {
                            Name = textStyleName
                        };
                        var result = tsTab.Add(tstr);
                        trans.AddNewlyCreatedDBObject(tstr, true);
                        trans.Commit();
                        return(result);
                    }
                    else
                    {
                        return(db.Textstyle);
                    }
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// 新建文字样式
        /// </summary>
        public static ObjectId AddTextStyle(this Database db, string TextStyleName, string FontFilename, string BigFontFilename, double WidthFactor)
        {
            ObjectId tsId = ObjectId.Null;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 打开文字样式表
                TextStyleTable tst = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForRead);
                // 如果不存在名为styleName的文字样式,则新建一个文字样式
                if (!tst.Has(TextStyleName))
                {
                    //定义一个新的的文字样式表记录
                    TextStyleTableRecord tsr = new TextStyleTableRecord();
                    //设置的文字样式名
                    tsr.Name = TextStyleName;
                    //设置文字样式的字体
                    tsr.FileName        = FontFilename;
                    tsr.BigFontFileName = BigFontFilename;
                    // 切换文字样式表的状态为写以添加新的文字样式
                    tsr.XScale = WidthFactor;
                    tst.UpgradeOpen();
                    // 更新数据信息
                    tst.Add(tsr);
                    trans.AddNewlyCreatedDBObject(tsr, true);
                    // 为了安全,将文字样式表的状态切换为读
                    tst.DowngradeOpen();

                    tsId = tst[TextStyleName];
                }
                // 提交事务
                trans.Commit();
            }
            return(tsId);
        }
        /// <summary>Сохранить текстовый стиль в XElement</summary>
        /// <param name="textStyleTableRecord">Текстовый стиль</param>
        public static XElement SetTextStyleTableRecordXElement(TextStyleTableRecord textStyleTableRecord)
        {
            var returnedXml = new XElement("TextStyleTableRecord");

            returnedXml.SetAttributeValue("Name", textStyleTableRecord.Name);                                     // string
            returnedXml.SetAttributeValue("BigFontFileName", textStyleTableRecord.BigFontFileName);               // string
            returnedXml.SetAttributeValue("FileName", textStyleTableRecord.FileName);                             // string
            returnedXml.SetAttributeValue("IsShapeFile", textStyleTableRecord.IsShapeFile);                       // bool
            returnedXml.SetAttributeValue("IsVertical", textStyleTableRecord.IsVertical);                         // bool
            returnedXml.SetAttributeValue("FlagBits", textStyleTableRecord.FlagBits);                             // byte
            returnedXml.SetAttributeValue("ObliquingAngle", textStyleTableRecord.ObliquingAngle);                 // double
            returnedXml.SetAttributeValue("PriorSize", textStyleTableRecord.PriorSize);                           // double
            returnedXml.SetAttributeValue("TextSize", textStyleTableRecord.TextSize);                             // double
            returnedXml.SetAttributeValue("XScale", textStyleTableRecord.XScale);                                 // double
            returnedXml.SetAttributeValue("Annotative", textStyleTableRecord.Annotative);                         // AnnotativeState
            returnedXml.SetAttributeValue("HasSaveVersionOverride", textStyleTableRecord.HasSaveVersionOverride); // bool
            returnedXml.SetAttributeValue("PaperOrientation", textStyleTableRecord.PaperOrientation);             // bool

            // font
            var font = new XElement("Font");

            font.SetAttributeValue("TypeFace", textStyleTableRecord.Font.TypeFace);             // string
            font.SetAttributeValue("Bold", textStyleTableRecord.Font.Bold);                     // bool
            font.SetAttributeValue("Italic", textStyleTableRecord.Font.Italic);                 // bool
            font.SetAttributeValue("CharacterSet", textStyleTableRecord.Font.CharacterSet);     // int
            font.SetAttributeValue("PitchAndFamily", textStyleTableRecord.Font.PitchAndFamily); // int
            returnedXml.Add(font);
            return(returnedXml);
        }
Exemple #7
0
        public static bool CreateTextStyle(Document doc, string styleName, string fontName)
        {
            Database db = doc.Database;
            bool isSucceded = false;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                TextStyleTable newTextStyle = tr.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                if (!newTextStyle.Has(styleName))
                {
                    try
                    {
                        newTextStyle.UpgradeOpen();
                        TextStyleTableRecord newTextStyleRec = new TextStyleTableRecord();
                        newTextStyleRec.FileName = fontName;
                        newTextStyleRec.Name = styleName;
                        newTextStyle.Add(newTextStyleRec);
                        tr.AddNewlyCreatedDBObject(newTextStyleRec, true);
                        tr.Commit();
                        isSucceded = true;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    Editor ed = doc.Editor;
                    ed.WriteMessage("\nA text style with this name already exists\n");
                }
            }

            return isSucceded;
        }
Exemple #8
0
        public static void RemoveTextStyle(string styleName)
        {
            Document document = Active.Document;
            Database database = document.Database;

            try
            {
                TextStyleTable textStyleTable = GetTextStyleTable();
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    foreach (ObjectId textStyleTableRecordId in textStyleTable)
                    {
                        TextStyleTableRecord textStyleTableRecord = transaction.GetObject <TextStyleTableRecord>(textStyleTableRecordId, OpenMode.ForRead);
                        if (textStyleTableRecord.Name == styleName)
                        {
                            textStyleTableRecord.UpgradeOpen();
                            textStyleTableRecord.Erase();
                        }
                    }

                    transaction.Commit();
                }//using
            }
            catch (Exception ex)
            {
                Active.WriteMessage(ex.Message);
                throw;
            }
        }
Exemple #9
0
        private static ObjectId CreateSpreadPointTextStyle(SpreadPointSettings settings, Database database)
        {
            ObjectId result = ObjectId.Null;

            using (var transaction = database.TransactionManager.StartTransaction())
            {
                var textStyleTable = (TextStyleTable)transaction.GetObject(database.TextStyleTableId, OpenMode.ForRead);
                if (textStyleTable.Has(settings.TextStyleName))
                {
                    result = textStyleTable[settings.TextStyleName];
                }
                else
                {
                    textStyleTable.UpgradeOpen();
                    var textStyleRecord = new TextStyleTableRecord();
                    textStyleRecord.Name            = settings.TextStyleName;
                    textStyleRecord.FileName        = settings.TextStyleFontFileName;
                    textStyleRecord.BigFontFileName = settings.TextStyleBigFontFileName;
                    result = textStyleTable.Add(textStyleRecord);
                    transaction.AddNewlyCreatedDBObject(textStyleRecord, add: true);
                }
                transaction.Commit();
            }
            return(result);
        }
Exemple #10
0
        public static TextStyleTableRecord GetTextStyle(string textStyleName)
        {
            Document document = Active.Document;
            Database database = document.Database;

            using (Transaction transaction = database.TransactionManager.StartTransaction())
            {
                try
                {
                    TextStyleTable textStyleTable = GetTextStyleTable();
                    foreach (ObjectId textStyleTableRecordId in textStyleTable)
                    {
                        TextStyleTableRecord textStyleTableRecord = transaction.GetObject <TextStyleTableRecord>(textStyleTableRecordId, OpenMode.ForRead);
                        if (textStyleTableRecord.Name == textStyleName)
                        {
                            return(textStyleTableRecord);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Active.WriteMessage(ex.Message);
                    throw;
                }
            }//using
            return(null);
        }
Exemple #11
0
        public void CreateStyle()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                TextStyleTable st        = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForWrite);
                String         StyleName = "工程图";
                if (st.Has(StyleName) == false)
                {
                    TextStyleTableRecord str = new TextStyleTableRecord();
                    str.Name     = StyleName;
                    str.FileName = "simfang.ttf";
                    //---------------------------------------------
                    // 设置SHX字体
                    // str.FileName = "gbenor"
                    //设置大字体.
                    // str.BigFontFileName = "gbcbig"
                    // --------------------------------------------
                    str.ObliquingAngle = 15 * Math.PI / 180;
                    str.XScale         = 0.67;
                    ObjectId TextstyleId = st.Add(str);
                    trans.AddNewlyCreatedDBObject(str, true);
                    db.Textstyle = TextstyleId;
                    trans.Commit();
                }
            }
        }
Exemple #12
0
        // Returns all text styles
        public static Dictionary <string, ObjectId> GetTextStyles()
        {
            Dictionary <string, ObjectId> list = new Dictionary <string, ObjectId>();

            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    TextStyleTable        table = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead);
                    SymbolTableEnumerator it    = table.GetEnumerator();
                    while (it.MoveNext())
                    {
                        ObjectId             id    = it.Current;
                        TextStyleTableRecord style = (TextStyleTableRecord)tr.GetObject(id, OpenMode.ForRead);
                        list.Add(style.Name, id);
                    }
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Error: " + ex.Message, "RebarPos", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
            }

            return(list);
        }
Exemple #13
0
        // Creates a new text style
        public static ObjectId GetOrCreateTextStyle(Database db, string name, string filename, double scale)
        {
            ObjectId id = ObjectId.Null;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                TextStyleTable table = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead);
                if (table.Has(name))
                {
                    id = table[name];
                }
                else
                {
                    TextStyleTableRecord style = new TextStyleTableRecord();
                    style.Name     = name;
                    style.FileName = filename;
                    style.XScale   = scale;
                    table.UpgradeOpen();
                    id = table.Add(style);
                    table.DowngradeOpen();
                    tr.AddNewlyCreatedDBObject(style, true);
                }

                tr.Commit();
            }

            return(id);
        }
 /// <summary>
 /// 通过文字样式Id来克隆文字样式
 /// </summary>
 /// <param name="objId"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public ObjectId CreateTextStyleByClone(ObjectId TextStyleId, string name = "")
 {
     try
     {
         TextStyleTableRecord TextStyle = TextStyleId.GetObject(OpenMode.ForRead) as TextStyleTableRecord;
         using (Transaction tran = database.TransactionManager.StartTransaction())
         {
             TextStyleTableRecord newTextStyle = new TextStyleTableRecord();
             newTextStyle.Name            = name == "" ? TextStyle.Name : name;//如果没有指定名称,则设为被复制的名称
             newTextStyle.BigFontFileName = TextStyle.BigFontFileName;
             newTextStyle.FileName        = TextStyle.FileName;
             newTextStyle.FlagBits        = TextStyle.FlagBits;
             newTextStyle.Font            = TextStyle.Font;
             newTextStyle.IsShapeFile     = TextStyle.IsShapeFile;
             newTextStyle.IsVertical      = TextStyle.IsVertical;
             newTextStyle.ObliquingAngle  = TextStyle.ObliquingAngle;
             newTextStyle.PriorSize       = TextStyle.PriorSize;
             newTextStyle.TextSize        = TextStyle.TextSize;
             newTextStyle.XScale          = TextStyle.XScale;
             TextStyleTbl.UpgradeOpen();//提升权限
             ObjectId NewTextStyleId = TextStyleTbl.Add(newTextStyle);
             tran.AddNewlyCreatedDBObject(newTextStyle, true);
             TextStyleTbl.DowngradeOpen();//降低权限
             tran.Commit();
             return(NewTextStyleId);
         }
     }
     catch (Exception ex)
     {
         Logger.log("CreateLayerByClone", ex.Message);
     }
     return(ObjectId.Null);
 }
Exemple #15
0
        static ObjectId ArialStyle()
        {
            using (var transaction = ModelSpace.StartTransaction())
                using (var styles = (TextStyleTable)transaction.GetObject(
                           HostApplicationServices.WorkingDatabase.TextStyleTableId,
                           OpenMode.ForWrite))
                    using (var currentStyle = (TextStyleTableRecord)transaction.GetObject(
                               HostApplicationServices.WorkingDatabase.Textstyle,
                               OpenMode.ForWrite))
                    {
                        var style = new TextStyleTableRecord()
                        {
                            Font = new Autodesk.AutoCAD.GraphicsInterface.FontDescriptor(
                                "ARIAL",
                                bold: false,
                                italic: false,
                                characters: currentStyle.Font.CharacterSet,
                                pitchAndFamily: currentStyle.Font.PitchAndFamily),
                        };

                        ObjectId styleId = styles.Add(style);

                        transaction.AddNewlyCreatedDBObject(style, true);
                        transaction.Commit();

                        return(styleId);
                    }
        }
Exemple #16
0
        /// <summary>
        /// Trả về một Rectangle bao quanh một chuỗi
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Rectangle GetTextBounds(DBText s, double bufer = 0.35)
        {
            Autodesk.AutoCAD.GraphicsInterface.TextStyle style = new Autodesk.AutoCAD.GraphicsInterface.TextStyle();
            byte        n;
            Transaction tr = GLOBAL.CurrentDatabase.TransactionManager.StartTransaction();

            try
            {
                using (tr)
                {
                    BlockTableRecord btr            = (BlockTableRecord)tr.GetObject(GLOBAL.CurrentDatabase.CurrentSpaceId, OpenMode.ForWrite);
                    string           text           = s.TextString;
                    TextStyleTable   textStyleTable = tr.GetObject
                                                      (
                        GLOBAL.CurrentDatabase.TextStyleTableId,
                        OpenMode.ForRead
                                                      ) as TextStyleTable;

                    string currentTextStyle = Application.GetSystemVariable("TEXTSTYLE").ToString();

                    ObjectId textStyleId = ObjectId.Null;
                    textStyleId = textStyleTable[currentTextStyle];
                    Autodesk.AutoCAD.GraphicsInterface.TextStyle iStyle
                        = new Autodesk.AutoCAD.GraphicsInterface.TextStyle();

                    // get textstyle of newly created text
                    TextStyleTableRecord txtbtr = (TextStyleTableRecord)tr.GetObject(textStyleId, OpenMode.ForRead);
                    // copy properties from TextStyleTableRecord and dbtext to temp AcGi.TextStyle (just very limited one for the future calculation)
                    style.FileName = txtbtr.FileName;
                    // then copy properties from existing text
                    style.TextSize       = s.Height; // txtbtr.TextSize;
                    style.ObliquingAngle = s.Oblique;
                    style.XScale         = s.WidthFactor;
                    // load temp style record
                    try
                    {
                        n = style.LoadStyleRec;
                    }
                    catch { return(null); }

                    Point2d textPos = new Point2d(s.Position.X, s.Position.Y);
                    //bufer = s.Height * 0.35;
                    Point2d p = Autodesk.AutoCAD.Internal.Utils.GetTextExtents(textStyleId, s.TextString, s.Height);

                    Rectangle rec2 = new Rectangle(p.X, p.Y);
                    rec2.LowerLeft  = new Point2d(textPos.X - bufer, textPos.Y - bufer);
                    rec2.UpperLeft  = new Point2d(rec2.LowerLeft.X, rec2.LowerLeft.Y + rec2.Height + 2 * bufer);
                    rec2.UpperRight = new Point2d(rec2.UpperLeft.X + rec2.Width + 2 * bufer, rec2.UpperLeft.Y);
                    rec2.LowerRight = new Point2d(rec2.UpperRight.X, rec2.LowerLeft.Y);

                    return(rec2);
                }
            }
            catch (System.Exception exc)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(exc.Message + "\n" + exc.StackTrace);
                return(null);
            }
            finally { }
        }
Exemple #17
0
        makeTextStyle(string nameStyle, AnnotativeStates annoState = AnnotativeStates.True, double xFactor = 0.8)
        {
            Database db = BaseObjs._db;

            TextStyleTable tst;
            ObjectId       idTxtStyle = ObjectId.Null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    tst = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite);
                    TextStyleTableRecord tstr = new TextStyleTableRecord();
                    tstr.Name           = nameStyle;
                    tstr.Annotative     = annoState;
                    tstr.FileName       = "romans.shx";
                    tstr.TextSize       = 0.0;
                    tstr.ObliquingAngle = 0.0;
                    tstr.IsVertical     = false;
                    tstr.IsShapeFile    = false;
                    tstr.XScale         = xFactor;

                    tst.Add(tstr);
                    idTxtStyle = tstr.ObjectId;
                    tr.AddNewlyCreatedDBObject(tstr, true);

                    tr.Commit();
                }// end using
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " Txt.cs: line: 543");
            }
            return(idTxtStyle);
        }
Exemple #18
0
        getTextStyleTableRecord(string name)
        {
            TextStyleTableRecord tstr = null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    TextStyleTable tst = getTextStyleTable();
                    if (tst.Has(name) == true)
                    {
                        tstr = (TextStyleTableRecord)tr.GetObject(tst[name], OpenMode.ForRead);
                    }
                    else
                    {
                        tstr = addTextStyleTableRecord(name);
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " Txt.cs: line: 469");
            }
            return(tstr);
        }
Exemple #19
0
        addTextStyleTableRecord(string name, string nameFontFile = "Romans.shx", double size = 0.0, double xscale = 0.8)
        {
            TextStyleTableRecord TStr = new TextStyleTableRecord();

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    TextStyleTable TST = getTextStyleTable();
                    TStr.Name = name;

                    TST.UpgradeOpen();
                    TST.Add(TStr);

                    TStr.FileName   = nameFontFile;
                    TStr.TextSize   = size;
                    TStr.XScale     = xscale;
                    TStr.Annotative = AnnotativeStates.True;

                    tr.AddNewlyCreatedDBObject(TStr, true);
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " Txt.cs: line: 199");
            }
            return(TStr);
        }
Exemple #20
0
        public ErrorStatus getTextStyleId(string Textstil, ref ObjectId TextstilId)
        {
            Database    db  = HostApplicationServices.WorkingDatabase;
            Transaction myT = db.TransactionManager.StartTransaction();

            ErrorStatus es = ErrorStatus.KeyNotFound;

            try
            {
                TextStyleTable tsTbl = (TextStyleTable)myT.GetObject(db.TextStyleTableId, OpenMode.ForRead, true, true);

                foreach (ObjectId objId in tsTbl)
                {
                    TextStyleTableRecord tsTblRec = new TextStyleTableRecord();
                    tsTblRec = (TextStyleTableRecord)myT.GetObject(objId, OpenMode.ForWrite);

                    if (Textstil == tsTblRec.Name)
                    {
                        TextstilId = objId;
                        //m_myT.Commit();
                        break;
                    }
                }

                es = ErrorStatus.OK;
            }

            finally
            {
                myT.Commit();
            }

            return(es);
        }
Exemple #21
0
        public ObjectId CreatMyTextStyle()
        {
            ObjectId     StyleID   = ObjectId.Null;
            const string StyleName = "RQBZ";

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    TextStyleTable Tst = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForRead);
                    if (Tst.Has(StyleName))
                    {
                        StyleID = Tst[StyleName];     //来自这个链接 https://www.keanw.com/2012/08/a-handy-jig-for-creating-autocad-text-using-net-part-2.html
                    }
                    else
                    {
                        TextStyleTableRecord MyTextStyle = new TextStyleTableRecord();
                        MyTextStyle.FileName        = "txtd.shx";
                        MyTextStyle.BigFontFileName = "hztxt.shx";
                        MyTextStyle.Name            = "RQBZ";
                        MyTextStyle.XScale          = 0.7;
                        Tst.UpgradeOpen();
                        StyleID = Tst.Add(MyTextStyle);
                        trans.AddNewlyCreatedDBObject(MyTextStyle, true);
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception EX)
                {
                    ed.WriteMessage("出错了!" + EX.ToString());
                }
                trans.Commit();
            }
            return(StyleID);
        }
Exemple #22
0
        getPntLabelStyle(string name)
        {
            LabelStyle LS = null;
            ObjectId   id = ObjectId.Null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    LabelStyleCollection labelStyles = BaseObjs._civDoc.Styles.LabelStyles.PointLabelStyles.LabelStyles;
                    if (labelStyles.Contains(name))
                    {
                        LS = (LabelStyle)tr.GetObject(labelStyles[name], OpenMode.ForRead);
                        return(LS.ObjectId);
                    }
                    else
                    {
                        Base_Tools45.Layer.manageLayers(name);

                        TextStyleTableRecord TStr = Base_Tools45.Txt.getTextStyleTableRecord("L100");
                        if (TStr == null)
                        {
                            TStr = Base_Tools45.Txt.addTextStyleTableRecord("L100");
                        }

                        TStr.FileName = "ROMANS";
                        TStr.XScale   = 0.8;

                        CivilDocument civDoc = CivilApplication.ActiveDocument;

                        id = civDoc.Styles.LabelStyles.PointLabelStyles.LabelStyles.Add(name);

                        LS = (LabelStyle)tr.GetObject(id, OpenMode.ForWrite);

                        LS.AddComponent("PointNumber", LabelStyleComponentType.Text);
                        ObjectIdCollection      ids   = LS.GetComponents(LabelStyleComponentType.Text);
                        LabelStyleTextComponent lstc1 = (LabelStyleTextComponent)tr.GetObject(ids[0], OpenMode.ForWrite);
                        lstc1.General.Visible.Value = true;

                        LS.Properties.DraggedStateComponents.DisplayType.Value = Autodesk.Civil.LabelContentDisplayType.StackedText;

                        tr.Commit();
                    }
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(string.Format("{0} Pnts.cs: line: 133", ex.Message));
            }
            return(id);
        }
Exemple #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        private bool KeepUnchanged(TextStyleTableRecord ts)
        {
            string tsName = ts.Name;

            // 如果在不改变的列表中,则直接返回 true
            foreach (var unChangedTs in KeepUnchangedTextStyle)
            {
                if (tsName.ToUpper().Contains(unChangedTs))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #24
0
        Stream(ArrayList data, TextStyleTableRecord rec)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(TextStyleTableRecord)));

            data.Add(new Snoop.Data.String("Big font file name", rec.BigFontFileName));
            data.Add(new Snoop.Data.String("Filename", rec.FileName));
            data.Add(new Snoop.Data.String("Flag bits", rec.FlagBits.ToString()));
            data.Add(new Snoop.Data.Object("Font descriptor", rec.Font));
            data.Add(new Snoop.Data.Bool("Is shape file", rec.IsShapeFile));
            data.Add(new Snoop.Data.Bool("Is vertical", rec.IsVertical));
            data.Add(new Snoop.Data.Angle("Obliquing angle", rec.ObliquingAngle));
            data.Add(new Snoop.Data.Distance("Prior size", rec.PriorSize));
            data.Add(new Snoop.Data.Distance("Text size", rec.TextSize));
            data.Add(new Snoop.Data.Distance("X scale", rec.XScale));
        }
Exemple #25
0
        /// <summary>
        /// 创建文本样式
        /// </summary>
        public static ObjectId CreateStyle()
        {
            var TextstyleId = new ObjectId();
            var db          = HostApplicationServices.WorkingDatabase;

            using (var trans = db.TransactionManager.StartTransaction())
            {
                var          st         = (TextStyleTable)trans.GetObject(db.TextStyleTableId, OpenMode.ForWrite);
                const string StyleName  = "LableStyle";
                const string StyleName2 = "MultLableStyle";
                if (st.Has(StyleName) == false)
                {
                    var str = new TextStyleTableRecord
                    {
                        Name           = StyleName,
                        FileName       = "SIMHEI.TTF",
                        ObliquingAngle = 0 * Math.PI / 180,
                        XScale         = 0.67
                    };

                    // 设置TrueType字体(黑体)
                    //---------------------------------------------
                    // 设置SHX字体
                    // str.FileName = "gbenor"
                    //设置大字体.
                    // str.BigFontFileName = "gbcbig"
                    // --------------------------------------------
                    TextstyleId = st.Add(str);
                    trans.AddNewlyCreatedDBObject(str, true);
                    db.Textstyle = TextstyleId;
                }
                if (st.Has(StyleName2) == false)
                {
                    var str = new TextStyleTableRecord
                    {
                        Name           = StyleName2,
                        FileName       = "SIMHEI.TTF",
                        ObliquingAngle = 0 * Math.PI / 180,
                        XScale         = 1
                    };
                    TextstyleId = st.Add(str);
                    trans.AddNewlyCreatedDBObject(str, true);
                    PublicMethod.Instance.MultTextStyleId = str.Id;
                }
                trans.Commit();
            }
            return(TextstyleId);
        }
Exemple #26
0
 setTextStyleXScale(ObjectId idTxtStyle, double xFactor)
 {
     try
     {
         using (Transaction tr = BaseObjs.startTransactionDb())
         {
             TextStyleTableRecord tstr = (TextStyleTableRecord)tr.GetObject(idTxtStyle, OpenMode.ForWrite);
             tstr.XScale = xFactor;
             tr.Commit();
         }
     }
     catch (System.Exception ex)
     {
         BaseObjs.writeDebug(ex.Message + " Txt.cs: line: 698");
     }
 }
Exemple #27
0
        /// <summary>
        /// 设置多行文本的属性为当前文字样式的属性
        /// </summary>
        /// <param name="mtxt">多行文本对象</param>
        public static void SetFromTextStyle(this MText mtxt)
        {
            Database             db    = mtxt.Database;
            var                  trans = db.TransactionManager;
            TextStyleTableRecord str   = (TextStyleTableRecord)trans.GetObject(mtxt.TextStyleId, OpenMode.ForRead);

            if (!mtxt.IsWriteEnabled)
            {
                mtxt.UpgradeOpen();
            }
            mtxt.Rotation   = str.ObliquingAngle;
            mtxt.Annotative = str.Annotative;
            mtxt.SetPaperOrientation(Convert.ToBoolean(str.PaperOrientation));
            mtxt.LineSpacingFactor = str.XScale;
            mtxt.TextHeight        = str.TextSize;
        }
        public void TestAddTextStyle()
        {
            var newId = ObjectId.Null;

            using (var db = AcadDatabase.Active())
            {
                var newTextStyle = new TextStyleTableRecord()
                {
                    Name = "NewTextStyle"
                };
                db.TextStyles.Add(newTextStyle);
                newId = newTextStyle.ObjectId;
            }

            AcadAssert.That.TextStyleTable.Contains(newId);
        }
Exemple #29
0
        upgradePntLabelStyle(string nameLabelStyle, string nameFontFile = "Romans.shx", double xscale = 0.8)
        {
            LabelStyle ls = null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    LabelStyleCollection labelStyles = BaseObjs._civDoc.Styles.LabelStyles.PointLabelStyles.LabelStyles;
                    if (labelStyles.Contains(nameLabelStyle))
                    {
                        labelStyles.Remove(nameLabelStyle);
                    }

                    //Layer.manageLayers(name);

                    TextStyleTableRecord TStr = Txt.getTextStyleTableRecord("L100");
                    if (TStr == null)
                    {
                        TStr = Txt.addTextStyleTableRecord("L100");
                    }

                    TStr.FileName = nameFontFile;
                    TStr.XScale   = xscale;

                    CivilDocument civDoc = BaseObjs._civDoc;

                    ObjectId id = civDoc.Styles.LabelStyles.PointLabelStyles.LabelStyles.Add(nameLabelStyle);

                    ls = (LabelStyle)tr.GetObject(id, OpenMode.ForWrite);
                    ls.Properties.DraggedStateComponents.DisplayType.Value = Autodesk.Civil.LabelContentDisplayType.StackedText;

                    addLocationZcomponent(ls);
                    addPointNumberComponent(ls);
                    addDescriptionComponent(ls);

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(string.Format("{0} Pnt_Style.cs: line: 254", ex.Message));
            }
            return(ls.ObjectId);
        }
        /// <summary>
        /// 查找同名文字样式并返回文字样式Id(如果找不到,则克隆文字样式)
        /// </summary>
        /// <param name="TextStyleId"></param>
        /// <returns></returns>
        public ObjectId FindOrCloneTextStyle(ObjectId TextStyleId)
        {
            TextStyleTableRecord TextStyle = TextStyleId.GetObject(OpenMode.ForRead) as TextStyleTableRecord;
            string TextStyleName           = TextStyle.Name;

            if (TextStyleIdDict.Keys.Contains(TextStyleName))
            {
                return(TextStyleIdDict[TextStyleName]);
            }
            ObjectId NewTextStyleId = GetTextStyleIdByName(TextStyleName);

            if (NewTextStyleId.IsNull)
            {
                NewTextStyleId = CreateTextStyleByClone(TextStyleId);
            }
            TextStyleIdDict.Add(TextStyleName, NewTextStyleId);
            return(NewTextStyleId);
        }
Exemple #31
0
        public void TestgetTextStyle()
        {
            Database            db     = HostApplicationServices.WorkingDatabase;
            Editor              ed     = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions optEnt = new PromptEntityOptions("\n请选择文字");

            optEnt.SetRejectMessage("\n您选择的对象不是文字,请重新选择!");
            optEnt.AddAllowedClass(typeof(DBText), true);
            optEnt.AddAllowedClass(typeof(MText), true);
            PromptEntityResult resEnt = ed.GetEntity(optEnt);

            if (resEnt.Status != PromptStatus.OK)
            {
                return;
            }
            ObjectId entId = resEnt.ObjectId;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity   ent = (Entity)trans.GetObject(entId, OpenMode.ForRead);
                DBText   textEnt;
                MText    mtextEnt;
                ObjectId textStyle;
                try
                {
                    textEnt   = (DBText)ent;
                    textStyle = textEnt.TextStyle;
                }
                catch
                {
                    mtextEnt  = (MText)ent;
                    textStyle = mtextEnt.TextStyle;
                }
                TextStyleTableRecord str = (TextStyleTableRecord)trans.GetObject(textStyle, OpenMode.ForRead);
                if (str.Font.TypeFace == "")
                {
                    Application.ShowAlertDialog("您选择的文字是SHX字体" + "\n字体名:" + str.FileName + "\n大字体名:" + str.BigFontFileName);
                }
                else
                {
                    Application.ShowAlertDialog("您选择的文字是TrueType字体" + "\n字体文件名:" + str.FileName + "\n字体名:" + str.Font.TypeFace);
                }
            }
        }
        public void SetSettings(string styleName, TextStyleTableRecord stdStyle)
        {
            if (Exists(styleName))
                using (Transaction t = targetDB.TransactionManager.StartTransaction())
                {
                    TextStyleTable tst = (TextStyleTable)t.GetObject(targetDB.TextStyleTableId,
                          OpenMode.ForRead);
                    TextStyleTableRecord ts = (TextStyleTableRecord)t.GetObject(tst[styleName],
                           OpenMode.ForWrite);

                    ts.FileName = stdStyle.FileName;
                    ts.Annotative = stdStyle.Annotative;
                    ts.ObliquingAngle = stdStyle.ObliquingAngle;
                    // ts.SetPaperOrientation(stdStyle.PaperOrientation);
                    ts.BigFontFileName = stdStyle.BigFontFileName;
                    ts.TextSize = stdStyle.TextSize;
                    ts.XScale = stdStyle.XScale;
                    ts.IsVertical = stdStyle.IsVertical;
                    t.Commit();
                }
        }
        public void Union(Dictionary<string, ObjectId[]> dicDeleteTextStyles, TextStyleTableRecord resultStyleName)
        {
            using (Transaction tr = targetDB.TransactionManager.StartTransaction())
            {
                foreach (var style in dicDeleteTextStyles)
                {
                    AttributeDefinition[] attdefs = style.Value.Where(n => tr.GetObject(n,
                        OpenMode.ForRead) is AttributeDefinition).Select(n =>
                            (AttributeDefinition)tr.GetObject(n, OpenMode.ForWrite)).ToArray();

                    foreach (AttributeDefinition attdef in attdefs)
                    {
                        attdef.TextStyleId = resultStyleName.ObjectId;
                        // attdef.UpdateMTextAttributeDefinition();

                    }

                    foreach (var _x in style.Value)
                    {
                        DBObject item = tr.GetObject(_x, OpenMode.ForWrite);
                        //Если это размерный стиль
                        if (item is DimStyleTableRecord)
                        {
                            DimStyleTableRecord dstr = (DimStyleTableRecord)item;
                            dstr.Dimtxsty = resultStyleName.ObjectId;
                        }
                        //Если это стиль мультивыноски
                        else if (item is MLeaderStyle)
                        {
                            MLeaderStyle mls = (MLeaderStyle)item;
                            mls.TextStyleId = resultStyleName.ObjectId;
                        }
                        //Если это табличный стиль
                        else if (item is TableStyle)
                        {
                            TableStyle ts = (TableStyle)item;

                            //В цикле проверяем текстовый стиль каждой ячейки таблицы
                            foreach (string cellStyle in ts.CellStyles)
                            {
                                if (ts.TextStyle(cellStyle).Database == null) continue;
                                if (dicDeleteTextStyles.Keys.Contains(GetStyle(ts.TextStyle(cellStyle))
                                     .Name.Trim().ToUpper()))
                                    ts.SetTextStyle(resultStyleName.ObjectId, cellStyle);
                            }
                        }
                        //Если это однострочный текст, не являющийся при этом атрибутом
                        //определения блока
                        else if ((item is DBText) && !(item is AttributeDefinition))
                        {
                            DBText txt = (DBText)item;

                            txt.TextStyleId = resultStyleName.ObjectId;
                            txt.Oblique = 0;

                            //if (txt is AttributeReference)
                            //   ((AttributeReference)txt).UpdateMTextAttribute();

                        }
                        //Если это многострочный текст
                        else if (item is MText)
                        {
                            MText txt = (MText)item;
                            txt.TextStyleId = resultStyleName.ObjectId;
                        }
                        //Если это таблица
                        else if (item is Table)
                        {
                            Table table = (Table)item;
                            string[] styleNames = dicDeleteTextStyles.Keys.ToArray();
                            //Сначала проверяю, какие стили текста назначены столбцам
                            for (int i = 0; i < table.NumColumns; i++)
                                if (styleNames.Contains(table.GetCellStyle(-1, i).ToUpper().Trim()))
                                {
                                    try
                                    {
                                        table.SetCellStyle(-1, i, resultStyleName.Name);
                                    }
                                    catch { }

                                }
                            //Теперь проверяю, какие стили текста назначены строкам
                            for (int i = 0; i < table.NumRows; i++)
                                if (styleNames.Contains(table.GetCellStyle(i, -1).ToUpper().Trim()))
                                {

                                    try
                                    {
                                        table.SetCellStyle(i, -1, resultStyleName.Name);
                                    }
                                    catch { }
                                }
                            //Анализируем каждую ячейку таблицы
                            //Цикл по столбцам
                            for (int i = 0; i < table.NumColumns; i++)
                            {
                                //Цикл по строкам
                                for (int k = 0; k < table.NumRows; k++)
                                {
                                    //Анализируем конкретную ячейку таблицы
                                    if (styleNames.Contains(table.GetCellStyle(k, i).ToUpper().Trim()))
                                    {

                                        try
                                        {
                                            table.SetCellStyle(k, i, resultStyleName.Name);
                                        }
                                        catch { }
                                    }
                                }
                            }
                        }
                    }

                    if (CanBeRemoved(style.Key))
                    {
                        TextStyleTableRecord tsr = (TextStyleTableRecord)tr.GetObject(GetStyleByName(style.Key), OpenMode.ForWrite, true);
                        tsr.Erase();
                    }

                }
                tr.Commit();
            }
        }
 //创建building编号的文本样式
 public static ObjectId GetDefaultStyleId()
 {
     Document doc = Application.DocumentManager.MdiActiveDocument;
     Database db = doc.Database;
     Editor ed = doc.Editor;
     using (Transaction newTransaction = doc.Database.TransactionManager.StartTransaction())
     {
         TextStyleTable newTextStyleTable = newTransaction.GetObject(doc.Database.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
         if (!newTextStyleTable.Has("HEATSOURCE"))  //The TextStyle is currently not in the database
         {
             newTextStyleTable.UpgradeOpen();
             var newTextStyleTableRecord = new TextStyleTableRecord();
             newTextStyleTableRecord.FileName = "Arial";
             newTextStyleTableRecord.Name = "HEATSOURCE";
             newTextStyleTable.Add(newTextStyleTableRecord);
             newTransaction.AddNewlyCreatedDBObject(newTextStyleTableRecord, true);
         }
         newTransaction.Commit();
         return newTextStyleTable["HEATSOURCE"];
     }
 }