- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Geometry;
- using Autodesk.AutoCAD.Runtime;
- using System.IO;
- namespace BlockPreviews
- {
- publicclassCommands
- {
- [CommandMethod("GBP", CommandFlags.Session)]
- staticpublicvoid GenerateBlockPreviews()
- {
- Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
- PromptFileNameResult res = ed.GetFileNameForOpen(
- "Select file for which to generate previews"
- );
- if (res.Status != PromptStatus.OK) return;
- Document doc = null;
- try
- {
- doc = Application.DocumentManager.Open(res.StringResult, false);
- }
- catch
- {
- ed.WriteMessage("\nUnable to read drawing.");
- return;
- }
- Database db = doc.Database;
- string path = Path.GetDirectoryName(res.StringResult),
- name = Path.GetFileName(res.StringResult),
- iconPath = path + "\" + name + " icons";
- int numIcons = 0;
- Transaction tr = doc.TransactionManager.StartTransaction();
- using (tr)
- {
- BlockTable table = (BlockTable)tr.GetObject(
- db.BlockTableId, OpenMode.ForRead
- );
- foreach (ObjectId blkId in table)
- {
- BlockTableRecord blk = (BlockTableRecord)tr.GetObject(
- blkId, OpenMode.ForRead
- );
- // Ignore layouts and anonymous blocks
- if (blk.IsLayout || blk.IsAnonymous) continue;
- // Attempt to generate an icon, where one doesn't exist
- if (blk.PreviewIcon == null)
- {
- object ActiveDocument = doc.AcadDocument;
- object[] data = { "_.BLOCKICON " + blk.Name + "\n" };
- ActiveDocument.GetType().InvokeMember(
- "SendCommand",
- System.Reflection.BindingFlags.InvokeMethod,
- null, ActiveDocument, data
- );
- }
- // Hopefully we now have an icon
- if (blk.PreviewIcon != null)
- {
- // Create the output directory, if it isn't yet there
- if (!Directory.Exists(iconPath))
- Directory.CreateDirectory(iconPath);
- // Save the icon to our out directory
- blk.PreviewIcon.Save(iconPath + "\" + blk.Name + ".bmp");
- // Increment our icon counter
- numIcons++;
- }
- }
- tr.Commit();
- }
- doc.CloseAndDiscard();
- ed.WriteMessage(
- "\n{0} block icons saved to "{1}".", numIcons, iconPath
- );
- }
- }
- }
|