# How to keep filecontents* from getting confused when it encloses \begin{document}..\end{document}?

I TeX the following code with pdflatex --shell-escape but the compilation got paused because of an error as the produced prepare.tex does not contain \end{document}.

\documentclass{article}
\begin{filecontents*}{prepare.tex}
\documentclass{beamer}
\usepackage{graphicx}
\usepackage[active,tightpage,graphics]{preview}
\PreviewBorder=0pt

\begin{document}
\begin{frame}
\only<1>{\includegraphics{example-image-a}}
\only<2>{\includegraphics{example-image-b}}
\end{frame}
\end{document}
\end{filecontents*}

\usepackage{animate}
\begin{document}
\immediate\write18{pdflatex.exe prepare.tex}
\animategraphics{10}{prepare.pdf}{}{}
\end{document}


How to keep filecontents* from getting confused when it encloses \begin{document}..\end{document}?

Bonus question (rather than I create a new question for it): How can I force filecontents to override the specified file if it already exists?

Edit: Actually there is no problem with filecontents. The source of problem is the extension .pdf in the \animategraphics. Now unfortunately, the title is misleading.

-
The bonus answer: Load the package filecontents. –  Marco Daniel Jul 29 '12 at 7:59
There is no problem with the prepare.tex file as per your MWE. It gets created properly. Have a look at that file with a text editor. –  Peter Grill Jul 29 '12 at 8:05
The package mwe is needed to get the graphics example-image-a and example-image-b –  Marco Daniel Jul 29 '12 at 8:19
@MarcoDaniel: No need, graphicx already provides us with them out of the box I think. –  kiss my armpit Jul 29 '12 at 8:22
you don't need to load mwe into the document but you need to have installed mwe (or at least extracted the images from the mwe distribution and placed them in the input path) –  David Carlisle Jul 29 '12 at 9:29

The following example works.

My changes

1. The argument of \animategraphics must NOT have a file extension.
2. I load the package filecontents to answer your bonus question.

Here the mwe:

\documentclass{article}
\usepackage{filecontents}
\usepackage{graphicx}
\begin{filecontents*}{prepare.tex}
\documentclass{beamer}
\usepackage{graphicx}
\usepackage[active,tightpage,graphics]{preview}
\PreviewBorder=0pt

\begin{document}
\begin{frame}
\only<1>{\includegraphics{example-image-a}}
\only<2>{\includegraphics{example-image-b}}
\end{frame}
\end{document}
\end{filecontents*}

\usepackage{animate}
\begin{document}
\immediate\write18{pdflatex.exe prepare.tex}
\animategraphics{10}{prepare}{}{}% <======= MUST NOT HAVE EXTENSION!
\end{document}


tested with Ubuntu+TeXLive

-