Get rid of the white space around the pdf shape

I would like to use PDF versions of my Matlab plots in a LaTeX document. I save numbers using the "saveas" command with the PDF option, but I get a huge amount of spaces around my sections in pdf files. This is normal? How can I get rid of it? Automatically, of course, since I have a lot of stories.

+42
pdf matlab
Sep 27 '10 at 7:07
source share
16 answers

Exporting shapes for publication is a good starting point. Instead of -deps use -dpdf to output in pdf format.

You can fix the bounding box problem using the code below.

 set(gcf, 'PaperSize', [6.25 7.5]); set(gcf, 'PaperPositionMode', 'manual'); set(gcf, 'PaperPosition', [0 0 6.25 7.5]); set(gcf, 'PaperUnits', 'inches'); set(gcf, 'PaperSize', [6.25 7.5]); set(gcf, 'PaperPositionMode', 'manual'); set(gcf, 'PaperPosition', [0 0 6.25 7.5]); set(gcf, 'renderer', 'painters'); print(gcf, '-dpdf', 'my-figure.pdf'); print(gcf, '-dpng', 'my-figure.png'); print(gcf, '-depsc2', 'my-figure.eps'); 

You can read more about this in Tobin's article .

+15
Sep 27 '10 at 7:38 on
source share

The answers above seem too complicated. This function uses a shape descriptor and a line to print material in a pdf file without huge margins.

 function printpdf(h,outfilename) set(h, 'PaperUnits','centimeters'); set(h, 'Units','centimeters'); pos=get(h,'Position'); set(h, 'PaperSize', [pos(3) pos(4)]); set(h, 'PaperPositionMode', 'manual'); set(h, 'PaperPosition',[0 0 pos(3) pos(4)]); print('-dpdf',outfilename); 

For example, to print the current digit, you can call it with:

 printpdf(gcf,'trash') 

However, if you really need a pdf digit, for example, generated by Matlab eps, that is, only a rectangular convex plot shell (or a set of subheadings), here is a more complicated version:

 function printpdf(h,outfilename) % first use the same non-relative unit system for paper and screen (see % below) set(h,'PaperUnits','centimeters'); % now get all existing plots/subplots a=get(h,'Children'); nfigs=length(a); % bounds will contain lower-left and upper-right corners of plots plus one % line to make sure single plots work bounds=zeros(nfigs+1,4); bounds(end,1:2)=inf; bounds(end,3:4)=-inf; % generate all coordinates of corners of graphs and store them in % bounds as [lower-left-x lower-left-y upper-right-x upper-right-y] in % the same unit system as paper (centimeters here) for i=1:nfigs set(a(i),'Unit','centimeters'); pos=get(a(i),'Position'); inset=get(a(i),'TightInset'); bounds(i,:)=[pos(1)-inset(1) pos(2)-inset(2) ... pos(1)+pos(3)+inset(3) pos(2)+pos(4)+inset(4)]; end % compute the rectangular convex hull of all plots and store that info % in mypos as [lower-left-x lower-left-y width height] in centimeters auxmin=min(bounds(:,1:2)); auxmax=max(bounds(:,3:4)); mypos=[auxmin auxmax-auxmin]; % set the paper to the exact size of the on-screen figure using % figure property PaperSize [width height] set(h,'PaperSize',[mypos(3) mypos(4)]); % ensure that paper position mode is in manual in order for the % printer driver to honor the figure properties set(h,'PaperPositionMode', 'manual'); % use the PaperPosition four-element vector [left, bottom, width, height] % to control the location on printed page; place it using horizontal and % vertical negative offsets equal to the lower-left coordinates of the % rectangular convex hull of the plot, and increase the size of the figure % accordingly set(h,'PaperPosition',[-mypos(1) -mypos(2) ... mypos(3)+mypos(1) mypos(4)+mypos(2)]); % print stuff print('-dpdf',outfilename); 
+8
Jul 17 '13 at 19:53 on
source share

I got a little worried about this b4, finding an easy answer. Save as .eps, and then convert .eps to .pdf. On Mac OS, this can be done in preview mode.

+6
Nov 20
source share

In addition to the other suggestions here, you can also try to use the LooseInset property, as described at http://UndocumentedMatlab.com/blog/axes-looseinset-property/ , to remove excess space around your plot axes.

+5
Sep 27 2018-10-22T00:
source share

I just spent some time doing most of these parameters, but my friend Espen pointed out the simplest: if you use the graphicsx package in LaTeX, go with the standard Matlab pdf output and use the trim option in \ includegraphics. Example in a Beamer slide:

\ includegraphics [trim = 0.1in 2.5in 0.1in 2.5in, clip, scale = 0.5] {matlabgraphic.pdf}

The order of the cropping parameters here is left, bottom, right, top. The key is to trim the top and bottom a lot to get rid of excess space. Learn more at Wikibooks .

+4
Apr 12 '14 at 16:26
source share

For raster image outputs (e.g. png), the following is in my Makefile:

 convert -trim input.png input-trimmed.png 

This requires imagemagick.

Update:. In all my recent publications I have used https://github.com/altmany/export_fig , and this is the best solution I have found so far (along with many other solutions for other tasks in one package). I feel a tool that is at least as powerful as it should already be an official part of Matlab. I use it like:

 export_fig -transparent fig.pdf 

Which exports the current drawing, trimming the default output.

Require ghostcript

+4
Aug 08 '15 at 10:14
source share

In MATLAB file sharing, I found an extremely useful feature provided by JΓΌrg Schwizer:

 plot2svg( filename, figHandle ); 

Displays a figure in the form of vector graphics (.svg) and individual curly components as pixel graphics (by default -.png). This allows you to do all kinds of things in your drawing (delete shortcuts, move color panels, etc.), but if you want to remove the white background, just open the .svg file, for example. inkscape, ungroup the elements and export the items you are interested in as a new shape.

+2
Sep 20 '13 at 15:34
source share

For those using linux, a very simple solution is to write in the shell: ps2pdf14 -dPDFSETTINGS=/prepress -dEPSCrop image.eps

+2
Jul 12 '14 at 7:01
source share

I also ran into this problem. Finally, I used the following method, which enabled it, which can automatically save the shape in MATLAB format as the correct PDF format.

you can do it in MATLAB via:

 h = figure; % For example, h = openfig('sub_fig.fig'); Or you just ploted one figure: plot(1:10); set(h,'Units','Inches'); pos = get(h,'Position'); set(h,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3),pos(4)]); print(h,'your_filename','-dpdf','-r0'); 

Hope this helps.

+2
Apr 11 '15 at 5:09 on
source share

I liked the @Antonio method, but it still left too many spaces, and I was looking for one graphic solution that was exported to vector pdf files for use in LaTeX.

  • I did something based on his script and added the ability to export only the graph field (lowering the axes).

  • Please note that unlike the Antonio script, this only works with numbers without subtitles.

  • In the code below, any shape descriptor will be exported as a vector PDF, either with or without axes.




 function SaveFigureAsVectorPDF(InputFigureHandle, OutFileName, ShouldPrintAxes) %% Check input parameters [NumberOfFigures, ~] = size(InputFigureHandle); if(NumberOfFigures ~= 1) error('This function only supports one figure handle.'); end if(isempty(OutFileName)) error('No file path provided to save the figure to.'); end cUnit = 'centimeters'; %% Copy the input figure so we can mess with it %Make a copy of the figure so we don't modify the properties of the %original. FigureHandleCopy = copy(InputFigureHandle); %NOTE: Do not set this figure to be invisible, for some bizarre reason % it must be visible otherwise Matlab will just ignore attempts % to set its properties. % % I would prefer it if the figure did not briefly flicker into % view but I am not sure how to prevent that. %% Find the axis handle ChildAxisHandles = get(FigureHandleCopy, 'Children'); NumberOfChildFigures = length(ChildAxisHandles); if(NumberOfChildFigures ~= 1) %note that every plot has at least one child figure error('This function currently only supports plots with one child figure.'); end AxisHandle = ChildAxisHandles(1); %% Set Units % It doesn't matter what unit you choose as long as it the same for % the figure, axis, and paper. Note that 'PaperUnits' unfortunately % does not support 'pixels' units. set(FigureHandleCopy, 'PaperUnits', cUnit); set(FigureHandleCopy, 'Unit', cUnit); set(AxisHandle, 'Unit', cUnit); %% Get old axis position and inset offsets %Note that the axes and title are contained in the inset OldAxisPosition = get(AxisHandle, 'Position'); OldAxisInset = get(AxisHandle, 'TightInset'); OldAxisWidth = OldAxisPosition(3); OldAxisHeight = OldAxisPosition(4); OldAxisInsetLeft = OldAxisInset(1); OldAxisInsetBottom = OldAxisInset(2); OldAxisInsetRight = OldAxisInset(3); OldAxisInsetTop = OldAxisInset(4); %% Set positions and size of the figure and the Axis if(~ShouldPrintAxes) FigurePosition = [0.0, 0.0, OldAxisWidth, OldAxisHeight]; PaperSize = [OldAxisWidth, OldAxisHeight]; AxisPosition = FigurePosition; else WidthWithInset = OldAxisWidth + OldAxisInsetLeft + OldAxisInsetRight; HeightWithInset = OldAxisHeight + OldAxisInsetTop + OldAxisInsetBottom; FigurePosition = [0.0, 0.0, WidthWithInset, HeightWithInset]; PaperSize = [WidthWithInset, HeightWithInset]; AxisPosition = [OldAxisInsetLeft, OldAxisInsetBottom, OldAxisWidth, OldAxisHeight]; end set(FigureHandleCopy, 'Position', FigurePosition); set(AxisHandle, 'Position', AxisPosition); %Note: these properties do not effect the preview but they are % absolutely necessary for the pdf!! set(FigureHandleCopy, 'PaperSize', PaperSize); set(FigureHandleCopy, 'PaperPosition', FigurePosition); %% Write the figure to the PDF file print('-dpdf', OutFileName); set(FigureHandleCopy, 'name', 'PDF Figure Preview', 'numbertitle', 'off'); %If you want to see the figure (eg, for debugging purposes), comment %the line below out. close(FigureHandleCopy); end 

Sample Images:

With axles:

Example PDF screenshot with axes

Without axles:

PDF screenshot example without axes

Testing Code:

 %% Generates a graph and saves it to pdf FigureHandle = figure; plot(1:100); title('testing'); %with axes SaveFigureAsVectorPDF(FigureHandle, 'withaxes.pdf', true); %without axes SaveFigureAsVectorPDF(FigureHandle, 'withoutaxes.pdf', false); 
+2
Jun 24 '17 at 15:35
source share

This works to display goals:

 set(gca, 'LooseInset', get(gca, 'TightInset')); 

It should work for printing. A.

+1
May 20 '11 at 9:21
source share

You can also do this in latex.

  • open eps file with notpad
  • go to the first line (%! PS-Adobe-3.1 EPSF- 3.0 )

If the last number is 3, search for "rf" and then comment out this line by typing % at the beginning of the line

else, if the last number is 2, find "pr" and then comment out this line by typing % at the beginning of the line

+1
Apr 11 '14 at 15:02
source share

For Linux users, the following command can help

ps2epsi <input.eps> <output.eps>

as suggested here

and if you intend to use latex, use the command Latex \includegraphics* instead of \includegraphics

+1
Jul 07 '14 at 12:23
source share

The following two-step approach (using pdfcrop) was used for me. Assuming you have all pdf tools and PDFcrop installed ( http://pdfcrop.sourceforge.net/ )

In MATLAB, type

 print -deps -r600 figure.eps 

And then on the command line

 ./cropEpsFigure.sh figure 

Using the following file: cropEpsFigure.sh

 #!/bin/bash /usr/texbin/epstopdf "$1.eps" /usr/texbin/pdfcrop "$1.pdf" /usr/local/bin/pdftops -eps "$1-crop.pdf"` 
0
Jun 05 '14 at 10:07 on
source share

save the chart in .eps format in Matlab, then run the esptopdf command under Linux. This does not require additional coding. Only a Linux machine is required.

0
Jul 07 '14 at 2:38
source share

You can use this command with Inkscape if you have existing PDF files with extra spaces.

 Inkscape.exe --file SomePDFWithWhitespace.pdf --export-pdf=SomePDFWithWhitespaceRemoved.pdf --export-area-drawing 

Note that this method still leaves some spaces, because the "drawing area" of the exported shape itself contains some spaces.

The effects of using Inkscape are shown below:

To: (figure saved using file β†’ Save As)

PDF saved using file -> Save as

After: (using Inkscape)

PDF Trimmed with the inkscape command shown above

-3
Sep 04 '12 at 8:24
source share



All Articles