1 module adrdox.latex; 2 3 import std.process; 4 import std.file; 5 6 import arsd.dom; 7 8 string makeDataUrl(string mimeType, in void[] data) { 9 import std.base64; 10 auto data64 = Base64.encode(cast(const(ubyte[])) data); 11 return "data:" ~ mimeType ~ ";base64," ~ cast(string)(data64); 12 } 13 14 // requires latex and dvipng to be installed on your system already, it just 15 // calls out to them in the shell 16 Element mathToImgHtml(string mathCode) { 17 18 string dir = tempDir; 19 20 // FIXME: this should prolly be unique or somethign 21 string filebase = "./adrdox"; 22 23 std.file.write(dir ~ "/" ~ filebase ~ ".latex", 24 `\documentclass{article} 25 \usepackage{amsmath} 26 \usepackage{amsfonts} 27 \usepackage{amssymb} 28 \pagestyle{empty} 29 \begin{document} 30 $ `~mathCode~` $ 31 \end{document}` 32 ); 33 34 auto tpl = executeShell( 35 "latex -interaction=nonstopmode " ~ filebase ~ ".latex" 36 ~ " && " ~ 37 "dvipng -T tight -D 200 -o "~filebase~".png -bg Transparent "~filebase~".dvi -z 9", 38 null, Config.none, size_t.max, dir 39 ); 40 41 if(tpl.status != 0) 42 return null; 43 44 45 auto prefix = dir ~ "/" ~ filebase; 46 if(exists(prefix ~ ".aux")) 47 remove(prefix ~ ".aux"); 48 if(exists(prefix ~ ".dvi")) 49 remove(prefix ~ ".dvi"); 50 if(exists(prefix ~ ".latex")) 51 remove(prefix ~ ".latex"); 52 if(exists(prefix ~ ".log")) 53 remove(prefix ~ ".log"); 54 55 if(exists(prefix ~ ".png")) { 56 auto file = read(prefix ~ ".png"); 57 remove(prefix ~ ".png"); 58 59 auto img = Element.make("img"); 60 img.alt = mathCode; 61 img.src = makeDataUrl("image/png", file); 62 img.className = "rendered-math"; 63 return img; 64 } 65 66 return null; 67 68 }