qq1254582201 发表于 2021-4-23 00:27:00

【转载】打印记录 Log AutoCAD's Plotting

One of the technical issues CAD managers oftern ask thenself is how do I tracking plottings done through .
There are many ways to do that. AutoCAD itself provides plot and publish logging (via Options dialog box-> plot and Publish tab). There be other software that can monitor printing tasks sent to one or more printers...
With AutoCD .NET API, we can fairly easily to build a custom plotting logging application, which is the topic of this article.
The Autodesk.AutoCAD.PlottingServices.PlotReactorManager class provides all the functionalities needed to track plotting from an running AutoCAD session. This class exposes a series of events that fire from the beginning of plotting to the end of plotting. Some plotting information that would be the interest of plot tracking is exposed through various EventArgs. Therefore, simply handling approriate events and retrieving needed plotting information, then saving the information into some sort of data store, these all a custom plot tracking application needs to do.
Let's look at the code.
First, I define a data class that hold plotting information I want to track when AutoCAD does a plotting:

using System;
using Autodesk.AutoCAD.DatabaseServices;
namespace TrackAcadPlotting
{
    public class PlotLog
    {
      public string DwgName { set; get; }
      public string DwgPath { set; get; }
      public int CopyCount { set; get; }
      public string PlotterName { set; get; }
      public DateTime PlottingTime { set; get; }
      public PlotPaperUnit PaperUnit { set; get; }
      public double PaperWidth { set; get; }
      public double PaperHeight { set; get; }
      public string MediaName { set; get; }
      public string UserName { set; get; }
      public string ComputerName { set; get; }
    }
}
The data store used to save plot tracking data can be different, from file (plain text, Xml...), to database. AutoCAD built-in plotting log is a plain text file, usually saved where the the plotted drawing is, if enabled. Of course these kind of plotting logs are not convenient for plotting management: they scattered everywhere. In general, file based store is not very ideal solution with this custom plot tracking application: the user who runs AutoCAD, thus the plot tracking application, must have read/write permission to the log file. So, it could be a security hole, if you want this plot tracking to be a serious CAD management tool. Ideally, the data store would be some sort of central database.
In order for this custom plot tracking application to be able to save plotting log to different data store, I created an Interface called IPlottingLogWriter. For different data store, we can write different code to save the plotting log, as long as the IPlottingLogWriter is implemented. In this article, the the simplicity, I implemented an file data store, called PlottingLogFileWriter to save plotting log to a text file. As aforementioned, I could implement the IPlottingLogWriter to save the data to database, or send the plotting log data to a WCF service to be saved somewhere. This way, no matter what data storage mechanism the application uses, the code to track plotting will not have to be changed.
Here is the Interface and its implementing:
The interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrackAcadPlotting
{
    public interface IPlottingLogWriter
    {
      void SavePlottingLog(PlotLog log);
    }
}The interface implementing:

using System;
using System.IO;
namespace TrackAcadPlotting
{
    public class PlottingLogFileWriter : IPlottingLogWriter
    {
      private string _logFolder;
      public PlottingLogFileWriter(string folderPath)
      {
            _logFolder = folderPath;
            //Create log folder:
            if (!Directory.Exists(_logFolder))
            {
                Directory.CreateDirectory(_logFolder);
            }
      }
      #region IPlottingLogWriter Members
      public void SavePlottingLog(PlotLog log)
      {
            string fileName = _logFolder +
                        "\\PlotTracking_" +
                        DateTime.Today.ToString("yyyy-MM-dd") +
                        ".txt";
            using (FileStream st = new FileStream(
                fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
            {
                using (StreamWriter writer = new StreamWriter(st))
                {
                  writer.WriteLine(
                        "-------------Log begins------------------");
                  writer.WriteLine("Drawing: {0}",
                        log.DwgName);
                  writer.WriteLine("File path: {0}",
                        log.DwgPath);
                  writer.WriteLine("Plotting copy: {0}",
                        log.CopyCount);
                  writer.WriteLine("Plotter name: {0}",
                        log.PlotterName);
                  writer.WriteLine("Paper unit: {0}",
                        log.PaperUnit.ToString());
                  writer.WriteLine("Paper width: {0}",
                        log.PaperWidth.ToString("#######0.00") + "mm");
                  writer.WriteLine("Paper hight: {0}",
                        log.PaperHeight.ToString("#######0.00") + "mm");
                  writer.WriteLine("Media name: {0}",
                        log.MediaName);
                  writer.WriteLine("User name: {0}",
                        log.UserName);
                  writer.WriteLine("CAD computer: {0}",
                        log.ComputerName);
                  writer.WriteLine(
                        "-------------Log ends--------------------");
                  writer.Flush();
                  writer.Close();
                }
            }
      }
      #endregion
    }
}Finally, this is the class "TrackPlotting" that does the actual work:

using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.PlottingServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;


namespace TrackAcadPlotting
{
   public class TrackPlotting: IExtensionApplication
   {
       private static PlotReactorManager _plotManager;
       private static IPlottingLogWriter _logWriter;
       private static bool _cancelled=false;
       private static PlotLog _log=null;
       #region IExtensionApplication Members
       private List _plotters = null;
       public void Initialize()
       {
         Document dwg = Autodesk.AutoCAD.ApplicationServices.
               Application.DocumentManager.MdiActiveDocument;
         //Get plotter names to track
         _plotters = GetPlotterNames();
         try
         {
               //Hard-coded log file folder path.
               //In production, the file path could be
               //set in acad.exe.confg or using other
               //configuing technique
               //Note: here I instantiated an PlottingLogFileWriter
               //I can also instantiate an PlottingLogSqlServerWriter,
               //if it is available
               _logWriter = new PlottingLogFileWriter("E:\\Temp\\PlottingTrack");
         }
         catch
         {
               if (dwg != null)
               {
                   dwg.Editor.WriteMessage(
                     "\nInitializing plot tracking log writer faailed.");
               }
               return;
         }
         //Hook up event handlers
         _plotManager = new PlotReactorManager();
         _plotManager.BeginPlot +=
               new BeginPlotEventHandler(PlotManager_BeginPlot);
         _plotManager.BeginDocument +=
               new BeginDocumentEventHandler(PlotManager_BeginDocument);
         _plotManager.BeginPage +=
               new BeginPageEventHandler(PlotManager_BeginPage);
         _plotManager.EndPage +=
               new EndPageEventHandler(PlotManager_EndPage);
         _plotManager.EndDocument +=
               new EndDocumentEventHandler(PlotManager_EndDocument);
         _plotManager.EndPlot +=
               new EndPlotEventHandler(PlotManager_EndPlot);
         _plotManager.PageCancelled +=
               new PageCancelledEventHandler(PlotManager_PageCancelled);
         _plotManager.PlotCancelled +=
               new PlotCancelledEventHandler(PlotManager_PlotCancelled);
         if (dwg != null)
         {
               dwg.Editor.WriteMessage("\nPlot tracking has been initialized.");
         }
       }
       public void Terminate()
       {
         //Remove event handlers
         _plotManager.BeginPlot -=
               new BeginPlotEventHandler(PlotManager_BeginPlot);
         _plotManager.BeginDocument -=
               new BeginDocumentEventHandler(PlotManager_BeginDocument);
         _plotManager.BeginPage -=
               new BeginPageEventHandler(PlotManager_BeginPage);
         _plotManager.EndPage -=
               new EndPageEventHandler(PlotManager_EndPage);
         _plotManager.EndDocument -=
               new EndDocumentEventHandler(PlotManager_EndDocument);
         _plotManager.EndPlot +=
               new EndPlotEventHandler(PlotManager_EndPlot);
         _plotManager.PageCancelled -=
               new PageCancelledEventHandler(PlotManager_PageCancelled);
         _plotManager.PlotCancelled -=
               new PlotCancelledEventHandler(PlotManager_PlotCancelled);
       }
       #endregion
       #region private methods
       private List GetPlotterNames()
       {
         List plotters = new List();
         //A plotter name list could be stored somewhere
         //and loaded in, such as acad.exe.config (user may change it!)
         //Or centrally stored in a DB (so only manager can set/change it)
         //Here I simply hard-coded one plotter name
         plotters.Add("CutePDF Writer");
         return plotters;
       }
       private void GetUserComputerName(
         out string userName, out string computerName)
       {
         userName = "";
         computerName = "";
         string domain = System.Environment.UserDomainName;
         string user = System.Environment.UserName;
         userName = domain + "\" + user;
         computerName = System.Environment.MachineName;
       }
       private bool IsTracedDevice(string plotterName)
       {
         foreach (string plt in _plotters)
         {
               if (plt.Equals(plotterName,
                   StringComparison.CurrentCultureIgnoreCase))
               {
                   return true;
               }
         }
         return false;
       }
       #endregion
       #region Private methods: plotting event handlers
       private void PlotManager_BeginPlot(object sender, BeginPlotEventArgs e)
       {
         _cancelled = false;
         if (e.PlotType == Autodesk.AutoCAD.
               PlottingServices.PlotType.BackgroundPlot
               || e.PlotType == Autodesk.AutoCAD.
               PlottingServices.PlotType.Plot)
         {
               _log = new PlotLog();
               string user;
               string comp;
               GetUserComputerName(out user, out comp);
               _log.UserName = user;
               _log.ComputerName = comp;
         }
         else
         {
               _log = null;
         }
       }
       private void PlotManager_BeginDocument(
         object sender, BeginDocumentEventArgs e)
       {
         if (e.PlotToFile)
         {
               _log = null;
               return;
         }
         _log.DwgName = Path.GetFileName(e.DocumentName);
         _log.DwgPath = Path.GetDirectoryName(e.DocumentName);
         _log.CopyCount = e.Copies;
       }
       private void PlotManager_BeginPage(
         object sender, BeginPageEventArgs e)
       {
         if (_log == null) return;
         if (e.PlotInfo.ValidatedConfig != null)
         {
               if (e.PlotInfo.ValidatedConfig.IsPlotToFile)
               {
                   _log = null;
                   return;
               }
               _log.PlotterName = e.PlotInfo.ValidatedConfig.DeviceName;
         }
         if (e.PlotInfo.ValidatedSettings != null)
         {
               _log.PaperUnit = e.PlotInfo.ValidatedSettings.PlotPaperUnits;
               _log.MediaName = e.PlotInfo.ValidatedSettings.CanonicalMediaName;
               Point2d pt = e.PlotInfo.ValidatedSettings.PlotPaperSize;
               if (pt.X > pt.Y)
               {
                   _log.PaperWidth = pt.X;
                   _log.PaperHeight = pt.Y;
               }
               else
               {
                   _log.PaperWidth = pt.Y;
                   _log.PaperHeight = pt.X;
               }
         }
       }
       private void PlotManager_EndPage(
         object sender, EndPageEventArgs e)
       {
         if (e.Status != SheetCancelStatus.Continue) _cancelled = true;
       }
       private void PlotManager_EndDocument(
         object sender, EndDocumentEventArgs e)
       {
         if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
       }
       private void PlotManager_EndPlot(
         object sender, EndPlotEventArgs e)
       {
         if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
         if (_cancelled)
         {
               _log = null;
               _cancelled = false;
               return;
         }
         if (_log == null) return;
         _log.PlottingTime = DateTime.Now;
         //Debug code here
         Document dwg = Autodesk.AutoCAD.ApplicationServices.
               Application.DocumentManager.MdiActiveDocument;
         Editor ed = dwg.Editor;
         ed.WriteMessage("\nPlotted by: {0}", _log.UserName);
         ed.WriteMessage("\nPlotted on: {0}", _log.PlotterName);
         ed.WriteMessage("\nDwg Location: {0}", _log.DwgPath);
         ed.WriteMessage("\nPlotted Dwg: {0}", _log.DwgName);
         ed.WriteMessage("\nMedia: {0}", _log.MediaName);
         ed.WriteMessage("\nMedia size: " +
               _log.PaperWidth.ToString("#####0.00") +
               " (W) x " +
               _log.PaperHeight.ToString("#####0.00") + " (H)");
         ed.WriteMessage("\nCopy Count: {0}", _log.CopyCount);
         //Save Plotting log, if the plotting plotter is on printer list;
         if (IsTracedDevice(_log.PlotterName))
         {
               _logWriter.SavePlottingLog(_log);
         }
       }
       private void PlotManager_PlotCancelled(object sender, EventArgs e)
       {
         _cancelled = true;
       }
       private void PlotManager_PageCancelled(object sender, EventArgs e)
       {
         _cancelled = true;
       }
       #endregion
   }
}

Some descriptions of the code:
Line 16: this class implements IExtensionApplication. That means, as soon as the assembly is loaded, the code starts monitoring plotting done in the AutoCAD session.
Line 25 and Line 122 - 133: these lines of code defines a list of plotter/printer name that I want to track. The name should be the same as I can see in the printer dropdown list of AutoCAD's plot dialog box. Only plotters in this list is tracked.
Line 44: Notice the variable _logWriter is declared as IPlottingLogWriter, but here it points to a PlottingLogFileWriter (new PlottingLogFileWriter()). It is possible to declare the differently implemented IPlottingLogWriter in acad.exe.config, so that this class will be truly not affected when a new implemented log-writer is available/changed.
The rest of code would be quite obvious, no extra explanation is necessary.
This video clip shows how it works. Note, since I used CutePDF virtual plotter, each time after the plotting is done (e.g. the PDF has been produced), I simply cancelled the "Save As" dialog box. By then the plotting from AutoCAD has already completed, thus cancelling saving PDF file has no affect to the plot tracking process.
At my work, similar code is used to monitor AutoCAD plotting to some expensive color plotters office-wide. The plotting logs are saved to database and can be browsed by managers through a web application.
Finally, I'd like to thank Kean Walmsley for recommending me the VS addin tool CopySourceToHtml, which solves my code posting issue.
**** Hidden Message *****
页: [1]
查看完整版本: 【转载】打印记录 Log AutoCAD's Plotting