# Including a length-dependent page range using pdfpages

I'd like to extract pages from 16 to (last page minus one) using pdfpages. I know I can access the last page via the token last, but I need to do arithmetic on it, to get a page range that looks like 16-(last-1).

Is there a way to do this in pdfpages ?

-
Related but not a duplicate: How to know the number of pages in a PDF file?. – Click Me Jul 11 '12 at 11:24

Assuming you use pdflatex to TeXify the following,

\documentclass{article}
\usepackage{pdfpages}

\begin{document}
\pdfximage{pstricks-doc.pdf}%
\newcount\N
\N=\pdflastximagepages\relax
\includepdf[pages=16-\the\N]{pstricks-doc}
\end{document}


For XeLaTeX (and PDFLaTeX) fans,

\documentclass{article}

\usepackage{pdfpages}
\usepackage{ifxetex}

\ifxetex
\newcount\pdflastximagepages
\def\pdfximage#1{\pdflastximagepages=\XeTeXpdfpagecount"#1"\relax}
\fi

\begin{document}
\pdfximage{filename.pdf}%
\newcount\N
\N=\pdflastximagepages\relax
\includepdf[pages=16-\the\N]{filename}
\end{document}

-

The following redefinition of \AM@checklast allows you to now use the new key prelast to insert up to the before-last page:

\usepackage{pdfpages}% http://ctan.org/pkg/pdfpages
\makeatletter
\def\AM@checklast#1-\END{%
\edef\AM@tempii{\AM@trim@space{#1}}%
\expandafter\ifx\expandafter\\\AM@tempii\\
\@tempcntb=\AM@pagecount\relax
\ifAM@DVIoutput
\ifnum\AM@pagecount=1
\@tempcntb\@tempcnta
\fi
\fi
\whiledo{\@tempcnta<\@tempcntb}{%
\AM@append{\the\@tempcnta}%
}%
\else
\def\AM@cmp{last}%
\ifx\AM@cmp\AM@tempii
\let\AM@tempii\AM@pagecount
\ifx\AM@cmp\AM@tempii%                                  |
\@tempcntb=\numexpr\number\AM@pagecount-1\relax%      |
\edef\AM@tempii{\the\@tempcntb}%                      |
\fi% <---------------------------------------------------
\fi
\AM@checkinteger{\AM@tempii}%
\ifAM@integer
\@tempcntb=\AM@tempii\relax
\AM@checkpagenumber{\the\@tempcntb}%
\ifnum\@tempcnta<\@tempcntb \def\AM@rel{<}\def\AM@inc{\@ne}%
\else \def\AM@rel{>}\def\AM@inc{\m@ne}\fi
\whiledo{\@tempcnta\AM@rel\@tempcntb}{%
\AM@append{\the\@tempcnta}%
}%
\else
\AM@setnewdocname{\AM@temp}%
\fi
\fi
}
\makeatother


The idea behind it is to insert a test case for the prelast "page", and to subtract one from \AM@pagecount - the number of pages within the document being read.

The intended use would be

\includepdf[pages=16-prelast]{file}

-
 Your solution is quite impressive, and does much more than what I had originally asked. But for what I need, the other answer suffices, and so I accepted it. – Suresh Jul 11 '12 at 15:45