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?
bboxB = bboxerase( bboxA , window ) removes bounding boxes in the input bboxA that lie within a region of interest (ROI) specified by window . The output is the set of bounding boxes retained from the input bboxA .
Description. [ xlim , ylim ] = boundingbox( polyin ) returns the x and y bounds of the smallest rectangle enclosing a polyshape . xlim and ylim are two-element row vectors whose first elements correspond to the lower x and y bounds, and whose second elements correspond to the upper x and y bounds.
Click the drop-down menu next to "Save as type" and select "PDF." Type in a name for the PDF file.
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)];
You can format the bounding box as follows
figure(1)
hold on;
plot(1,1,'x')
ps = get(gcf, 'Position');
ratio = ps(4) / ps(3)
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]);
~edit~
I corrected the calculation of the ratio because it was wrong, as pointed out by Space47's answer. (Thanks @Space47).
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