2

I find that my pdfs are exceedingly large, since I use many high quality pictures in them. To automatically reduce the quality, I found this question [ Can pdflatex (or any tex package) automatically rescale included images which have been reduced in size? ] with this really cool answer-code (thanks @daau):

% for downsampling large images: \includegraphicsRS
% (\includegraphics "resize")

\newcommand{\includegraphicsRS}{}

\ifnum\pdfshellescape=1
% Yes, enabled
% #2 is the filename - assumed relative
% IFP - image file path
% IFN - image filename only
% here resizing at 800 px wide
\newread\myinput
% must add default argument [] so typeout works
\renewcommand\includegraphicsRS[2][\@empty]{%
% run downsampling bash script
\immediate\write18{mkdir -p downsampled; IFP=#2 ; %
  echo "Processing $IFP" ; %
  IFN=$(basename $IFP) ; %
  echo "downsampled/$IFN" > tmpname ; %
  if [ ! -f downsampled/$IFN ]; then %
  echo "File downsampled/$IFN not found! Converting..." ; %
  % convert $IFP -resize 50\% downsampled/$IFN ; %
  convert $IFP -resize 800x downsampled/$IFN ; %
  else %
  echo "Found downsampled/$IFN - reusing." ; %
  fi ; %
} % end write18
% here we should have downsampled file
% retrieve downsample filename first
\immediate\openin\myinput=tmpname
% The group localizes the change to \endlinechar
\bgroup
  \endlinechar=-1
  \immediate\read\myinput to \localline
  % Since everything in the group is local, we have to explicitly make the
  % assignment global
  \global\let\myTmpFileName\localline
\egroup
\immediate\closein\myinput
% Clean up after ourselves
% \immediate\write18{rm -f -- tmpname}
% finally, include downsampled image
\includegraphics[#1]{\myTmpFileName}
} % end renewcommand
\else
% No, disabled
% in this case, \includegraphicsRS is just the usual \includegraphics
\renewcommand\includegraphicsRS[2][\@empty]{%
\includegraphics[#1]{#2}
}
\fi

Now I don't want to simply use a width of 800px for each image, but to calculate a width in pixel depending on the first parameter of \includegraphicsRS (e.g. \includegraphicsRS[width=0.5\textwidth]{test.jpg}).

For that I want to replace the string \textwidth with the actual textwidth in px.

Q1: I used

textwidth="\the\textwidth" ; %
TW=${textwidth:0:(-2)} ; %

inside the \write18 environment. The first line works fine (returns something like '455.24411pt' for a4 with 2cm margins).

But the second line (intended to remove the pt at the end) does not work. Why? I don't get it and can't find anything related.

Q2: Since it would require some more ugly steps (multiplying by something like 1.3, finding xx in width=xx\textwidth and calulating that) and the fact that after that it still does only work with \textwidth: Has anyone a better idea on how to do this?

  • I found at least how to prevent ImageMagick to produce larger files than the originals: -resize "800x\string>" does the trick. – 3244611user Jul 14 '15 at 14:42

0 Answers0