- Undocumented Matlab - https://undocumentedmatlab.com -

Capturing print events

Posted By Yair Altman On July 8, 2015 | 3 Comments

As a followup to my recent post on capturing and using HG2’s new graphic events [1], I would like to welcome back guest blogger Robert Cumming, who developed a commercial Matlab GUI framework [2]. 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 [3] 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 [4]. 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

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

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

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

Categories: Figure window, Guest bloggers, Medium risk of breaking in future versions, Undocumented feature


3 Comments (Open | Close)

3 Comments To "Capturing print events"

#1 Comment By Yaroslav On July 8, 2015 @ 23:48

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.

#2 Comment By Robert Cumming On July 9, 2015 @ 00:46

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

#3 Comment By Robert Cumming On July 9, 2015 @ 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


Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/capturing-print-events

URLs in this post:

[1] HG2’s new graphic events: http://undocumentedmatlab.com/blog/undocumented-hg2-graphics-events

[2] Matlab GUI framework: https://sites.google.com/site/matpihome/matlab-gui-framework

[3] has shown: http://undocumentedmatlab.com/blog/modifying-default-toolbar-menubar-actions

[4] customize the standard print setup: http://undocumentedmatlab.com/blog/customizing-print-setup

[5] Customizing print setup : https://undocumentedmatlab.com/articles/customizing-print-setup

[6] Detecting window focus events : https://undocumentedmatlab.com/articles/detecting-window-focus-events

[7] UDD Events and Listeners : https://undocumentedmatlab.com/articles/udd-events-and-listeners

[8] Matlab callbacks for uifigure JavaScript events : https://undocumentedmatlab.com/articles/matlab-callbacks-for-uifigure-javascript-events

[9] Waiting for asynchronous events : https://undocumentedmatlab.com/articles/waiting-for-asynchronous-events

[10] Undocumented HG2 graphics events : https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.