1
votes

How can I print ONLY the plot created by my MATLAB GUI into a PDF document?

I know about the function available online called export_fig, but we are not allowed to make use of externally coded tools for this.

I currently have the following

function PrintButton_Callback(hObject, eventdata, handles)
set(gcf,'PaperType','A4','PaperOrientation','landscape','PaperPositionMode','auto');
print(get(handles.Axes,'Parent'), '-dpdf','Results.pdf');

However, this results in my entire GUI figure being saved. How can I select ONLY the plot made by my axes ("Axes")?

2

2 Answers

1
votes

The print command only accepts a figure as handle parameter ...

To print specified axis only a trick is to copy this axis to a new temporary figure using copyobj and use print command on the new figure.

Here is some sample code:

%% -- Test code
function [] = TestPrint()
%[
    % Create figure with two axes
    fig = figure(1); clf;
    ax1 = subplot(1,2,1);
    plot(rand(1, 12));    
    ax2 = subplot(1,2,2);
    plot(rand(1, 12)); 

    % Print the whole figure
    print(fig, '-dpdf', 'figure.pdf');

    % Print ONLY second axis
    printAxis(ax2, '-dpdf', 'axis.pdf');
%]
end

%% --- Print specified axis only
% NB: Accept same arguments as 'print' except for first one which now is an axis.
function [] = printAxis(ax, varargin)
%[
    % Create a temporary figure
    visibility = 'on'; % You can set it to off if you want
    tempFigure = figure('Visible', visibility);
    cuo = onCleanup(@()clearTempFigure(tempFigure)); % Just to be sure to destroy the figure

    % Copy selected axis to the temporary figure
    newAx = copyobj(ax, tempFigure);

    % Make it fill whole figure space
    set(newAx, 'OuterPosition', [0 0 1 1]);

    % Print temporary figure
    print(tempFigure, varargin{1:end});        
%]
end
function [] = clearTempFigure(h)
%[
    if (ishandle(h)), delete(h); end
%]
end
0
votes

Disable axes visibility: set(gca,'Visible','off') before printing.