lua-filters.md - added tikz filter example.

This commit is contained in:
John MacFarlane 2017-11-21 12:20:28 -08:00
parent 251fbfc60d
commit d070424b94

View file

@ -479,6 +479,89 @@ function CodeBlock(block)
end
```
## Building images with tikz
This filter converts raw LaTeX tikz environments into images.
It works with both PDF and HTML output. The tikz code is
compiled to an image using `pdflatex`, and the image is
converted (if necessary) from pdf to png format using
ImageMagick's `convert`, so both of these must be in the system
path. Converted images are cached in the working directory
and given filenames based on a hash of the source, so that
they need not be regenerated each time the document is built.
(A more sophisticated version of this might put these in a special
cache directory.)
```lua
local function tikz2image(src, filetype, outfile)
local tmp = os.tmpname()
local tmpdir = string.match(tmp, "^(.*[\\/])") or "."
local f = io.open(tmp .. ".tex", 'w')
f:write("\\documentclass{standalone}\n\\usepackage{tikz}\n\\begin{document}\n")
f:write(src)
f:write("\n\\end{document}\n")
f:close()
os.execute("pdflatex -output-directory " .. tmpdir .. " " .. tmp)
if filetype == 'pdf' then
os.rename(tmp .. ".pdf", outfile)
else
os.execute("convert " .. tmp .. ".pdf " .. outfile)
end
os.remove(tmp .. ".tex")
os.remove(tmp .. ".pdf")
os.remove(tmp .. ".log")
os.remove(tmp .. ".aux")
end
extension_for = {
html = 'png',
html4 = 'png',
html5 = 'png',
latex = 'pdf',
beamer = 'pdf' }
local function file_exists(name)
local f = io.open(name, 'r')
if f ~= nil then
io.close(f)
return true
else
return false
end
end
function RawBlock(el)
local filetype = extension_for[FORMAT] or "png"
local fname = pandoc.sha1(el.text) .. "." .. filetype
if not file_exists(fname) then
tikz2image(el.text, filetype, fname)
end
return pandoc.Para({pandoc.Image({}, fname)})
end
```
Example of use:
```
pandoc --lua-filter tikz.lua -s -o cycle.html <<EOF
Here is a diagram of the cycle:
\begin{tikzpicture}
\def \n {5}
\def \radius {3cm}
\def \margin {8} % margin in angles, depends on the radius
\foreach \s in {1,...,\n}
{
\node[draw, circle] at ({360/\n * (\s - 1)}:\radius) {$\s$};
\draw[->, >=latex] ({360/\n * (\s - 1)+\margin}:\radius)
arc ({360/\n * (\s - 1)+\margin}:{360/\n * (\s)-\margin}:\radius);
}
\end{tikzpicture}
EOF
```
# Module text
UTF-8 aware text manipulation functions, implemented in Haskell.