Matlab - otfried/ipe-wiki GitHub Wiki

Creating Ipe documents from Matlab figures

In order to simply create nice Ipe PDFs from Matlab figures we need to write a script that does the following:

  1. Save the figure as a PDF.
  2. [Optional?] Crop the PDF (matlab gets this totally wrong).
  3. Convert the generic PDF to an Ipe-compatible PDF using pdf2ipe.

Saving the figure as a PDF

The code is fairly simple. Save the following file in your path. If you get really bad JPEG artifacts in your PDFs follow the instructions linked in the code.

function SaveFigure(filename, figure_handle)
% SaveFigure(filename)
% SaveFigure(filename, figure_handle)
%
% Save the figure to an ipe-compatible PDF.
% Filename is the name of the file to save it to (you can omit the .pdf
% extension if you like). figure_handle gives the figure to save. If
% omitted the current figure is used.

% See http://www.histed.org/wiki/index.php?title=Controlling_matlab%27s_pdf_output
% to improve the pdf quality.

filename(find(filename # '\')) = '/';

if numel(filename >= 4) && strcmpi(filename(end-3:end), '.pdf')
    filename = filename(1:end-4);
end

if nargin < 2
    figure_handle = gcf;
end

print(figure_handle, '-dpdf', '-painters', '-r2400', filename); % Save as PDF
CropPDF(filename); % Crop PDF
PDFtoIpe(filename); % Convert to Ipe-compatible PDF.

end

Cropping the PDF

You need pdfcrop.pl in your path. This should be done already (I think) if you have matlab and miktex installed correctly. Here's the code that calls it. Save this file in your path.

function CropPDF(pdffile)
% Uses the pdfcrop program to crop the PDF.
% pdffile is the file name (without the extension) to crop. It is
% overwritten.

% You need the pdfcrop.pl script in the current directory (or you can
% modify the command line below to point to it), and a version of perl
% installed.
%
% pdfcrop.pl is available on ctan, and you can use ActivePerl on windows.

system(['perl pdfcrop.pl --verbose --margin 5 "' pdffile '.pdf"']);
movefile([pdffile '-crop.pdf'], [pdffile '.pdf']);

end

Converting the PDF to an Ipe-compatible file

Finally add this file to your path. Be sure to change the code to point to the location of your pdf2ipe program.

function PDFtoIpe(pdffile)
% Uses the PDFtoIpe program to convert the PDF to one Ipe can edit.
% pdffile is the file name (without the extension) to convert. It is
% overwritten.

% Alter these paths to point to the location of your ipe programs.
pdftoipe = 'C:/.../ipe/bin/pdftoipe.exe';
ipetoipe = 'C:/.../ipe/bin/ipetoipe.exe';

system(['"' pdftoipe '" "' pdffile '.pdf" "' pdffile '.xml"']);
system(['"' ipetoipe '" -pdf "' pdffile '.xml" "' pdffile '.pdf"']);
delete([pdffile '.xml']);

end