Assume I produce several figures in my program. I want to give the user the option of printing them all at once. I do not want to show the print dialog for every page. Therefore, I am displaying it only once and for the first figure only. This is the solution that I have come up with so far:
figHandles = get(0, 'Children');
for currFig = 1:length(figHandles)
if(currFig == 1)
printdlg(figHandles(currFig)); % Shows the print dialog for the first figure
else
print(figHandles(currFig)); % Does not show the print dialog and uses the latest printer selection
end
end
But the problem is, if the user cancels the print for the first figure, there is no way that I can catch it and cancel the other prints. How should I achieve that?
Ok this one is a pretty dirty trick and there is definitely no guaranty it will work for all versions. It does work for me on Matlab 2013a / win 7.
To get Matlab to return a value as to whether it executed a print job or not, you need to insert a small hack into the print.m
function.
print.m
Locate the print.m
function. It should be in your matlab installation folders around ..\toolbox\matlab\graphics\print.m
.
Once located, make a backup copy! (this trick is minor and shouldn't break anything but we never know).
open the file print.m
and locate the line LocalPrint(pj);
, it should be near or at the end of the main function (~line 240 for me).
Replace the line by:
.
pj = LocalPrint(pj); %// Add output to the call to LocalPrint
if (nargout == 1)
varargout{1} = pj ; %// transfer this output to the output of the `print` function
end
Done for the hack. Now every time you are calling the print
function, you can have a return argument full of information.
First, notice that on windows machines, the printdlg
function is equivalent to call the print
function with the '-v'
argument.
So printdlg(figHandle)
is exactly the same as print('-v',figHandle)
. (the '-v'
stands for verbose
). We are going to use that.
The output of the print
function is going to be a structure (let's call it pj
) with many fields. The field you want to check to know if the print command was actually executed is pj.Return
.
pj.return == 0 => job cancelled
pj.return == 1 => job sent to printer
So in your case, after the tweak on the print.m
, it could look like this:
pj = print('-v',figHandles(1)); %// Shows the print dialog for the first figure
if pj.Return %//if the first figure was actually printed (and not cancelled)
for currFig = 2:length(figHandles)
print(figHandles(currFig)); %// Does not show the print dialog and uses the latest printer selection
end
end
Note: The pj
structure contains many more reusable informations, including the print job options, the current selected printers etc ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With