Crop white margins in a PDF file
114 views (last 30 days)
Hi, I know this question has been asked already, but - so far - I did not find a suitable and easy solution.
I have a PDF file in a folder, which is actually a graph/figure.
I would like to programmatically read that PDF file and remove the margins/white space around my graph/figure.
Is there any simple but efficient way to do so (without changing figure ratio, size or quality)?
Something like this:
filename = open('mypdffile.pdf')
Richard Quist on 6 Jan 2022
One of the following should help.
1. Use external tool to modify previously generated PDF file
MATLAB does not provide a way to read in a PDF file and edit/crop it. You may be able to use an external tool such as ghostscript to do this.
2. Use exportgraphics
In R2020a and above you should be able to use exportgraphics to do this.
exportgraphics(fig, 'output.pdf', 'ContentType', 'vector');
If you are getting errors during installation or when running that command you should contact tech support.
3. Use print with a tiledlayout
If you are using R2020b or later you could place your plot inside a tiledlayout container with tight padding and then use the print command to generate the PDF. Something like the following:
fig = figure;
% set whatever figure properties are needed
tl = tiledlayout(fig, 1, 1, 'padding', 'tight');
ax = nexttile;
% additional code to create your plot inside ax
% make sure PDF paper size is sized properly
fig.PaperSize = fig.PaperPosition(3:4);
% print the figure
print(fig, '-dpdf', 'output.pdf');