Tight bounding box around PDF of MATLAB figure

2019-04-29 11:20发布

问题:

When creating a simple figure in MATLAB and saving it as PDF, the resulting PDF file will have a luxurious bounding box.

plot(1,1,'x')
print(gcf, '-dpdf', 'test.pdf');

(From the ratio of the output it seems they always put in on an A page.)

Is there a simple way to get a tight bounding box around the PDF?

回答1:

You can format the bounding box as follows

figure(1)
hold on;
plot(1,1,'x')

ps = get(gcf, 'Position');
ratio = (ps(4)-ps(2)) / (ps(3)-ps(1))
paperWidth = 10;
paperHeight = paperWidth*ratio;


set(gcf, 'paperunits', 'centimeters');
set(gcf, 'papersize', [paperWidth paperHeight]);
set(gcf, 'PaperPosition', [0    0   paperWidth paperHeight]);


print(gcf, '-dpdf', 'test2.pdf');

For smaller borders, you can adjust the paperposition property, e.g.

set(gcf, 'PaperPosition', [-0.5   -0.5   paperWidth+0.5 paperHeight+0.5]);


回答2:

An old question, but I'll answer since google found this for me before the Mathworks own help page (Sorry no reputation enough to post a comment to previous). Anyway

ratio = (ps(4)-ps(2)) / (ps(3)-ps(1))

should be

ratio = ps(4)/ps(3);

as first values gcf.Position are [x,y] location on the screen, nothing to do with the size.

Also Matlab(R) gives an answer, especially if you don't want/need to resize figure: https://se.mathworks.com/help/matlab/creating_plots/save-figure-with-minimal-white-space.html

fig = gcf;
fig.PaperPositionMode = 'auto'
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];