[Tex/LaTex] How to fit the table of contents into a single page? Revisited

page-breakingtable of contents

This question is essentially the same as How can I fit my table of contents into a single page?

"When I use \tableofcontents I get all my contents in a single page except for a line that goes on the other page, how can I make all in the same page?"

However, the solution given there does not help me, for the following reason. The page next to the ToC is text only (plus one line of ToC), the page after that starts with a section title. The last line of ToC seems to be forced here by LaTeX in order to avoid getting the section title at the bottom: it prefers to put a space between the ToC and the text rather than between paragraphs.

Is there an elegant solution to this?

Best Answer

Henrique's solution is hardwired to a position in the document and assumes that the toc will be only one page. Here is another solution.

\documentclass[12pt,a6paper]{article}
\usepackage{blindtext}
\makeatletter
\def\enlargetocpage{%
  \begingroup
  \@ifstar{\def\x{*}\@enlargetocpage}{\def\x{}\@enlargetocpage}%
}
\def\@enlargetocpage#1{%
  \toks@{#1}%
  \protected@edef\x{%
    \endgroup\noexpand\AtEndDocument{\noexpand\addtocontents{toc}%
    {\protect\enlargethispage\x{\the\toks@}}}%
  }\x
}
\makeatother

\enlargetocpage*{\baselineskip}

\begin{document}
\tableofcontents
\blindtext

\section{A section}

\subsection{And a subsection}

\blindtext

\blinddocument

\blinddocument

\blinddocument

\end{document}
Related Question