# How to include all pages except last one from an external PDF

I'm using the package pdfpages to insert (many) external PDFs in my pdflatex compiled document, but I need to insert separately all the pages but the last one and the last page (I have to issue some commands in between). It seems that the pages option of includepdf command hasn't a direct way to do it.

I tried using \the\pdflastximagepages but I'm not good enough at LaTeX to deploy it for this task. Thanks in advance for any clue.

Here is a MWE to work on.

\documentclass{minimal}
\usepackage{pdfpages}
\begin{document}

\pdfximage{test.pdf}
\def\lastbutonepage{3}% set for testing purpose assuming 'test.pdf' has 4 pages

\ifnum\lastbutonepage>0
\includepdf[pages=-\lastbutonepage]{test.pdf}
\fi
Something in between.
\includepdf[pages=\the\pdflastximagepages]{test.pdf}

\end{document}


Here I store the last page (number) as well as the page before that in \totalpages and \lastbutonepage:

\documentclass{article}

\usepackage{pdfpages}

\begin{document}

\edef\totalpages{\the\pdflastximagepages}% Store number of pages
\edef\lastbutonepage{\number\numexpr\totalpages-1}% Store last page - 1

\ifnum\totalpages>1
\includepdf[pages=1-\lastbutonepage]{example-image-letter-numbered.pdf}%
\fi
Something in the middle.

\includepdf[pages=\totalpages]{example-image-letter-numbered.pdf}

\end{document}

• Nice to know. Just wondering, why do you need the \number in that definition? – daleif Jul 17 '18 at 20:03
• @daleif: Without it, \lastbutonepage isn't properly expanded to just contain the result of the numeric expression. As such, it's carried forward to the optional argument of \includepdf and it doesn't like that. – Werner Jul 17 '18 at 20:10
• Thanks, I would have thought edef took care of that, I was mistaken. – daleif Jul 17 '18 at 20:12