Search code examples
rr-markdownknitrpandoctex

How to show the total number of pages in a PDF via the RMarkdown (i.e. display "Page 1 of 10")?


Given the code below, which currently outputs the page number on top of the page, I would like it to output the PDF page count as in Page 1 of 3. I have done a lot of searching but haven't found any way to include the total page number.

Question Is this possible to do w/ in R Markdown ? If not, are there any workarounds ?

I have googled this and haven't found anything obvious such as YAML or TeX solutions, however, I may be missing something or not searching for the correct things.

RMarkdown Code

---
title: "R Markdown Example With Numbered Sections"
output:
  bookdown::pdf_document2:
    toc: true
    toc_depth: 6
    number_sections: true
    includes:
        in_header: header.tex
header-includes:
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \fancyhead[RO,RE]{\thepage}
- \fancyhead[LO,LE]{Header Message}
- \fancyfoot[LE,LO]{Footer Messge on the Left}
- \fancyfoot[LE,RO]{Footer Messge on the Right}
---

\thispagestyle{fancy}

# Example R Rarkdown : Numbered Sections

## R Markdown

### Description

Some description text

\newpage

#### Details

Details go here.

\newpage

## Plots

Plots go here

\newpage

Last page

Current header

enter image description here

Desired Header

enter image description here


Solution

  • Make sure you have the lastpage package installed.

    Then modify your header includes to look like this:

    header-includes:
      - \usepackage{fancyhdr}
      - \usepackage{lastpage}
      - \pagestyle{fancy}
      - \fancyhead[RO,RE]{\thepage\ of \pageref{LastPage}}
      - \fancyhead[LO,LE]{Header Message}
      - \fancyfoot[LE,LO]{Footer Messge on the Left}
      - \fancyfoot[LE,RO]{Footer Messge on the Right}