rpdfquarto

Using R Quarto to create PDF documents, how can I center code chunk output and add a background color?


This question builds off a previous question of mine: How can I center the output of general R results in Quarto?

But this time, in a R Quarto script that creates PDF output using xelatex, I can print general R object and the results will be left aligned on a white background. How can I center align general R results while changing the background color and text color of the output?

The code provided is from a default template Quarto file, and the image shows the results being left aligned by default.

```{r}
mtcars
```

Image of R output being left aligned on white background

If I am creating HTML output, I can use the following code to accomplish this. But this does not work for PDF documents.

<style>
.styled-output .cell-output {background-color:#212121}
.styled-output .cell-output pre {max-width:fit-content; margin-left:auto; margin-right:auto; color:#ececec}
</style>

```{r}
#| classes: styled-output
mtcars
```

Centered output on a dark background


Solution

  • Changing the background- and text-color is easy. Aligning the output with inner margins seems to be difficult. This is the closest to your requirement I could get: out

    ---
    title: |
      \huge \textbf{Title}
    format: 
      pdf:
        fig-format: pdf
        code-block-border-left: false
        code-block-bg: false
        fig-align: center
        include-in-header: 
          text: |
            \usepackage{fvextra} % Extended fancyvrb
            \usepackage{xcolor}  % For coloring
            \usepackage{etoolbox} % For redefining environments
            
            % Define custom colors
            \definecolor{outputbg}{HTML}{212121} % Black background
            \definecolor{outputfg}{HTML}{ececec} % White text
            
            % Customize Verbatim environment
            \DefineVerbatimEnvironment{verbatim}{Verbatim}{
              formatcom=\color{outputfg},
              bgcolor=outputbg,
              frame=none,
              fontsize=\small,
              bgcolorpadding = 2em
            }
    
           
    execute:
      warning: false
      message: false 
      error: false
      echo: true
    ---
    
    # Xelatex custom Verbatim style
    
    
    ```{r}
    mtcars
    ```