I think I found an answer to both of my questions. It did take - as Yihui pointed out - quite some time. I'm including the answer here in case someone else turns out to need this (or myself at a later point).
Re 1) Render TikZ code to both pdf and gitbook
This turned out to be easier than I anticipated. Setting the argument fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png'
as part of the chunk arguments helps this along. If I'm not knitting to PDF then imagemagick or some other software automatically converts it to PNG.
Re 2) Modifying the font
As listed in my updated question this can be set by tweaking the file tikz2pdf.tex
that is part of knitr. A copy of it is included below so you don't have to search for it yourself. Setting the chunk argument engine.opts = list(template = "latex/tikz2pdf.tex")
enables you to put any desired fonts, LaTeX packages etc in preamble before the TikZ code is rendered.
Looking through the knitr
code, you can see that texi2dvi
is used to parse the tikz2pdf.tex
file with the TikZ code inserted. texi2dvi
calls pdflatex
which messes things up in case you need to use XeLaTeX or LuaLaTeX to include TrueType fonts using fontspec
.
I'm sure it would be possible to fix that somehow in the texi2dvi
code but a much simpler solution (at least for me) was to change the environment. If I set the two environmental variable before starting R and rendering the book then xelatex is automatically used for compiling all the code. In my bash terminal this is done using
export LATEX="xelatex"
export PDFLATEX="xelatex"
Voila!
The chunk becomes
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext=if (knitr:::is_latex_output()) 'pdf' else 'png', fig.cap='Some caption.', engine.opts = list(template = "latex/tikz2pdf.tex")
}
egin{tikzpicture}[scale=.7]
draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
draw [very thick] (5, 0) -- (13,0);
ode [below] at (2,-1) {large Hello};
ode [below, align=center] at (0,-1) {large Two\ lines};
end{tikzpicture}
```
and tikz2pdf.tex
is
documentclass{article}
include{preview}
usepackage[pdftex,active,tightpage]{preview}
usepackage{amsmath}
usepackage{tikz}
usetikzlibrary{matrix}
%% INSERT YOUR OWN CODE HERE
egin{document}
egin{preview}
%% TIKZ_CODE %%
end{preview}
end{document}
I'm still surprised at the whole flexibility of knitr
and related packages. Nice work Yihui!