Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Using pandoc default.latex template results in: ! LaTeX Error: Can be used only in preamble #1510

@zeigerpuppy

Description

@zeigerpuppy

I am attempting to set a latex template file, so that I can customise the pdf_book output of bookdown.

Using RStudio and creating a standard bookdown project, I have:

  1. tried rendering pdf_book without specifying template (works)

  2. downloaded the pandoc default.latex from https://github.com/jgm/pandoc-templates/blob/master/default.latex and saved as default.tex in the root of project.

  3. edited _output.yml to include the saved template file:

...
bookdown::pdf_book:
  includes:
    in_header: preamble.tex
  latex_engine: xelatex
  citation_package: biblatex
  keep_tex: yes
  template: default.tex
bookdown::epub_book: default
  1. added graphics: true to the YAML header in index.html

This is required to load the \usepackage{graphicx} in the template, as mentioned in #1350 .

  1. tried rendering with both the "Build Book" option in RStudio and the bookdown::render_book("index.Rmd", "bookdown::pdf_book",config_file = "_bookdown.yml") command

  2. rendering the PDF with the template specified, produces the error:

! LaTeX Error: Can be used only in preamble.

I think this is to do with packages being loaded after the \begin{document} specifier in the template. However, I am not sure why it works with the default bookdown config vs adding the pandoc default template explicitly.

xfun::session_info('bookdown')

R version 4.5.1 (2025-06-13)
Platform: x86_64-pc-linux-gnu
Running under: Debian GNU/Linux forky/sid, RStudio 2025.9.0.387

Locale:
  LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C              
  LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8    
  LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8   
  LC_PAPER=en_AU.UTF-8       LC_NAME=C                 
  LC_ADDRESS=C               LC_TELEPHONE=C            
  LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C       

Package version:
  base64enc_0.1.3   bookdown_0.45.2   bslib_0.9.0      
  cachem_1.1.0      cli_3.6.5         digest_0.6.37    
  evaluate_1.0.5    fastmap_1.2.0     fontawesome_0.5.3
  fs_1.6.6          glue_1.8.0        graphics_4.5.1   
  grDevices_4.5.1   highr_0.11        htmltools_0.5.8.1
  jquerylib_0.1.4   jsonlite_2.0.0    knitr_1.50       
  lifecycle_1.0.4   memoise_2.0.1     methods_4.5.1    
  mime_0.13         R6_2.6.1          rappdirs_0.3.3   
  rlang_1.1.6       rmarkdown_2.30    sass_0.4.10      
  stats_4.5.1       tinytex_0.57      tools_4.5.1      
  utils_4.5.1       xfun_0.54         yaml_2.3.10

default.tex (unaltered from default at pandoc: https://github.com/jgm/pandoc-templates/blob/master/default.latex )

$passoptions.latex()$
\documentclass[
$for(babel-otherlangs)$
  $babel-otherlangs$,
$endfor$
$if(babel-lang)$
  $babel-lang$,
$endif$
$if(fontsize)$
  $fontsize$,
$endif$
$if(papersize)$
  $papersize$paper,
$endif$
$for(classoption)$
  $classoption$$sep$,
$endfor$
]{$documentclass$}
$if(beamerarticle)$
\usepackage{beamerarticle} % needs to be loaded first
$endif$
\usepackage{xcolor}
$if(geometry)$
\usepackage[$for(geometry)$$geometry$$sep$,$endfor$]{geometry}
$endif$
\usepackage{amsmath,amssymb}
$if(cancel)$
\usepackage{cancel}
$endif$
$--
$-- section numbering
$--
$if(numbersections)$
\setcounter{secnumdepth}{$if(secnumdepth)$$secnumdepth$$else$5$endif$}
$else$
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
$endif$
$fonts.latex()$
$font-settings.latex()$
$common.latex()$
$for(header-includes)$
$header-includes$
$endfor$
$after-header-includes.latex()$
$hypersetup.latex()$
$if(pdf-trailer-id)$

\ifXeTeX
\special{pdf:trailerid [ $pdf-trailer-id$ ]}
\fi
\ifPDFTeX
\pdftrailerid{}
\pdftrailer{/ID [ $pdf-trailer-id$ ]}
\fi
\ifLuaTeX
\pdfvariable trailerid {[ $pdf-trailer-id$ ]}
\fi
$endif$

$if(title)$
\title{$title$$if(thanks)$\thanks{$thanks$}$endif$}
$endif$
$if(subtitle)$
\usepackage{etoolbox}
\makeatletter
\providecommand{\subtitle}[1]{% add subtitle to \maketitle
  \apptocmd{\@title}{\par {\large #1 \par}}{}{}
}
\makeatother
\subtitle{$subtitle$}
$endif$
\author{$for(author)$$author$$sep$ \and $endfor$}
\date{$date$}

\begin{document}
$if(has-frontmatter)$
\frontmatter
$endif$
$if(title)$
\maketitle
$if(abstract)$
\begin{abstract}
$abstract$
\end{abstract}
$endif$
$endif$

$for(include-before)$
$include-before$

$endfor$
$if(toc)$
$if(toc-title)$
\renewcommand*\contentsname{$toc-title$}
$endif$
{
$if(colorlinks)$
$if(toccolor)$
\hypersetup{linkcolor=$toccolor$}
$endif$
$endif$
\setcounter{tocdepth}{$toc-depth$}
\tableofcontents
}
$endif$
$if(lof)$
\listoffigures
$endif$
$if(lot)$
\listoftables
$endif$
$if(linestretch)$
\setstretch{$linestretch$}
$endif$
$if(has-frontmatter)$
\mainmatter
$endif$
$body$

$if(has-frontmatter)$
\backmatter
$endif$
$if(nocite-ids)$
\nocite{$for(nocite-ids)$$it$$sep$, $endfor$}
$endif$
$if(natbib)$
$if(bibliography)$
$if(biblio-title)$
$if(has-chapters)$
\renewcommand\bibname{$biblio-title$}
$else$
\renewcommand\refname{$biblio-title$}
$endif$
$endif$
\bibliography{$for(bibliography)$$bibliography$$sep$,$endfor$}

$endif$
$endif$
$if(biblatex)$
\printbibliography$if(biblio-title)$[title=$biblio-title$]$endif$

$endif$
$for(include-after)$
$include-after$

$endfor$

$if(linestretch)$
\usepackage{setspace}
$endif$
$--
$-- paragraph formatting
$--
$if(indent)$
$else$
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
  \IfFileExists{parskip.sty}{%
    \usepackage{parskip}
  }{% else
    \setlength{\parindent}{0pt}
    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
  \KOMAoptions{parskip=half}}
\makeatother
$endif$
$if(beamer)$
$else$
$if(block-headings)$
% Make \paragraph and \subparagraph free-standing
\makeatletter
\ifx\paragraph\undefined\else
  \let\oldparagraph\paragraph
  \renewcommand{\paragraph}{
    \@ifstar
      \xxxParagraphStar
      \xxxParagraphNoStar
  }
  \newcommand{\xxxParagraphStar}[1]{\oldparagraph*{#1}\mbox{}}
  \newcommand{\xxxParagraphNoStar}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
  \let\oldsubparagraph\subparagraph
  \renewcommand{\subparagraph}{
    \@ifstar
      \xxxSubParagraphStar
      \xxxSubParagraphNoStar
  }
  \newcommand{\xxxSubParagraphStar}[1]{\oldsubparagraph*{#1}\mbox{}}
  \newcommand{\xxxSubParagraphNoStar}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
\makeatother
$endif$
$endif$
$--
$-- verbatim in notes
$--
$if(verbatim-in-note)$
\usepackage{fancyvrb}
$endif$
$-- highlighting
$if(listings)$
\usepackage{listings}
\newcommand{\passthrough}[1]{#1}
\lstset{defaultdialect=[5.3]Lua}
\lstset{defaultdialect=[x86masm]Assembler}
$endif$
$if(lhs)$
\lstnewenvironment{code}{\lstset{language=Haskell,basicstyle=\small\ttfamily}}{}
$endif$
$if(highlighting-macros)$
$highlighting-macros$
$endif$
$--
$-- tables
$--
$if(tables)$
\usepackage{longtable,booktabs,array}
\newcounter{none} % for unnumbered tables
$if(multirow)$
\usepackage{multirow}
$endif$
\usepackage{calc} % for calculating minipage widths
$if(beamer)$
\usepackage{caption}
% Make caption package work with longtable
\makeatletter
\def\fnum@table{\tablename~\thetable}
\makeatother
$else$
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
$endif$
$endif$
$--
$-- graphics
$--
$if(graphics)$
\usepackage{graphicx}
\makeatletter
\newsavebox\pandoc@box
\newcommand*\pandocbounded[1]{% scales image to fit in text height/width
  \sbox\pandoc@box{#1}%
  \Gscale@div\@tempa{\textheight}{\dimexpr\ht\pandoc@box+\dp\pandoc@box\relax}%
  \Gscale@div\@tempb{\linewidth}{\wd\pandoc@box}%
  \ifdim\@tempb\p@<\@tempa\p@\let\@tempa\@tempb\fi% select the smaller of both
  \ifdim\@tempa\p@<\p@\scalebox{\@tempa}{\usebox\pandoc@box}%
  \else\usebox{\pandoc@box}%
  \fi%
}
% Set default figure placement to htbp
\def\fps@figure{htbp}
\makeatother
$endif$
$if(svg)$
\usepackage{svg}
$endif$
$--
$-- strikeout/underline
$--
$if(strikeout)$
\ifLuaTeX
  \usepackage{luacolor}
  \usepackage[soul]{lua-ul}
\else
  \usepackage{soul}
$if(beamer)$
  \makeatletter
  \let\HL\hl
  \renewcommand\hl{% fix for beamer highlighting
    \let\set@color\beamerorig@set@color
    \let\reset@color\beamerorig@reset@color
    \HL}
  \makeatother
$endif$
$if(CJKmainfont)$
  \ifXeTeX
    % soul's \st doesn't work for CJK:
    \usepackage{xeCJKfntef}
    \renewcommand{\st}[1]{\sout{#1}}
  \fi
$endif$
\fi
$endif$
$--
$-- CSL citations
$--
$if(csl-refs)$
% definitions for citeproc citations
\NewDocumentCommand\citeproctext{}{}
\NewDocumentCommand\citeproc{mm}{%
  \begingroup\def\citeproctext{#2}\cite{#1}\endgroup}
\makeatletter
 % allow citations to break across lines
 \let\@cite@ofmt\@firstofone
 % avoid brackets around text for \cite:
 \def\@biblabel#1{}
 \def\@cite#1#2{{#1\if@tempswa , #2\fi}}
\makeatother
\newlength{\cslhangindent}
\setlength{\cslhangindent}{1.5em}
\newlength{\csllabelwidth}
\setlength{\csllabelwidth}{3em}
\newenvironment{CSLReferences}[2] % #1 hanging-indent, #2 entry-spacing
 {\begin{list}{}{%
  \setlength{\itemindent}{0pt}
  \setlength{\leftmargin}{0pt}
  \setlength{\parsep}{0pt}
  % turn on hanging indent if param 1 is 1
  \ifodd #1
   \setlength{\leftmargin}{\cslhangindent}
   \setlength{\itemindent}{-1\cslhangindent}
  \fi
  % set entry spacing
  \setlength{\itemsep}{#2\baselineskip}}}
 {\end{list}}
\usepackage{calc}
\newcommand{\CSLBlock}[1]{\hfill\break\parbox[t]{\linewidth}{\strut\ignorespaces#1\strut}}
\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{\strut#1\strut}}
\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{\strut#1\strut}}
\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
$endif$
$--
$-- Babel language support
$--
$if(lang)$
\ifLuaTeX
\usepackage[bidi=basic$if(shorthands)$$else$,shorthands=off$endif$$for(babeloptions)$,$babeloptions$$endfor$]{babel}
\else
\usepackage[bidi=default$if(shorthands)$$else$,shorthands=off$endif$$for(babeloptions)$,$babeloptions$$endfor$]{babel}
\fi
$if(babel-lang)$
$if(mainfont)$
\ifPDFTeX
\else
\babelfont{rm}[$for(mainfontoptions)$$mainfontoptions$$sep$,$endfor$$if(mainfontfallback)$,RawFeature={fallback=mainfontfallback}$endif$]{$mainfont$}
\fi
$endif$
$endif$
$for(babelfonts/pairs)$
\babelfont[$babelfonts.key$]{rm}{$babelfonts.value$}
$endfor$
\ifLuaTeX
  \usepackage{selnolig} % disable illegal ligatures
\fi
$endif$
$--
$-- pagestyle
$--
$if(pagestyle)$
\pagestyle{$pagestyle$}
$endif$
$--
$-- prevent overfull lines
$--
\setlength{\emergencystretch}{3em} % prevent overfull lines
$--
$-- tight lists
$--
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
$--
$-- subfigure support
$--
$if(subfigure)$
\usepackage{subcaption}
$endif$
$--
$-- text direction support for pdftex
$--
$if(dir)$
\ifPDFTeX
  \TeXXeTstate=1
  \newcommand{\RL}[1]{\beginR #1\endR}
  \newcommand{\LR}[1]{\beginL #1\endL}
  \newenvironment{RTL}{\beginR}{\endR}
  \newenvironment{LTR}{\beginL}{\endL}
\fi
\ifluatex
  \newcommand{\RL}[1]{\bgroup\textdir TRT#1\egroup}
  \newcommand{\LR}[1]{\bgroup\textdir TLT#1\egroup}
  \newenvironment{RTL}{\textdir TRT\pardir TRT\bodydir TRT}{}
  \newenvironment{LTR}{\textdir TLT\pardir TLT\bodydir TLT}{}
\fi
$endif$
$--
$-- bibliography support support for natbib and biblatex
$--
$if(natbib)$
\usepackage[$natbiboptions$]{natbib}
\bibliographystyle{$if(biblio-style)$$biblio-style$$else$plainnat$endif$}
$endif$
$if(biblatex)$
\usepackage[$if(biblio-style)$style=$biblio-style$,$endif$$for(biblatexoptions)$$biblatexoptions$$sep$,$endfor$]{biblatex}
$for(bibliography)$
\addbibresource{$bibliography$}
$endfor$
$endif$
$--
$-- csquotes
$--
$if(csquotes)$
\usepackage[$for(csquotesoptions)$$csquotesoptions$$sep$,$endfor$]{csquotes}
$endif$
\end{document}

Metadata

Metadata

Assignees

No one assigned

    Labels

    reprexneeds a minimal reproducible example

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions