Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment

There is no need to redefine \includegraphics just

\maketletter
\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.

share|improve this answer
add comment

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}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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