6

I want the images I'm using that exceed the page's text width to be scaled down to half the text width. Images that aren't wider than the text width don't need to be scaled. I have one markdown document that I'm converting to both html and pdf using pandoc.

The following code is in the preamble.

\usepackage{graphicx}
\makeatletter
\def\maxwidth{
\ifdim\Gin@nat@width>\linewidth
    \linewidth
\else
    \Gin@nat@width
\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}

What syntax do I use to have maxwidth = x * \linewidth where x = .5 (or some other number)? This is the 5th line in code block.

1

If you want to resize to half of \linewidth if it is wider than \linewidth then simply add a 0.5 in front of \linewidht in the then clause:

\usepackage{graphicx}
\makeatletter
\def\maxwidth{%
\ifdim\Gin@nat@width>\linewidth
    0.5\linewidth
\else
    \Gin@nat@width
\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}

There should also be a % after the {, otherwise you get a space there, which might cause trouble.


Note that the adjustbox package adds a max width key and also allows to use the original width ad \width with \adjincludegraphics. For this see my answer to Includegraphics maximum width.

8

There is no need to redefine \includegraphics just

\makeatletter
\setkeys{Gin}{width=\ifdim\Gin@nat@width>\linewidth
    0.5\linewidth
\else
    \Gin@nat@width
\fi}
\makeatother

In the preamble should cause all graphics inclusions to respect that scaling.

  • This has the added benefit of still respecting options given to the \includegraphics command. For example, \includegraphics[draft]{path} works as expected using the above method. When using the \renewcommand method, latex complains. – cledoux Sep 17 '15 at 16:54
  • 1
    Works great, but first line contains typo, should be: \makeatletter – ciri Nov 2 '18 at 13:31
1

The following redefinition of \includegraphics allows for that:

enter image description here

\documentclass{article}
\usepackage{graphicx}% http://ctan.org/pkg/graphicx
\makeatletter
\let\old@includegraphics\includegraphics
\renewcommand{\includegraphics}[2][,]{%
  \setbox9=\hbox{\old@includegraphics[#1]{#2}}%
  \ifdim\wd9>\textwidth
    \old@includegraphics[#1,width=.5\textwidth]{#2}%
  \else
    \old@includegraphics[#1]{#2}%
  \fi%
}
\makeatother
\begin{document}
\noindent\rule{\textwidth}{1pt} \par
\noindent\includegraphics[width=.8\textwidth,height=50pt]{example-image-a}\par
\noindent\includegraphics[width=1.1\textwidth,height=50pt]{example-image-a} \par
\noindent\rule[1ex]{.5\textwidth}{1pt}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.