[Tex/LaTex] Background images for code listings

backgroundsgraphicslistings

I've been searching around but I can't find any info for adding an image background for my code listing using the listings package. Is there a way to do this?

Best Answer

As PolGab says, there is always a tikz way. Here is one that uses the infamous \tikzmark to mark the begin and end of the listing, and then adds an image clipped to the size of the listing:

enter image description here

Note:

Issues:

This however has some serious issues:

  • A blank line is required before the listing (surprising result otherwise).

  • Not sure why the fudge facts were required, but they end up aligning the frame to pretty close to where the fram=tb option would have drawn the horizontal lines.

Code:

\documentclass{article}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathreplacing}

\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}

\newcommand*{\AddBackgroundImage}[4][]{%
%\pgfmathsetmacrp{\height}{}%
    \begin{tikzpicture}[overlay,remember picture]
    \coordinate (VCenter) at ($(#2)!0.5!(#3)$);
    \coordinate (Fudge) at (-\pgflinewidth,0);
    \coordinate (VFudge) at (0,\baselineskip);
    %\draw [red, thick,fill=yellow, fill opacity=0.2]% for debugging
    \clip
            ($(#2)+ (Fudge) - 0.50*(VFudge)$) -- 
            ($(#2) + (\linewidth,0) - 0.50*(VFudge)$) -- 
            ($(#3) + (\linewidth,0) + 1.25*(VFudge)$) --
            ($(#3)+ (Fudge) + 1.25*(VFudge)$) -- cycle;
    \path (VCenter) -- ++($(0.5*\linewidth,0)$) 
    node [opacity=0.3, #1] {\includegraphics[width=\linewidth]{#4}};
    \end{tikzpicture}%
}%


\lstset{
    language=C,
    basicstyle=\small\sffamily,
    %frame=tb,
    numbers=left,
    xleftmargin=5.0ex,
    numberstyle=\tiny,
    numbersep=4pt,
    stepnumber=2,
    keywordstyle=\color{blue}\bfseries
    }

\lstset{emph={%  Adjust any special keywords
    printf%
    },emphstyle={\color{red}\bfseries}%
}%


\begin{document}
\noindent
Here is an example of listings with a background image:

\noindent% Line above MUST be blank
\tikzmark{Start}%
\begin{lstlisting}
/* Hello World program */

#include<stdio.h>

struct cpu_info {
    long unsigned utime, ntime, stime, itime;
    long unsigned iowtime, irqtime, sirqtime;
};

main()
{
    printf("Hello World");
}\end{lstlisting}
\tikzmark{End}
\AddBackgroundImage{Start}{End}{images/EiffelWide}%
%
\noindent
Some text afterwards.
\end{document}