Revit二次开发示例:AutoStamp

该示例中,在Revit启动时添加打印事件,在打印时向模型添加水印,打印完成后删除该水印。

 

#region Namespaces
using System;
using System.Collections.Generic;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion

namespace AutoStamp
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    [Journaling(JournalingMode.NoCommandData)]
    class App : IExternalApplication
    {
        EventsReactor m_eventsReactor;

        public Result OnStartup(UIControlledApplication a)
        {
            m_eventsReactor = new EventsReactor();
            a.ControlledApplication.ViewPrinting+=new EventHandler<Autodesk.Revit.DB.Events.ViewPrintingEventArgs>(m_eventsReactor.AppViewPrinting);
            a.ControlledApplication.ViewPrinted += new EventHandler<Autodesk.Revit.DB.Events.ViewPrintedEventArgs>(m_eventsReactor.AppViewPrinted);
            return Result.Succeeded;
        }

        public Result OnShutdown(UIControlledApplication a)
        {
            m_eventsReactor.CloseLogFiles();

            a.ControlledApplication.ViewPrinting -= new EventHandler<Autodesk.Revit.DB.Events.ViewPrintingEventArgs>(m_eventsReactor.AppViewPrinting);
            a.ControlledApplication.ViewPrinted -= new EventHandler<Autodesk.Revit.DB.Events.ViewPrintedEventArgs>(m_eventsReactor.AppViewPrinted);
            return Result.Succeeded;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;

namespace AutoStamp
{
    public sealed class EventsReactor
    {
        private TextWriterTraceListener m_eventLog;
        string m_assemblyPath;
        ElementId m_newTextNoteId;

        public EventsReactor()
        {
            m_assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }

        public void CloseLogFiles()
        {
            Trace.Flush();
            Trace.Close();

            Trace.Flush();
            if (null != m_eventLog)
            {
                Trace.Listeners.Remove(m_eventLog);
                m_eventLog.Flush();
                m_eventLog.Close();
            }
        }

        public void AppViewPrinting(object sender, ViewPrintingEventArgs e)
        {
            if (null == m_eventLog)
            {
                SetupLogFiles();
            }

            Trace.WriteLine(System.Environment.NewLine + "View Print Start: -----------------------------");
            DumpEventArguments(e);

            bool faileOccur = false;
            try
            {
                string strText = string.Format("Printer Name: {0} {1}User Name: {2}",
                    e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName);

#if !(Debug || DEBUG)
                strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#endif

                Transaction eventTransaction = new Transaction(e.Document, "External Tool");
                eventTransaction.Start();
                TextNote newTextNote = e.Document.Create.NewTextNote(
                    e.View,
                    new XYZ(0, 0, 0),
                    new XYZ(1, 0, 0),
                    new XYZ(0, 1, 0),
                    1,
                    TextAlignFlags.TEF_ALIGN_CENTER,
                    strText
                    );
                eventTransaction.Commit();

                if (null != newTextNote)
                {
                    Trace.WriteLine("Create TextNote element successfully...");
                    m_newTextNoteId = new ElementId(newTextNote.Id.IntegerValue);
                }
                else
                {
                    faileOccur = true;
                }

            }
            catch (Exception ex)
            {
                faileOccur = true;
                Trace.WriteLine("Exception occured when creating TextNote, print will be cancelled, ex: " + ex.Message);
            }
            finally
            {
                if (faileOccur && e.Cancellable)
                {
                    e.Cancel();
                }
            }
        }

        public void AppViewPrinted(object sender, ViewPrintedEventArgs e)
        {
            Trace.WriteLine(System.Environment.NewLine + "View Print End: ------");
            
            DumpEventArguments(e);
            if (RevitAPIEventStatus.Cancelled != e.Status)
            {
                Transaction eventTransaction = new Transaction(e.Document, "External Tool");
                eventTransaction.Start();
                e.Document.Delete(m_newTextNoteId);
                eventTransaction.Commit();
                Trace.WriteLine("Succeeded to delete the created TextNote element.");
            }
        }

        private void SetupLogFiles()
        {
            if (null != m_eventLog)
            {
                return;
            }

            string printEventsLogFile = Path.Combine(m_assemblyPath, "PrintEventsLog.txt");
            if (File.Exists(printEventsLogFile))
            {
                File.Delete(printEventsLogFile);
            }

            m_eventLog = new TextWriterTraceListener(printEventsLogFile);
            Trace.Listeners.Add(m_eventLog);
            Trace.AutoFlush = true;
        }


        private static void DumpEventArguments(RevitAPIEventArgs eventArgs)
        {
            if (eventArgs.GetType().Equals(typeof(ViewPrintingEventArgs)))
            {
                Trace.WriteLine("ViewPrintingEventArgs Parameters ----->");
                ViewPrintingEventArgs args = eventArgs as ViewPrintingEventArgs;
                Trace.WriteLine("    TotalViews          : " + args.TotalViews);
                Trace.WriteLine("    View Index          : " + args.Index);
                Trace.WriteLine("    View Information    : ");
                DumpViewInfo(args.View, "       ");
            }
            else if (eventArgs.GetType().Equals(typeof(ViewPrintedEventArgs)))
            {
                Trace.WriteLine("ViewPrintedEventArgs Parameters ------>");
                ViewPrintedEventArgs args = eventArgs as ViewPrintedEventArgs;
                Trace.WriteLine("     Event Status          : " + args.Status);
                Trace.WriteLine("     TotalViews            : " + args.Status);
                Trace.WriteLine("     View Index            : " + args.Status);
                Trace.WriteLine("     View Information      : ");
            }
            else
            {
                // no handling for other arguments
            }
        }

        private static void DumpViewInfo(View view, string prefix)
        {
            Trace.WriteLine(string.Format("{0} ViewName: {1}, ViewType: {2}", prefix, view.ViewName, view.ViewType));
        }


    }
}
原文地址:https://www.cnblogs.com/xpvincent/p/3600632.html