[Tex/LaTex] Vertical space of \includegraphics[height=2cm]

graphicsspacingvertical alignment

I am trying to place an image on the right of some individual lines of text that do not stretch over the entire \textwidth. The image will go higher than the first line and I have to be able to position the image very precisely. My idea was:

\documentclass{article} 
\usepackage{graphicx}
\textwidth=5cm
\begin{document}
\setlength{\parindent}{0pt}
A\\
B\\[-2cm]
C\hfill\includegraphics[height=2cm]{testimg}\\
D
\end{document}

which produces

What I don't like is that B and C are not on the same line, which means that in the the space between B and D is larger than the space between B and A (C will not be in the final document, it is just inserted for illustration).

Any ideas would be appreciated.

Best Answer

You should put the image in a vertical version of \rlap so that officially it doesn't take any vertical space. You can do this like this:

\documentclass{article} 
\usepackage{graphicx}
\textwidth=5cm
\begin{document}
\setlength{\parindent}{0pt}
A\\
B\hspace{4cm}\hbox to 0pt{\vbox to 0pt{\vss\rule{5cm}{2cm}}\hss}\\
D
\end{document}

(Here \rule is a demo replacement of the \includegraphics)

This also makes the image officially 0pt wide and you can position it using the value of \hspace.

However, you could control the position even more exact if you put both the text and the image into a picture environment like e.g. tikzpicture.