明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 425|回复: 0

[资源] 【转载】打印记录 Log AutoCAD's Plotting

[复制链接]
发表于 2021-4-23 00:27 | 显示全部楼层 |阅读模式
本帖最后由 qq1254582201 于 2021-4-23 11:18 编辑
One of the technical issues CAD managers oftern ask thenself is how do I tracking plottings done through AutoCAD.
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:
  1. using System;
  2. using Autodesk.AutoCAD.DatabaseServices;

  3. namespace TrackAcadPlotting
  4. {
  5.     public class PlotLog
  6.     {
  7.         public string DwgName { set; get; }
  8.         public string DwgPath { set; get; }
  9.         public int CopyCount { set; get; }
  10.         public string PlotterName { set; get; }
  11.         public DateTime PlottingTime { set; get; }
  12.         public PlotPaperUnit PaperUnit { set; get; }
  13.         public double PaperWidth { set; get; }
  14.         public double PaperHeight { set; get; }
  15.         public string MediaName { set; get; }
  16.         public string UserName { set; get; }
  17.         public string ComputerName { set; get; }
  18.     }
  19. }







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:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace TrackAcadPlotting
  6. {
  7.     public interface IPlottingLogWriter
  8.     {
  9.         void SavePlottingLog(PlotLog log);
  10.     }
  11. }
The interface implementing:
  1. using System;
  2. using System.IO;

  3. namespace TrackAcadPlotting
  4. {
  5.     public class PlottingLogFileWriter : IPlottingLogWriter
  6.     {
  7.         private string _logFolder;

  8.         public PlottingLogFileWriter(string folderPath)
  9.         {
  10.             _logFolder = folderPath;

  11.             //Create log folder:
  12.             if (!Directory.Exists(_logFolder))
  13.             {
  14.                 Directory.CreateDirectory(_logFolder);
  15.             }
  16.         }

  17.         #region IPlottingLogWriter Members

  18.         public void SavePlottingLog(PlotLog log)
  19.         {
  20.             string fileName = _logFolder +
  21.                         "\\PlotTracking_" +
  22.                         DateTime.Today.ToString("yyyy-MM-dd") +
  23.                         ".txt";

  24.             using (FileStream st = new FileStream(
  25.                 fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
  26.             {
  27.                 using (StreamWriter writer = new StreamWriter(st))
  28.                 {
  29.                     writer.WriteLine(
  30.                         "-------------Log begins------------------");

  31.                     writer.WriteLine("Drawing: {0}",
  32.                         log.DwgName);
  33.                     writer.WriteLine("File path: {0}",
  34.                         log.DwgPath);
  35.                     writer.WriteLine("Plotting copy: {0}",
  36.                         log.CopyCount);
  37.                     writer.WriteLine("Plotter name: {0}",
  38.                         log.PlotterName);
  39.                     writer.WriteLine("Paper unit: {0}",
  40.                         log.PaperUnit.ToString());
  41.                     writer.WriteLine("Paper width: {0}",
  42.                         log.PaperWidth.ToString("#######0.00") + "mm");
  43.                     writer.WriteLine("Paper hight: {0}",
  44.                         log.PaperHeight.ToString("#######0.00") + "mm");
  45.                     writer.WriteLine("Media name: {0}",
  46.                         log.MediaName);
  47.                     writer.WriteLine("User name: {0}",
  48.                         log.UserName);
  49.                     writer.WriteLine("CAD computer: {0}",
  50.                         log.ComputerName);

  51.                     writer.WriteLine(
  52.                         "-------------Log ends--------------------");

  53.                     writer.Flush();
  54.                     writer.Close();
  55.                 }
  56.             }
  57.         }

  58.         #endregion
  59.     }
  60. }
Finally, this is the class "TrackPlotting" that does the actual work:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;

  4. using Autodesk.AutoCAD.ApplicationServices;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.PlottingServices;
  7. using Autodesk.AutoCAD.Geometry;
  8. using Autodesk.AutoCAD.Runtime;

  9. [assembly: CommandClass(typeof(TrackAcadPlotting.TrackPlotting))]
  10. [assembly: ExtensionApplication(typeof(TrackAcadPlotting.TrackPlotting))]

  11. namespace TrackAcadPlotting
  12. {
  13.    public class TrackPlotting: IExtensionApplication
  14.    {
  15.        private static PlotReactorManager _plotManager;
  16.        private static IPlottingLogWriter _logWriter;
  17.        private static bool _cancelled=false;
  18.        private static PlotLog _log=null;

  19.        #region IExtensionApplication Members

  20.        private List<string> _plotters = null;

  21.        public void Initialize()
  22.        {
  23.            Document dwg = Autodesk.AutoCAD.ApplicationServices.
  24.                Application.DocumentManager.MdiActiveDocument;

  25.            //Get plotter names to track
  26.            _plotters = GetPlotterNames();

  27.            try
  28.            {
  29.                //Hard-coded log file folder path.
  30.                //In production, the file path could be
  31.                //set in acad.exe.confg or using other
  32.                //configuing technique
  33.                //Note: here I instantiated an PlottingLogFileWriter
  34.                //I can also instantiate an PlottingLogSqlServerWriter,
  35.                //if it is available
  36.                _logWriter = new PlottingLogFileWriter("E:\\Temp\\PlottingTrack");
  37.            }
  38.            catch
  39.            {
  40.                if (dwg != null)
  41.                {
  42.                    dwg.Editor.WriteMessage(
  43.                        "\nInitializing plot tracking log writer faailed.");
  44.                }

  45.                return;
  46.            }

  47.            //Hook up event handlers
  48.            _plotManager = new PlotReactorManager();

  49.            _plotManager.BeginPlot +=
  50.                new BeginPlotEventHandler(PlotManager_BeginPlot);

  51.            _plotManager.BeginDocument +=
  52.                new BeginDocumentEventHandler(PlotManager_BeginDocument);

  53.            _plotManager.BeginPage +=
  54.                new BeginPageEventHandler(PlotManager_BeginPage);

  55.            _plotManager.EndPage +=
  56.                new EndPageEventHandler(PlotManager_EndPage);

  57.            _plotManager.EndDocument +=
  58.                new EndDocumentEventHandler(PlotManager_EndDocument);

  59.            _plotManager.EndPlot +=
  60.                new EndPlotEventHandler(PlotManager_EndPlot);

  61.            _plotManager.PageCancelled +=
  62.                new PageCancelledEventHandler(PlotManager_PageCancelled);

  63.            _plotManager.PlotCancelled +=
  64.                new PlotCancelledEventHandler(PlotManager_PlotCancelled);

  65.            if (dwg != null)
  66.            {
  67.                dwg.Editor.WriteMessage("\nPlot tracking has been initialized.");
  68.            }
  69.        }

  70.        public void Terminate()
  71.        {
  72.            //Remove event handlers
  73.            _plotManager.BeginPlot -=
  74.                new BeginPlotEventHandler(PlotManager_BeginPlot);

  75.            _plotManager.BeginDocument -=
  76.                new BeginDocumentEventHandler(PlotManager_BeginDocument);

  77.            _plotManager.BeginPage -=
  78.                new BeginPageEventHandler(PlotManager_BeginPage);

  79.            _plotManager.EndPage -=
  80.                new EndPageEventHandler(PlotManager_EndPage);

  81.            _plotManager.EndDocument -=
  82.                new EndDocumentEventHandler(PlotManager_EndDocument);

  83.            _plotManager.EndPlot +=
  84.                new EndPlotEventHandler(PlotManager_EndPlot);

  85.            _plotManager.PageCancelled -=
  86.                new PageCancelledEventHandler(PlotManager_PageCancelled);

  87.            _plotManager.PlotCancelled -=
  88.                new PlotCancelledEventHandler(PlotManager_PlotCancelled);
  89.        }

  90.        #endregion

  91.        #region private methods

  92.        private List<string> GetPlotterNames()
  93.        {
  94.            List<string> plotters = new List<string>();

  95.            //A plotter name list could be stored somewhere
  96.            //and loaded in, such as acad.exe.config (user may change it!)
  97.            //Or centrally stored in a DB (so only manager can set/change it)
  98.            //Here I simply hard-coded one plotter name
  99.            plotters.Add("CutePDF Writer");

  100.            return plotters;
  101.        }

  102.        private void GetUserComputerName(
  103.            out string userName, out string computerName)
  104.        {
  105.            userName = "";
  106.            computerName = "";

  107.            string domain = System.Environment.UserDomainName;
  108.            string user = System.Environment.UserName;

  109.            userName = domain + "\" + user;
  110.            computerName = System.Environment.MachineName;
  111.        }

  112.        private bool IsTracedDevice(string plotterName)
  113.        {
  114.            foreach (string plt in _plotters)
  115.            {
  116.                if (plt.Equals(plotterName,
  117.                    StringComparison.CurrentCultureIgnoreCase))
  118.                {
  119.                    return true;
  120.                }
  121.            }

  122.            return false;
  123.        }

  124.        #endregion

  125.        #region Private methods: plotting event handlers

  126.        private void PlotManager_BeginPlot(object sender, BeginPlotEventArgs e)
  127.        {
  128.            _cancelled = false;

  129.            if (e.PlotType == Autodesk.AutoCAD.
  130.                PlottingServices.PlotType.BackgroundPlot
  131.                || e.PlotType == Autodesk.AutoCAD.
  132.                PlottingServices.PlotType.Plot)
  133.            {

  134.                _log = new PlotLog();

  135.                string user;
  136.                string comp;
  137.                GetUserComputerName(out user, out comp);

  138.                _log.UserName = user;
  139.                _log.ComputerName = comp;
  140.            }
  141.            else
  142.            {
  143.                _log = null;
  144.            }
  145.        }

  146.        private void PlotManager_BeginDocument(
  147.            object sender, BeginDocumentEventArgs e)
  148.        {
  149.            if (e.PlotToFile)
  150.            {
  151.                _log = null;
  152.                return;
  153.            }

  154.            _log.DwgName = Path.GetFileName(e.DocumentName);
  155.            _log.DwgPath = Path.GetDirectoryName(e.DocumentName);
  156.            _log.CopyCount = e.Copies;
  157.        }

  158.        private void PlotManager_BeginPage(
  159.            object sender, BeginPageEventArgs e)
  160.        {
  161.            if (_log == null) return;

  162.            if (e.PlotInfo.ValidatedConfig != null)
  163.            {
  164.                if (e.PlotInfo.ValidatedConfig.IsPlotToFile)
  165.                {
  166.                    _log = null;
  167.                    return;
  168.                }

  169.                _log.PlotterName = e.PlotInfo.ValidatedConfig.DeviceName;
  170.            }

  171.            if (e.PlotInfo.ValidatedSettings != null)
  172.            {
  173.                _log.PaperUnit = e.PlotInfo.ValidatedSettings.PlotPaperUnits;
  174.                _log.MediaName = e.PlotInfo.ValidatedSettings.CanonicalMediaName;

  175.                Point2d pt = e.PlotInfo.ValidatedSettings.PlotPaperSize;
  176.                if (pt.X > pt.Y)
  177.                {
  178.                    _log.PaperWidth = pt.X;
  179.                    _log.PaperHeight = pt.Y;
  180.                }
  181.                else
  182.                {
  183.                    _log.PaperWidth = pt.Y;
  184.                    _log.PaperHeight = pt.X;
  185.                }
  186.            }
  187.        }

  188.        private void PlotManager_EndPage(
  189.            object sender, EndPageEventArgs e)
  190.        {
  191.            if (e.Status != SheetCancelStatus.Continue) _cancelled = true;
  192.        }

  193.        private void PlotManager_EndDocument(
  194.            object sender, EndDocumentEventArgs e)
  195.        {
  196.            if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
  197.        }

  198.        private void PlotManager_EndPlot(
  199.            object sender, EndPlotEventArgs e)
  200.        {
  201.            if (e.Status != PlotCancelStatus.Continue) _cancelled = true;

  202.            if (_cancelled)
  203.            {
  204.                _log = null;
  205.                _cancelled = false;
  206.                return;
  207.            }

  208.            if (_log == null) return;

  209.            _log.PlottingTime = DateTime.Now;

  210.            //Debug code here
  211.            Document dwg = Autodesk.AutoCAD.ApplicationServices.
  212.                Application.DocumentManager.MdiActiveDocument;
  213.            Editor ed = dwg.Editor;

  214.            ed.WriteMessage("\nPlotted by: {0}", _log.UserName);
  215.            ed.WriteMessage("\nPlotted on: {0}", _log.PlotterName);
  216.            ed.WriteMessage("\nDwg Location: {0}", _log.DwgPath);
  217.            ed.WriteMessage("\nPlotted Dwg: {0}", _log.DwgName);
  218.            ed.WriteMessage("\nMedia: {0}", _log.MediaName);
  219.            ed.WriteMessage("\nMedia size: " +
  220.                _log.PaperWidth.ToString("#####0.00") +
  221.                " (W) x " +
  222.                _log.PaperHeight.ToString("#####0.00") + " (H)");
  223.            ed.WriteMessage("\nCopy Count: {0}", _log.CopyCount);

  224.            //Save Plotting log, if the plotting plotter is on printer list;
  225.            if (IsTracedDevice(_log.PlotterName))
  226.            {
  227.                _logWriter.SavePlottingLog(_log);
  228.            }
  229.        }

  230.        private void PlotManager_PlotCancelled(object sender, EventArgs e)
  231.        {
  232.            _cancelled = true;
  233.        }

  234.        private void PlotManager_PageCancelled(object sender, EventArgs e)
  235.        {
  236.            _cancelled = true;
  237.        }

  238.        #endregion
  239.    }
  240. }

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.


原文地址
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-5-7 17:27 , Processed in 0.392706 second(s), 23 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表