Last active
May 15, 2022 15:54
-
-
Save gfacciol/4099a3e28a2a29611d1d3323071f7be0 to your computer and use it in GitHub Desktop.
PanDoc filter to extract images from LaTeX with TikZ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- From: How to use PanDoc to derive output from LaTeX and TikZ to a DOCX file? | |
-- https://tex.stackexchange.com/questions/431719/how-to-use-pandoc-to-derive-output-from-latex-and-tikz-to-a-docx-file | |
-- see https://linuxtoosx.blogspot.com/2021/10/pandoc-quite-good-conversion-from-latex.html | |
local function tikz2image(src, outfile) | |
local tmp = os.tmpname() | |
local tmpdir = string.match(tmp, "^(.*[\\/])") or "." | |
local f = io.open(tmp .. ".tex", 'w') | |
f:write("\\documentclass{standalone}\n") | |
-- include all packages needed to compile your images | |
f:write("\\usepackage{tikz}\n\\usepackage{stanli}\n") | |
f:write("\\begin{document}\n") | |
f:write(src) | |
f:write("\n\\end{document}\n") | |
f:close() | |
os.execute("pdflatex -output-directory " .. tmpdir .. " " .. tmp) | |
os.execute("convert -density 300 " .. tmp .. ".pdf " .. outfile) | |
os.remove(tmp .. ".tex") | |
os.remove(tmp .. ".pdf") | |
os.remove(tmp .. ".log") | |
os.remove(tmp .. ".aux") | |
end | |
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) | |
-- Don't alter element if it's not a tikzpicture environment | |
if not el.text:match'^\\begin{tikzpicture}' then | |
return nil | |
-- Alternatively, parse the contained LaTeX now: | |
-- return pandoc.read(el.text, 'latex').blocks | |
end | |
local fname = pandoc.sha1(el.text) .. ".png" | |
if not file_exists(fname) then | |
tikz2image(el.text, fname) | |
end | |
return pandoc.Para({pandoc.Image({}, fname)}) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment