获取目录中每章的总页数

获取目录中每章的总页数

我需要获取某一章的总页数,以便在目录中,如果是第 1 章,则为 1-4,如果是第 2 章,则为 5-19在此处输入图片描述 章节开始的页码

答案1

以下内容基于book 类中\chapter找到的定义base.sty,可能不适用于 \chapter 的修改版本。此外,它可能与包冲突lastpage。哦,你必须\lastpage在每一章的末尾手动插入。

\documentclass{book}
\usepackage{lipsum}

\makeatletter
\newcommand{\newlastpage}[2]% #1=chapter, #2=page
{\global\expandafter\def\csname lastpage@chapter#1\endcsname{#2}}

\newcommand{\thelastpage}[1]% #1 = chapter
{\@ifundefined{lastpage@chapter#1}{}%
  {\rlap{-\csname lastpage@chapter#1\endcsname}}}

\newcommand{\lastpage}%
{\protected@write\@auxout{}{\string\newlastpage{\thechapter}{\thepage}}}

% copied (and modified) from base.sty for book class
\def\@chapter[#1]#2{\ifnum \c@secnumdepth >\m@ne
  \if@mainmatter
    \refstepcounter{chapter}%
    \typeout{\@chapapp\space\thechapter.}%
    \addtocontents{toc}{\contentsline {chapter}{\protect\numberline {\thechapter}#1}{\thepage\thelastpage{\thechapter}}}
  \else
    \addtocontents{toc}{\contentsline {chapter}{#1}{\thepage\thelastpage{\thechapter}}}
  \fi
\else
  \addtocontents{toc}{\contentsline {chapter}{#1}{\thepage\thelastpage{\thechapter}}}
\fi
\chaptermark{#1}%
\addtocontents{lof}{\protect\addvspace{10\p@}}%
\addtocontents{lot}{\protect\addvspace{10\p@}}%
\if@twocolumn
  \@topnewpage[\@makechapterhead{#2}]%
\else
  \@makechapterhead{#2}%
\@afterheading
\fi}
\makeatother

\begin{document}
\tableofcontents
\chapter{First}
\lipsum[1-10]
\lastpage
\chapter{Second}
\lipsum[1-10]
\lastpage

\end{document} 

相关内容