Here is a modification to Compiling only a page range or page selection that allows you to use negative numbers that counts from the last page. So, for example, you could use
\discardpages{-2,-1}
to remove the last two pages, or
\keeppages{-3,-1}
to only keep the third-to-last and final page. The adaptation relies of lastpage
to place a \label{LastPage}
on the last page and use the page number in calculations (thanks to refcount
).
\documentclass{article}
\usepackage{lipsum,atbegshi,etoolbox}
\usepackage{lastpage,refcount}
\makeatletter
\newcommand{\discardpages}[1]{% \discardpages{<csv list>}
\xdef\discard@pages{#1}% Store pages to discard
\AtBeginShipout{% At shipout, decide whether to discard page/not
\renewcommand*{\do}[1]{% How to handle each page entry in csv list
\ifnum##1<0
\ifnum\value{page}=\numexpr\getpagerefnumber{LastPage}+##1+1\relax
\AtBeginShipoutDiscard% Discard page/not
\gdef\do####1{}% Do nothing further
\fi
\else% ##1 >= 0
\ifnum\value{page}=##1\relax%
\AtBeginShipoutDiscard% Discard page/not
\gdef\do####1{}% Do nothing further
\fi
\fi
}%
\expandafter\docsvlist\expandafter{\discard@pages}% Process list of pages to discard
}%
}
\newif\ifkeeppage
\newcommand{\keeppages}[1]{% \keeppages{<csv list>}
\xdef\keep@pages{#1}% Store pages to keep
\AtBeginShipout{% At shipout, decide whether to discard page/not
\keeppagefalse%
\renewcommand*{\do}[1]{% How to handle each page entry in csv list
\ifnum##1<0
\ifnum\value{page}=\numexpr\getpagerefnumber{LastPage}+##1+1\relax
\keeppagetrue% Page should be kept
\gdef\do####1{}% Do nothing further
\fi
\else% ##1 >= 0
\ifnum\value{page}=##1\relax%
\keeppagetrue% Page should be kept
\gdef\do####1{}% Do nothing further
\fi
\fi
}%
\expandafter\docsvlist\expandafter{\keep@pages}% Process list of pages to keep
\ifkeeppage\else\AtBeginShipoutDiscard\fi% Discard page/not
}%
}
\makeatother
%\discardpages{-2,-1}
\keeppages{-3,-1}% Keep these pages.
\begin{document}
\sloppy\lipsum[1-50]\lipsum[1-50]\lipsum[1-50]\lipsum[1-50]\lipsum[1-50]
\end{document}
The LastPage
reference will have to settle in order to be effective. So, you'll have to compile at least twice with every change in this \label
location (or at the first go).
No further testing was done to see whether atveryend
might be required.
\keeppages{-3,-1}
to keep only the third-to-last and final page (say), but any references to content on the discarded pages will be lost. Is this a sufficient solution?\keeppages{-3,-1}
?