Under certain conditions, the text alignment set to a DBText does not take effect. To ensure that the alignment is correct, the "DBText.AdjustAlignment" method is to be used. This method makes use of the working database internally for its working. So, it is important to set the working database if the database to which the DBText is being added is not already the working database.
Here is a sample code :
[CommandMethod("TextAlign")]
public void TextAlign()
{
Document activeDoc = Application.DocumentManager.MdiActiveDocument;
// For adding a text with alignment to the current document
bool isInMemory = false;
Database db = activeDoc.Database;
// For adding a text to an in-memory database
//bool isInMemory = true;
//Database db = new Database(true, false);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(
db.BlockTableId,
OpenMode.ForRead
) as BlockTable;
BlockTableRecord mSpace = tr.GetObject
(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite
) as BlockTableRecord;
DBText dbText = new DBText();
dbText.SetDatabaseDefaults(db);
dbText.Position = Point3d.Origin;
dbText.Height = 5.0;
dbText.TextString = "Autodesk";
dbText.HorizontalMode = TextHorizontalMode.TextRight;
dbText.AlignmentPoint = Point3d.Origin;
if (isInMemory)
{ // For adding a text with an alignment to an in-memory database
// set the working database before using AdjustAlignment
Database prevWorkingDb = HostApplicationServices.WorkingDatabase;
HostApplicationServices.WorkingDatabase = db;
dbText.AdjustAlignment(db);
HostApplicationServices.WorkingDatabase = prevWorkingDb;
}
else
{ // For adding a text with alignment to the current document
// working database is already set
dbText.AdjustAlignment(db);
}
mSpace.AppendEntity(dbText);
tr.AddNewlyCreatedDBObject(dbText, true);
tr.Commit();
}
if (isInMemory)
{
db.SaveAs("C:\\Temp\\Test.dwg", DwgVersion.Current);
db.Dispose();
}
}