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:
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4
5 using Autodesk.AutoCAD.ApplicationServices;
6 using Autodesk.AutoCAD.EditorInput;
7 using Autodesk.AutoCAD.PlottingServices;
8 using Autodesk.AutoCAD.Geometry;
9 using Autodesk.AutoCAD.Runtime;
10
11 [assembly: CommandClass(typeof(TrackAcadPlotting.TrackPlotting))]
12 [assembly: ExtensionApplication(typeof(TrackAcadPlotting.TrackPlotting))]
13
14 namespace TrackAcadPlotting
15 {
16 public class TrackPlotting: IExtensionApplication
17 {
18 private static PlotReactorManager _plotManager;
19 private static IPlottingLogWriter _logWriter;
20 private static bool _cancelled=false;
21 private static PlotLog _log=null;
22
23 #region IExtensionApplication Members
24
25 private List<string> _plotters = null;
26
27 public void Initialize()
28 {
29 Document dwg = Autodesk.AutoCAD.ApplicationServices.
30 Application.DocumentManager.MdiActiveDocument;
31
32 //Get plotter names to track
33 _plotters = GetPlotterNames();
34
35 try
36 {
37 //Hard-coded log file folder path.
38 //In production, the file path could be
39 //set in acad.exe.confg or using other
40 //configuing technique
41 //Note: here I instantiated an PlottingLogFileWriter
42 //I can also instantiate an PlottingLogSqlServerWriter,
43 //if it is available
44 _logWriter = new PlottingLogFileWriter("E:\\Temp\\PlottingTrack");
45 }
46 catch
47 {
48 if (dwg != null)
49 {
50 dwg.Editor.WriteMessage(
51 "\nInitializing plot tracking log writer faailed.");
52 }
53
54 return;
55 }
56
57 //Hook up event handlers
58 _plotManager = new PlotReactorManager();
59
60 _plotManager.BeginPlot +=
61 new BeginPlotEventHandler(PlotManager_BeginPlot);
62
63 _plotManager.BeginDocument +=
64 new BeginDocumentEventHandler(PlotManager_BeginDocument);
65
66 _plotManager.BeginPage +=
67 new BeginPageEventHandler(PlotManager_BeginPage);
68
69 _plotManager.EndPage +=
70 new EndPageEventHandler(PlotManager_EndPage);
71
72 _plotManager.EndDocument +=
73 new EndDocumentEventHandler(PlotManager_EndDocument);
74
75 _plotManager.EndPlot +=
76 new EndPlotEventHandler(PlotManager_EndPlot);
77
78 _plotManager.PageCancelled +=
79 new PageCancelledEventHandler(PlotManager_PageCancelled);
80
81 _plotManager.PlotCancelled +=
82 new PlotCancelledEventHandler(PlotManager_PlotCancelled);
83
84 if (dwg != null)
85 {
86 dwg.Editor.WriteMessage("\nPlot tracking has been initialized.");
87 }
88 }
89
90 public void Terminate()
91 {
92 //Remove event handlers
93 _plotManager.BeginPlot -=
94 new BeginPlotEventHandler(PlotManager_BeginPlot);
95
96 _plotManager.BeginDocument -=
97 new BeginDocumentEventHandler(PlotManager_BeginDocument);
98
99 _plotManager.BeginPage -=
100 new BeginPageEventHandler(PlotManager_BeginPage);
101
102 _plotManager.EndPage -=
103 new EndPageEventHandler(PlotManager_EndPage);
104
105 _plotManager.EndDocument -=
106 new EndDocumentEventHandler(PlotManager_EndDocument);
107
108 _plotManager.EndPlot +=
109 new EndPlotEventHandler(PlotManager_EndPlot);
110
111 _plotManager.PageCancelled -=
112 new PageCancelledEventHandler(PlotManager_PageCancelled);
113
114 _plotManager.PlotCancelled -=
115 new PlotCancelledEventHandler(PlotManager_PlotCancelled);
116 }
117
118 #endregion
119
120 #region private methods
121
122 private List<string> GetPlotterNames()
123 {
124 List<string> plotters = new List<string>();
125
126 //A plotter name list could be stored somewhere
127 //and loaded in, such as acad.exe.config (user may change it!)
128 //Or centrally stored in a DB (so only manager can set/change it)
129 //Here I simply hard-coded one plotter name
130 plotters.Add("CutePDF Writer");
131
132 return plotters;
133 }
134
135 private void GetUserComputerName(
136 out string userName, out string computerName)
137 {
138 userName = "";
139 computerName = "";
140
141 string domain = System.Environment.UserDomainName;
142 string user = System.Environment.UserName;
143
144 userName = domain + "\\" + user;
145 computerName = System.Environment.MachineName;
146 }
147
148 private bool IsTracedDevice(string plotterName)
149 {
150 foreach (string plt in _plotters)
151 {
152 if (plt.Equals(plotterName,
153 StringComparison.CurrentCultureIgnoreCase))
154 {
155 return true;
156 }
157 }
158
159 return false;
160 }
161
162 #endregion
163
164 #region Private methods: plotting event handlers
165
166 private void PlotManager_BeginPlot(object sender, BeginPlotEventArgs e)
167 {
168 _cancelled = false;
169
170 if (e.PlotType == Autodesk.AutoCAD.
171 PlottingServices.PlotType.BackgroundPlot
172 || e.PlotType == Autodesk.AutoCAD.
173 PlottingServices.PlotType.Plot)
174 {
175
176 _log = new PlotLog();
177
178 string user;
179 string comp;
180 GetUserComputerName(out user, out comp);
181
182 _log.UserName = user;
183 _log.ComputerName = comp;
184 }
185 else
186 {
187 _log = null;
188 }
189 }
190
191 private void PlotManager_BeginDocument(
192 object sender, BeginDocumentEventArgs e)
193 {
194 if (e.PlotToFile)
195 {
196 _log = null;
197 return;
198 }
199
200 _log.DwgName = Path.GetFileName(e.DocumentName);
201 _log.DwgPath = Path.GetDirectoryName(e.DocumentName);
202 _log.CopyCount = e.Copies;
203 }
204
205 private void PlotManager_BeginPage(
206 object sender, BeginPageEventArgs e)
207 {
208 if (_log == null) return;
209
210 if (e.PlotInfo.ValidatedConfig != null)
211 {
212 if (e.PlotInfo.ValidatedConfig.IsPlotToFile)
213 {
214 _log = null;
215 return;
216 }
217
218 _log.PlotterName = e.PlotInfo.ValidatedConfig.DeviceName;
219 }
220
221 if (e.PlotInfo.ValidatedSettings != null)
222 {
223 _log.PaperUnit = e.PlotInfo.ValidatedSettings.PlotPaperUnits;
224 _log.MediaName = e.PlotInfo.ValidatedSettings.CanonicalMediaName;
225
226 Point2d pt = e.PlotInfo.ValidatedSettings.PlotPaperSize;
227 if (pt.X > pt.Y)
228 {
229 _log.PaperWidth = pt.X;
230 _log.PaperHeight = pt.Y;
231 }
232 else
233 {
234 _log.PaperWidth = pt.Y;
235 _log.PaperHeight = pt.X;
236 }
237 }
238 }
239
240 private void PlotManager_EndPage(
241 object sender, EndPageEventArgs e)
242 {
243 if (e.Status != SheetCancelStatus.Continue) _cancelled = true;
244 }
245
246 private void PlotManager_EndDocument(
247 object sender, EndDocumentEventArgs e)
248 {
249 if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
250 }
251
252 private void PlotManager_EndPlot(
253 object sender, EndPlotEventArgs e)
254 {
255 if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
256
257 if (_cancelled)
258 {
259 _log = null;
260 _cancelled = false;
261 return;
262 }
263
264 if (_log == null) return;
265
266 _log.PlottingTime = DateTime.Now;
267
268 //Debug code here
269 Document dwg = Autodesk.AutoCAD.ApplicationServices.
270 Application.DocumentManager.MdiActiveDocument;
271 Editor ed = dwg.Editor;
272
273 ed.WriteMessage("\nPlotted by: {0}", _log.UserName);
274 ed.WriteMessage("\nPlotted on: {0}", _log.PlotterName);
275 ed.WriteMessage("\nDwg Location: {0}", _log.DwgPath);
276 ed.WriteMessage("\nPlotted Dwg: {0}", _log.DwgName);
277 ed.WriteMessage("\nMedia: {0}", _log.MediaName);
278 ed.WriteMessage("\nMedia size: " +
279 _log.PaperWidth.ToString("#####0.00") +
280 " (W) x " +
281 _log.PaperHeight.ToString("#####0.00") + " (H)");
282 ed.WriteMessage("\nCopy Count: {0}", _log.CopyCount);
283
284 //Save Plotting log, if the plotting plotter is on printer list;
285 if (IsTracedDevice(_log.PlotterName))
286 {
287 _logWriter.SavePlottingLog(_log);
288 }
289 }
290
291 private void PlotManager_PlotCancelled(object sender, EventArgs e)
292 {
293 _cancelled = true;
294 }
295
296 private void PlotManager_PageCancelled(object sender, EventArgs e)
297 {
298 _cancelled = true;
299 }
300
301 #endregion
302 }
303 }
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.
I love this idea and I have been researching how to make cad log number of copies on each print for couple days already. I have stumbled on problem trying to implement your code in AutoCAD 2010 64bit, I believe C# does not like reference to acmgd.dll and acdmgd.dll from AutoCAD 2010 since its 64bit.
ReplyDeleteNot sure if there is a way to go about it
I do not believe the code I show here has problem just because of 64-bit AutoCAD. I do not have 64-bit AutoCAD 2010 accessible, but I have similar code that runs OK with AutoCAD 2012 64-bit on Windows 7 very well.
ReplyDeleteWhat exact problem you have?
Hello Norman..
ReplyDeleteI know this is a OLD OLD topic...
I'm learning C#, so please bear with me...can you explain to me:
1. when you said "I define a data class that hold plotting information", do you mean you create a "Visual c# -> Classsic Destop -> Class Library"?
2. The interface, you mean is a "Console Application"?
3. and then another "Class Library"? for the "TrackPlotting- that does the actual work"
thank for your help
I just try to understand how those file are tide together.
"define a data class..." just means to create a class to hold plotting information. In this simple project, the class is in the same DLL (Class Library) project. In fact, everything in this article is in the same class librray project, which is used as AutoCAD .NET add-in.
ReplyDelete"Interface" is an concept of Object-Oriented programming. In this project, the purpose to use "Interface" is because people might want to save plotting logs to different data store/in different format: database, text file, XML file...
Suggestion: before you start AutoCAD .NET API programming, learn some basic/generic .NET programming first.