using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(Rivilis.CalcPages))]
namespace Rivilis
{
public class CalcPages
{
[CommandMethod("CalcPages")]
public void MyCommand() // This method can have any name
{
Document doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null) return;
Editor ed = doc.Editor;
Database db = doc.Database;
ObjectIdCollection idsAttPages = new ObjectIdCollection();
int nPages = 0;
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
if (bt.Has("MainTitle"))
{
foreach (ObjectId idBtr in bt)
{
BlockTableRecord btr = tr.GetObject(idBtr, OpenMode.ForRead) as BlockTableRecord;
if (btr.Name.Contains("Title"))
{
ObjectIdCollection idsBr = btr.GetBlockReferenceIds(false, true);
nPages += idsBr.Count;
foreach (ObjectId idBr in idsBr)
{
BlockReference br = tr.GetObject(idBr, OpenMode.ForRead) as BlockReference;
AttributeCollection idsAtt = br.AttributeCollection;
foreach (ObjectId idAtt in idsAtt)
{
AttributeReference att = tr.GetObject(idAtt, OpenMode.ForRead) as AttributeReference;
if (att.Tag == "Pages") idsAttPages.Add(idAtt);
}
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////
// Вписывать количество страниц можно только после того, как мы их ВСЕ подсчитали!!!
/////////////////////////////////////////////////////////////////////////////////////
if (idsAttPages.Count > 0)
{
foreach (ObjectId idAtt in idsAttPages)
{
AttributeReference att = tr.GetObject(idAtt, OpenMode.ForWrite) as AttributeReference;
att.TextString = nPages.ToString();
}
}
tr.Commit();
}
}
}
}