2
votes

I am creating an R package "mytemplate" containing derived RMarkdown format from rmarkdown::pdf_document (as an R script function with report as the output, it calls header.tex file):

report <-  function() {

  ## location of resource files in the package
  header <- system.file("resources/header.tex", package = "mytemplate")

  ## derives the style from default PDF template
  rmarkdown::pdf_document(
    latex_engine = "xelatex", fig_caption = FALSE,
    includes = rmarkdown::includes(in_header = header)
    )
}

Within the header.tex I use an image file detected by system.file() rested in the resources/ folder in the inst/ package directory:

\usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{`r system.file("resources/cover.png", package = "mytemplate")`}
  }

Outside of my package and providing full YAML section in the .Rmd file, the pdf renders OK:

---
title: ""
output:
  pdf_document:
    latex_engine: xelatex
    fig_caption: false
header-includes:
  \usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{`r system.file("resources/cover.png", package = "mytemplate")`}
  }
---

text

But after installation when I use mytemplate::report as RMarkdown output, I am returned the error:

! LaTeX Error: File ``r system.file("resources/cover.png", package = "mytemp late")`' not found.

Is calling header.tex in the R script that's causing the error, or should I modify header.tex code and how?

1

1 Answers

3
votes

You are using an inline R chunk inside a tex document. That cannot work.

Instead, use the argument pandoc_args of pdf_document() to pass variables to pandoc. Inside the header.tex you can then use a pandoc variable:

args <- pandoc_variable_arg("cover", system.file("resources/cover.png", package = "mytemplate"))

report <-  function() {

  ## location of resource files in the package
  header <- system.file("resources/header.tex", package = "mytemplate")

  ## derives the style from default PDF template
  rmarkdown::pdf_document(
    latex_engine = "xelatex", fig_caption = FALSE,
    includes = rmarkdown::includes(in_header = header),
    pandoc_args = args  # pass to pandoc
    )
}

And header.tex:

\usepackage{fancyhdr}
  \thispagestyle{fancy}
  \fancyhead[LC]{
    \includegraphics{$cover$}
  }