Controlling matlab's pdf output

From WikiHistedOrg

Jump to: navigation, search

Problem: you try to save a matlab figure as a PDF, and images in the figure look distorted or downsampled.
This is probably because Matlab's PDF output compresses images as JPEG.
Two solutions: change the JPEG compression settings to get better output, or compress as ZIP, not as JPEG.

[edit] Changing how Matlab exports PDF files

Matlab first generates a postscript file internally then calls ghostscript on it, using the pdfwrite device, to produce a pdf. There's no way to customize the ghostscript parameters without editing the toolbox ghostscript.m file.

Use

which -all ghostscript

to find ghostscript.m, which sets up the parameters for the ghostscript call.

for me this is at

>> which -all ghostscript
/Applications/MATLAB_R2007b/toolbox/matlab/graphics/private/ghostscript.m  % Private to graphics


Then between the two lines below:

fprintf(rsp_fid, '-sOutputFile="%s"\n', pj.GhostName );
fclose(rsp_fid);

(These are at line 160 and 161 for my copy of R2007b)

Insert these lines:

% add these lines to ghostscript.m
if strcmp(pj.GhostDriver, 'pdfwrite')

    % Uncomment to embed images into file as ZIP not jpeg compressed
    fprintf(rsp_fid, '-dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode\n');
    
    % control resolution/downsampling of embedded images
    fprintf(rsp_fid, '-dDownsampleColorImages=false\n');
    %fprintf(rsp_fid, '-dColorImageDownsampleThreshold=1.5\n');
    %fprintf(rsp_fid, '-dColorImageResolution=300\n');
end

Done.

If you want to change the JPEG quality, use


     % uncomment this to get high-quality jpeg compression in pdf files
     fprintf(rsp_fid, ['-c .setpdfwrite << /ColorACSImageDict ' ...
                       '<< /QFactor 0.15 /Blend 1 /ColorTransform 1 '...
                       '   /HSamples [1 1 1 1] /VSamples [1 1 1 1]' ...
                       '>> >> setdistillerparams\n-f\n']);

The "QFactor" controls the JPEG quality- 0.5 is equivalent to JPEG Quality 75 and lower QFactor gives better quality.

Important: the '-c' command must be last in the parameter list; that's why it's right before 'fclose(rsp_fid)'.

search google for "ghostscript qfactor", "ps2pdf default ColorACSImageDict pdfwrite" for more details.