Search code examples
pdftextheaderr-markdowncenter

How to center in specific section of a pdf file created with RMarkdown a subtitle


I am trying to center the subtitle of a section for a pdf created with RMarkdown.

I am using the following code

---
title: "example"
author: "X"
date: "2023-09-23"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


## *Title*

### <h3 align="center" id="heading">*Title2*</h3>


```{r cars}
summary(cars)
```

However I am getting this output

enter image description here

While the output I am looking for is:

Title
                          Title2 (at the center)

I do not know what I am getting wrong.


Solution

  • One way of doing this defining a latex macro that will center the subsubsection text.

    \newcommand{\csubsubsection}[1]{
    \subsubsection{\texorpdfstring{\centering\emph{#1}}{#1}}
    }
    

    and then use the raw latex command \csubsubsection{subsection-title} directly.

    ---
    title: "example"
    author: "X"
    date: "2023-09-23"
    output: pdf_document
    ---
    
    \newcommand{\csubsubsection}[1]{
    \subsubsection{\texorpdfstring{\centering\emph{#1}}{#1}}
    }
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ## *Title*
    
    \csubsubsection{Model Applied (lm(y $\sim$ x))}
    
    ```{r cars}
    summary(cars)
    ```