Search code examples
rlatexr-markdownpandockableextra

Adding background image to R Markdown (.rmd) file for PDF document?


I have seen this post to include a background image to an R markdown report.

I have created a Shiny app to generate a pdf report:

shinyApp(
  ui = fluidPage(
    sliderInput("slider", "Slider", 1, 10, 5),
    downloadButton("report", "Generate report")
  ),
  server = function(input, output) {
    test1 <- reactive({
      n = input$slider
      df=matrix(1:n^2,n,n)
      df = as.data.frame(df)
      result <- list(df=df,n=n)
      return(result)

    })

    output$report <- downloadHandler(
      # For PDF output, change this to "report.pdf"
      filename = "report.pdf",
      content = function(file) {
        # Copy the report file to a temporary directory before processing it, in
        # case we don't have write permissions to the current working dir (which
        # can happen when deployed).
        tempReport <- file.path(tempdir(), "report.Rmd")
        file.copy("report.Rmd", tempReport, overwrite = TRUE)

        # Set up parameters to pass to Rmd document
        params <- list(n = test1()$n,
                       df = test1()$df)

        # Knit the document, passing in the `params` list, and eval it in a
        # child of the global environment (this isolates the code in the document
        # from the code in this app).
        rmarkdown::render(tempReport, output_file = file,
                          params = params,
                          envir = new.env(parent = globalenv())
        )
      }
    )
  }
)

And here is my .rmd file :

---
title: "Title"
author: "Name"
date: "`r Sys.Date()`"
output: 
  pdf_document :
    fig_caption: yes
    keep_tex: yes
    number_sections: yes
header-includes:
 \usepackage{booktabs}
 \usepackage{longtable}
 \usepackage{array}
 \usepackage{multirow}
 \usepackage{wrapfig}
 \usepackage{float}
 \usepackage{colortbl}
 \usepackage{pdflscape}
 \usepackage{tabu}
 \usepackage{threeparttable}
 \usepackage{threeparttablex}
 \usepackage[normalem]{ulem}
 \usepackage{makecell}
 \usepackage{background}
 \backgroundsetup{
 scale=1,
 color=black,
 opacity=0.4,
 angle=0,
 pages=all,
 contents={
  \includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
 }
 }
params:
  n: NA
  df: NA
---

```{r}
# The `params` object is available in the document.
params$n
```

A plot of `params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```
```{r}
params$df %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.85),
font_size = spec_font_size(x))
}) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")%>%
  kable_styling(latex_options = c("striped", "scale_down"))
```

The error that I'm getting is :

! Undefined control sequence.
l.171 \centering\rowcolors
                          {2}{gray!6}{white} 
Here is how much of TeX's memory you used:
 24161 strings out of 492990
 415742 string characters out of 6136334
 504502 words of memory out of 5000000
 27291 multiletter control sequences out of 15000+600000
 19644 words of font info for 30 fonts, out of 8000000 for 9000
 1141 hyphenation exceptions out of 8191
 62i,4n,56p,577b,315s stack positions out of 5000i,500n,10000p,200000b,80000s

  [1]: http

Which in tex community they referring to forgetting something like \end{document}. I should mention that if I use the .rmd file alone and replace the last part with :

{r}
library(kableExtra)
library(dplyr)
iris[1:10, ] %>%
mutate_if(is.numeric, function(x) {
cell_spec(x, "latex", bold = T, color = spec_color(x, end = 0.9),
font_size = spec_font_size(x))
}) %>%
mutate(Species = cell_spec(
Species, "latex", color = "white", bold = T,
background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
)) %>%
kable("latex", escape = F, booktabs = T, linesep = "", align = "c")

I will be able to compile it with that background image, the current shiny app is also generating the report if I exclude the part that related to the background image setting.


Solution

  • That's because xcolor must be loaded before background. Do:

    ---
    title: "Title"
    author: "Name"
    date: "`r Sys.Date()`"
    output: 
      pdf_document :
        fig_caption: yes
        keep_tex: yes
        number_sections: yes
    header-includes:
     \usepackage{background}
     \usepackage{float}
     \backgroundsetup{
     scale=1,
     color=black,
     opacity=0.4,
     angle=0,
     pages=all,
     contents={
      \includegraphics[width=\paperwidth,height=\paperheight]{C:/Users/path_to_image/image.jpg}
     }
     }
    ---
    

    Note that your "header-includes" is useless because all these packages are automatically included.