Crop white margins in a PDF file
150 次查看(过去 30 天)
显示 更早的评论
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')
crop_margins(filename)
2 个评论
DGM
2022-1-6
编辑:DGM
2022-1-6
It would help if you provide an example of the file.
Unless you know for certain that it's not, I'd suspect that the padding is actually part of the image. Accumulating extra padding when saving plots is a very common problem.
If the padding is part of the image, then removing it will change the size of the image. Should the cropped image be rescaled to retain the original geometry?
采纳的回答
Richard Quist
2022-1-6
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
bar(ax, magic(4));
% make sure PDF paper size is sized properly
fig.PaperSize = fig.PaperPosition(3:4);
% print the figure
print(fig, '-dpdf', 'output.pdf');
3 个评论
Tim Baur
2022-2-2
With option 3, the printing process always cuts off the right box line of the axes.
Do you have a solution for that problem, too?
Of course, I could used "compact" instead of "tight" padding but then again, the white space remains.
Richard Quist
2022-2-2
@Tim Baur: that looks like a clipping issue with the renderer.
You could try adjusting the size of the tiledlayout object, making it a tiny bit smaller to avoid the clipping. For example, set the OuterPosition property when creating it:
tl = tiledlayout(fig, 1, 1, 'padding', 'tight', 'OuterPosition',[0 0 .995 1]);
Or you could do this after the tiledlayout object has been created:
tl.OuterPosition(3) = .995;
You may need to tweak that value to get the results you want.
I hope that helps!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Printing and Saving 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!