[Tex/LaTex] Background image for minipage

backgroundsgraphicsminipage

I'd like to put a background image into a minipage, stretching exactly to the surrounding fbox. What's the best option to do that? (Searching the web, I only found solutions for backgrounding the whole page)

Best Answer

You basically need to store the minipage content in a box register, measure it and overlay it with the graphic. The following environment awaits the image file name as first argument and then accepts any minipage arguments:

\documentclass{article}

\usepackage{graphicx}

\newsavebox\mysavebox
\newenvironment{imgminipage}[2][]{%
   \def\imgcmd{\includegraphics[width=\wd\mysavebox,height=\dimexpr\ht\mysavebox+\dp\mysavebox\relax,#1]{#2}}%
   \begin{lrbox}{\mysavebox}%
   \begin{minipage}%
}{%
   \end{minipage}
   \end{lrbox}%
   \sbox\mysavebox{\fbox{\usebox\mysavebox}}%
   \mbox{\rlap{\raisebox{-\dp\mysavebox}{\imgcmd}}\usebox\mysavebox}%
}

\begin{document}

\begin{imgminipage}{imagefilename}{5cm}
    Some text\\
    Hello world!
\end{imgminipage}

\end{document}

Result


I added now a bgimage key to adjustbox (develop version) which allows you to add a background image. To have also a \fbox use either:

\begin{adjustbox}{minipage=<width>,fbox,bgimage=<image>}
    <text>
\end{adjustbox}

which adds the \fbox first and then places the background image behind it, so that the frame covers some small part of the image, or

\begin{adjustbox}{minipage=<width>,margin=\fboxsep,bgimage=<image>,frame}
    <text>
\end{adjustbox}

which adds the same margin manually, places the background image and then draws a tight frame around it, so that the image is fully shown (and a little bit smaller than before).