%SAVE2PDF Saves a figure as a properly cropped pdf % % save2pdf(pdfFileName,handle) % % - pdfFileName: Destination to write the pdf to. % - handle: (optional) Handle of the figure to write to a pdf. If % omitted, the current figure is used. Note that handles % are typically the figure number. % % Saves figure as a pdf with margins cropped to match the figure size. % (c) Gabe Hoffmann, gabe.hoffmann@gmail.com % Written 8/30/2007 function save2pdf(pdfFileName,handle) % Verify correct number of arguments error(nargchk(1,2,nargin)); % If no handle is provided, use the current figure as default if nargin==1 handle = gcf; end % Backup previous settings prePaperType = get(handle,'PaperType'); prePaperUnits = get(handle,'PaperUnits'); preUnits = get(handle,'Units'); prePaperPosition = get(handle,'PaperPosition'); prePaperSize = get(handle,'PaperSize'); % Make changing paper type possible set(handle,'PaperType',''); % Set units to all be the same set(handle,'PaperUnits','inches'); set(handle,'Units','inches'); % Set the page size and position to match the figure's dimensions paperPosition = get(handle,'PaperPosition'); position = get(handle,'Position'); set(handle,'PaperPosition',[0,0,position(3:4)]); set(handle,'PaperSize',position(3:4)); % Save the pdf (this is the same method used by "saveas") print(handle,'-dpdf',pdfFileName) % Restore the previous settings set(handle,'PaperType',prePaperType); set(handle,'PaperUnits',prePaperUnits); set(handle,'Units',preUnits); set(handle,'PaperPosition',prePaperPosition); set(handle,'PaperSize',prePaperSize);