Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Capturing print events

July 8, 2015 3 Comments

As a followup to my recent post on capturing and using HG2’s new graphic events, I would like to welcome back guest blogger Robert Cumming, who developed a commercial Matlab GUI framework. Today, Robert will highlight an unusual use of event listeners to enable print output customizations by tapping into print-related events.
One of my toolbox clients wanted to ensure that every print-out, of any Matlab GUI, would contain a datestamp footer and a project id header.
Initially I thought this would be a simple task, since the GUI framework already has saveAs and copyToClipboard methods that users could utilize. Moreover, as Yair has shown some years ago, we can easily adapt the standard callbacks associated with the Matlab figure toolbar’s <Print> button and the menu-bar’s Print action. We can even customize the standard print setup. However, all this does not help when directly invoking printout commands from the Matlab command line or from within the user program, for example:

% Create the GUI
[x,y,z] = peaks(75);
surf(x,y,z);
% printout via print() or export_fig
print(gcf, .... )
export_fig filename  % see https://undocumentedmatlab.com/blog/export_fig

% Create the GUI [x,y,z] = peaks(75); surf(x,y,z); % printout via print() or export_fig print(gcf, .... ) export_fig filename % see https://undocumentedmatlab.com/blog/export_fig

Printout with the expected header and footer stamps
Printout with the expected header and footer stamps


This initially posed a bit of a challenge – how could I capture the print event?
The key to solving this was using events in a different way. Rather than listen for a print event, we listen for something that print interacts with in the figure window. This will solve the problem for both print and export_fig, since export_fig uses print internally.
We can listen to get and set events on many Matlab properties. In this instance we can trap get events on a figure’s PaperPositioMode, or PaperSize property. print, saveas and export_fig all access these properties before doing the actual printing, so by trapping the event we can run our own function before the printing is done. For example:

classdef PrintListenerDemo
  properties
    referenceNo = 'R1234-56'
  end
  methods (Access=public)
    function obj = PrintListenerDemo
      hFig = figure;
      [x,y,z] = peaks(75);
      surf ( x, y, z );
      % add listener on event to prepare the figure for printing
      addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep );
      % Testing only:
      evalin ( 'base', 'print ( gcf, ''-dmeta'' )' );  % simulate user action in command-line
      print(hFig,'-dmeta');    % simulate programmatic printout
    end
    function Prep(obj, hFig, varargin)
      disp ( 'running function in preparation for printing.' );
      % Add datestamp and reference id UIControls
      str = sprintf ( 'Printed @ %s', datestr(now) );
      uicontrol ( 'parent',hFig, 'style','text', 'units','normalized', ...
                  'position',[0 0 1 0.07], 'string',str, 'BackgroundColor','white' );
    end
  end
end

classdef PrintListenerDemo properties referenceNo = 'R1234-56' end methods (Access=public) function obj = PrintListenerDemo hFig = figure; [x,y,z] = peaks(75); surf ( x, y, z ); % add listener on event to prepare the figure for printing addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep ); % Testing only: evalin ( 'base', 'print ( gcf, ''-dmeta'' )' ); % simulate user action in command-line print(hFig,'-dmeta'); % simulate programmatic printout end function Prep(obj, hFig, varargin) disp ( 'running function in preparation for printing.' ); % Add datestamp and reference id UIControls str = sprintf ( 'Printed @ %s', datestr(now) ); uicontrol ( 'parent',hFig, 'style','text', 'units','normalized', ... 'position',[0 0 1 0.07], 'string',str, 'BackgroundColor','white' ); end end end

When we run the above we can see that the disp message is displayed twice, because the property has two get calls in the print function. We can easily solve this by saving a temp variable that is created the first time it is run.
The next thing we need to do is to clean up afterwards, i.e. remove the uicontrols and reset the temp variable to ensure that any future print events are captured.
Here you might think the second get call I mentioned above was post printing, but it’s not. So we need to capture another event to do the cleaning up.
In this instance I thought about what was likely to happen – some sort of user interaction, e.g. a mouse move, press or key press. So we can listen for any of those events and run our clean up method. This is shown in the full code below:

% PrintListenerDemo - Demo of print listener methodology
classdef PrintListenerDemo
  properties
    referenceNo = 'R1234-56'
  end
  methods (Access=public)
    function obj = PrintListenerDemo
      hFig = figure;
      [x,y,z] = peaks(75);
      surf ( x, y, z );
      % add listener on event to prepare the figure for printing
      addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep );
      % add a few different ways to clean up
      addlistener ( hFig, 'ButtonDown', @obj.CleanUp );
      addlistener ( hFig, 'WindowKeyPress', @obj.CleanUp );
      addlistener ( hFig, 'WindowMouseMotion', @obj.CleanUp );
      % Testing only:
      evalin ( 'base', 'print ( gcf, ''-dmeta'' )' );  % simulate user action in command-line
      print(hFig,'-dmeta');    % simulate programmatic printout
    end
    function Prep(obj, hFig, varargin)
      try
        hFig.ApplicationData.printPrepDone;
        return % If variable set do not run this method again
      end
      disp ( 'preparing for print.' );
      % create the date string
      str1 = sprintf ( 'Printed @ %s', datestr(now) );
      str2 = sprintf ( 'Reference: %s', obj.referenceNo );
      % create 2 UI controls to contain the information requested in the image
      hFig.ApplicationData.UIC1 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str1, 'BackgroundColor','w', 'position',[0 0 1 0.07] );
      hFig.ApplicationData.UIC2 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str2, 'BackgroundColor','w', 'position',[0 0.93 1 0.07] );
      % Save a temp variable to stop this function being called many times.
      hFig.ApplicationData.printPrepDone = true;
    end
    function CleanUp(obj, hFig, varargin)
      try
        if hFig.ApplicationData.printPrepDone
          % Clean up the uicontrols
          disp ( 'clean up post printing event' );
          delete ( hFig.ApplicationData.UIC1 );
          delete ( hFig.ApplicationData.UIC2 );
          % remove the temp variable, so the next print job will be captured
          hFig.ApplicationData = rmfield ( hFig.ApplicationData, 'printPrepDone' );
        end
      end
    end
  end
end

% PrintListenerDemo - Demo of print listener methodology classdef PrintListenerDemo properties referenceNo = 'R1234-56' end methods (Access=public) function obj = PrintListenerDemo hFig = figure; [x,y,z] = peaks(75); surf ( x, y, z ); % add listener on event to prepare the figure for printing addlistener ( hFig, 'PaperPositionMode', 'PreGet', @obj.Prep ); % add a few different ways to clean up addlistener ( hFig, 'ButtonDown', @obj.CleanUp ); addlistener ( hFig, 'WindowKeyPress', @obj.CleanUp ); addlistener ( hFig, 'WindowMouseMotion', @obj.CleanUp ); % Testing only: evalin ( 'base', 'print ( gcf, ''-dmeta'' )' ); % simulate user action in command-line print(hFig,'-dmeta'); % simulate programmatic printout end function Prep(obj, hFig, varargin) try hFig.ApplicationData.printPrepDone; return % If variable set do not run this method again end disp ( 'preparing for print.' ); % create the date string str1 = sprintf ( 'Printed @ %s', datestr(now) ); str2 = sprintf ( 'Reference: %s', obj.referenceNo ); % create 2 UI controls to contain the information requested in the image hFig.ApplicationData.UIC1 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str1, 'BackgroundColor','w', 'position',[0 0 1 0.07] ); hFig.ApplicationData.UIC2 = uicontrol ( 'parent',hFig, 'style','text', 'units','norm', 'string',str2, 'BackgroundColor','w', 'position',[0 0.93 1 0.07] ); % Save a temp variable to stop this function being called many times. hFig.ApplicationData.printPrepDone = true; end function CleanUp(obj, hFig, varargin) try if hFig.ApplicationData.printPrepDone % Clean up the uicontrols disp ( 'clean up post printing event' ); delete ( hFig.ApplicationData.UIC1 ); delete ( hFig.ApplicationData.UIC2 ); % remove the temp variable, so the next print job will be captured hFig.ApplicationData = rmfield ( hFig.ApplicationData, 'printPrepDone' ); end end end end end

It is noted here that the datestamp and the reference number remain visible until the user interacts with the GUI but that’s a small price to pay.
Any suggestions on other ways to clean up the print event afterwards? If so, please post a comment below. Alternatively if you have used events and listeners in an unusual way please share this as well.

Conclusions

  1. It is possible to capture printout events in your code even when the print command is invoked programmatically, without a direct reference to your code
  2. We can use events for things that we might never have initially considered

Related posts:

  1. Customizing print setup – Matlab figures print-setup can be customized to automatically prepare the figure for printing in a specific configuration...
  2. Detecting window focus events – Matlab does not have any documented method to detect window focus events (gain/loss). This article describes an undocumented way to detect such events....
  3. UDD Events and Listeners – UDD event listeners can be used to listen to property value changes and other important events of Matlab objects...
  4. Matlab callbacks for uifigure JavaScript events – Matlab callback code can be attached to JavaScript events in web-based uifigures. ...
  5. Waiting for asynchronous events – The Matlab waitfor function can be used to wait for asynchronous Java/ActiveX events, as well as with timeouts. ...
  6. Undocumented HG2 graphics events – Matlab's new HG2 graphics engine includes many new undocumented events that could be used in various ways. ...
Figure Pure Matlab Robert Cumming Undocumented feature
Print Print
« Previous
Next »
3 Responses
  1. Yaroslav July 8, 2015 at 23:48 Reply

    Hi,

    Have you tried to examine printjob? It seems to be the printing controller that print uses internally.
    Upon closer inspection, it seems that printjob changes the 'ShowHiddenHandles' property of the root object before and after printing. Perhaps you could listen to that.

    • Robert Cumming July 9, 2015 at 00:46 Reply

      Hi,

      Thanks for the suggestion – It could be a good solution for triggering the clean up post printing – I’ll have a look at it report back.

      Regards

      • Robert Cumming July 9, 2015 at 07:00

        RE: Yaroslav,

        Looking into this the ShowHiddenHandles property is interacted with many times within the print command… so identifying the (2) occurrences after the actual printing (e.g. saving the file) is probably not straightforward (as it still happens inside the print function).

        Regards

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (email)
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
ActiveX (6) AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
  • Josh (10 hours 3 minutes ago): Dear Yair, Small typo; you wrote >>Move lines up or down – CTRL + ALT + UP or DOWN allows you to move selected lines up or down but it’s actually ALT+SHIFT then UP/DOWN...
  • Yair Altman (7 days 4 hours ago): You can try to increase the Java heap memory size in the Matlab preferences (General => Java Heap Memory). Any changes to the settings will only take effect after restarting...
  • Thomas (7 days 6 hours ago): Hello, thanks for sharing! I currently receive the following memory error message when using savezip with a big object (Matlab R2020b, Windows 10). Error using...
  • Yair Altman (10 days 13 hours ago): Yerlan – either use menuItem1.setEnabled(0) or set(menuItem1,'Enabled',0)
  • Manzn (10 days 16 hours ago): Thank you man! you saved me, when there was no more light 😀
  • Yerlan (11 days 21 hours ago): Hello Mr. Altman, how can I disable menu items in the context menu? E.g. when I am trying to do this: menuItems = jmenu.getSubElements; menuItem1 = menuItems(1);...
  • Yair Altman (12 days 13 hours ago): Thanks for the note Eric – you forgot the crucial call to jTable.setLabelTable(labelTabl e) – I added it into your code snippet above.
  • Erik (14 days 0 hours ago): Thank you for this — I don’t know if this has been mentioned anywhere else before, but it could be useful to mention how to add custom labels to a jslider. I did the...
  • turhv (26 days 18 hours ago): very nice! work perfectly to me in MATLAB 2019a. thanks!!!
  • Jianfei (59 days 22 hours ago): I have tried the MathWorks CheckBoxList in Matlab 2015b. For whatever the reason, I can’t change the font properties. I can change the font color, but changing font properties...
  • Donato Coppola (65 days 17 hours ago): Hi Yair, I have a problem with the double format. When I run the treeTable function, the numbers in double format cells are displayed with comma as decimal separator. How can...
  • Kim (71 days 8 hours ago): Yair, the following didn’t work for me either: jh.setBorderPainted(false); Regards, Kim
  • Adil (73 days 9 hours ago): Thank you for the blog, it was useful for me. I have a file named App_project.mlapp.zip and when I extract it through Winzip it gives all the files exactly as you described above. I...
  • Mr Ashley Trowell (75 days 19 hours ago): Thank you so much for this analysis. Also, I find it somewhat horrifying. The take away seems to be to use && / || and NOT and / or. Thanks a bunch! ~Ashley
  • Matt (80 days 20 hours ago): Late reply I know, but you can call custom shortcuts with alt-#. Hold down Alt to see what number is assigned to the shortcuts you’ve created. Now if there was a way to create a...
Contact us
Undocumented Matlab © 2009 - Yair Altman
Scroll to top