Tianxiang Xiong
Tianxiang Xiong

Reputation: 4081

Printing figure at same size as figure window

I'm trying to save a figure in PDF format such that I don't get extraneous white space around it, i.e. the figure should be the same size as the figure window.

I'm pretty sure that the way to do it is

figureNames = {'a', 'b', 'c'};
for i = 1:3
    set(figure(i), 'paperpositionmode', 'auto');
    print(figure(i), '-dpdf', figureNames{i})
end

But it's not working. I'm getting as much white space as ever. Can someone enlighten me as to what's wrong?

Upvotes: 2

Views: 6959

Answers (3)

Tianxiang Xiong
Tianxiang Xiong

Reputation: 4081

It seems that setting PaperPositionMode to auto will get rid of extraneous white space for EPS files, but not PDF's.

To get rid of white space for PDF's, I wrote a little script to resize the paper to the figure size. Since it's so short, I've included it below in case anyone else needs it.

It is inspired by this document, as well as this StackOverflow question.

My solution works by manipulating only the paper size, not the figure axes, because manipulating the axes runs into trouble with subplots. This also means that some white space will remain. In MATLAB's vocabulary, the figures is bounded by its OuterPosition rather than TightInset.

function [filename] =  printpdf(fig, name)
% printpdf Prints image in PDF format without tons of white space

% The width and height of the figure are found
% The paper is set to be the same width and height as the figure
% The figure's bottom left corner is lined up with
% the paper's bottom left corner

% Set figure and paper to use the same unit
set(fig, 'Units', 'centimeters')
set(fig, 'PaperUnits','centimeters');

% Position of figure is of form [left bottom width height]
% We only care about width and height
pos = get(fig,'Position');

% Set paper size to be same as figure size
set(fig, 'PaperSize', [pos(3) pos(4)]);

% Set figure to start at bottom left of paper
% This ensures that figure and paper will match up in size
set(fig, 'PaperPositionMode', 'manual');
set(fig, 'PaperPosition', [0 0 pos(3) pos(4)]);

% Print as pdf
print(fig, '-dpdf', name)

% Return full file name
filename = [name, '.pdf'];
end

Upvotes: 1

Ivan Oseledets
Ivan Oseledets

Reputation: 2290

You can try "all in one" solutions for converting figures to pdf-files. I use mlf2pdf (http://www.mathworks.com/matlabcentral/fileexchange/28545) and it seems to work quite well. Moreover, the quality of the produced figures is much better due to Latex typesetting of everything

Upvotes: 1

copiancestral
copiancestral

Reputation: 122

I've also had issues with this. The workaround is by printing in -depsc (color) or -deps if you just need grayscale figures. The encapsulated postscript file has practically no white margin. You can later convert the .eps file to pdf without trouble, if you working in LaTeX you can use it as it is.

Upvotes: 1

Related Questions