# Includepdf causes an error message from pgfplots externalization

I have a file test.pdf which I include in a document containing also an externalized pgfplots picture.

When I compile the following code, I get the error message Sorry, the system call pdflatex ... did NOT result in a usable file. In order to make my code work, I first need to remove the includepdf statement, compile (to create the externalized figures) and then compile again with the includepdf statement.

I suppose that it is a bug, or is there any possibility to solve it ?

Of course, the file test.pdf is totally independent from the externalized pictures from pgfplots.

\documentclass{scrbook}

\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usepgfplotslibrary[external]
\tikzexternalize[shell escape=-enable-write18]
\usepackage{pdfpages}

\begin{document}
\includepdf{report_test-figure44}

\begin{tikzpicture}
\begin{axis}[
xlabel=Cost,
ylabel=Error]
(2,-2.8559703)
(3,-3.5301677)
};
\end{axis}
\end{tikzpicture}

\end{document}

-
I have found a hack to avoid this problem in my case : let the pdf document be full page with \AddToShipoutPicture. –  Laurent Sep 28 '13 at 18:06
Quite interestingly, if the \includepdf command is added after the externalize step has been performed, there's no error. –  egreg Sep 28 '13 at 22:18

There is the option to "optimize expensive commands away" when externalizing stuff.

Since the includepdf statement is irrelevant for externalize, we could optimize it away - and your example compiled fine.

To be more precise: I moved \usepackage{pdfpages} before the externalize call and configured includepdf as "remove away":

\documentclass{scrbook}

\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usepgfplotslibrary[external]
\usepackage{pdfpages}
\tikzexternalize[shell escape=-enable-write18,optimize command away=\includepdf]

\begin{document}
\includepdf{report_test-figure44}

\begin{tikzpicture}
\begin{axis}[
xlabel=Cost,
ylabel=Error]