summaryrefslogtreecommitdiff
path: root/graphics/AddTeX2Eps/AddTeX2Eps.m
blob: 34afe29114ad94d03bacc22327540778c12bf1a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
(* ::Package:: *)

(* :Title: AddTeX2Eps *)
(* :Context: EpsTools`AddTeX2Eps` *)
(* :Author: Janko Slavic (janko.slavic@fs.uni-lj.si) *)
(* :Summary: 
    Package for using native LaTeX syntax on eps figures directly from Mathematica. 
    AddTeX2Eps calls latex.exe and dvips.exe and makes use of psfrag package (needs to be installed).

    default.tex is the LaTeX template where you can add packages and define your own LaTeX commands.
    Copy default.tex and AddTeX2Eps.m to ..\AddOns\StandardPackages\Graphics\  or to search path.

*)
(* :Package Version: 1.14 *)
(* :Mathematica Version: 7.0 *)
(* :History:
	1.14 by Janko Slavic, October, 2009 (some fixes for Mathematica 7.0).
	1.13 by Janko Slavic, December, 2006 (for linux compatibility default.tex is always used as lowercase).
	1.12 by Janko Slavic, April, 2006 (default.tex located in searh path or ..\AddOns\StandardPackages\Graphics\).
	1.11 by Janko Slavic, April, 2006 (directory problem resolved).
	1.1 by Janko Slavic, April, 2006.
	1.0 by Janko Slavic, 2003.
*)
(* :Keywords: eps, tex, latex, psfrag.  
*)


BeginPackage["EpsTools`AddTeX2Eps`"]

EpsExport::usage="EpsExport[fileName,graphics,PSFrag]
EpsExport is used to export graphics to eps files
and then use psfrag LaTeX package with latex.exe and dvips.exe. \n
fileName is a string with full path (long names and spaces can cause troubles)\n
graphics is a graphical object to export\n
PSFrag is List of strings with psfrag syntax\n
\n
Example:\n\n
Needs[\"EpsTools`AddTeX2Eps`\"];\n
fig = Plot[Sin[x^2], {x, 0, 4}, AxesLabel -> {\"a\",\"b\"},PlotLabel -> \"c\"];\n
EpsExport[\"d:/test.eps\",fig,\n
{\n
\"\\psfrag{a}[c]{$x$}\",\n
\"\\psfrag{b}[c]{$\\sin(x^2)$}\",\n
\"\\psfrag{c}[c]{Native \\LaTeX via psfrag package}\"\n
}]
";

CorrectBB::usage="Use to manually correct bounding box dimensions: {llx, lly, urx, ury}.\n
For example: {-10, 0, 0, 0} moves the lower left bounding box point for 10 points to the left.";

IncludeGraphicsOptions ::usage="Native LaTeX includegraphics options (scale, trim,...)";

DeleteTempFiles::usage="If you are having problems with compiling, it may help to look at the temporary files.
 Try to compile temp.tex with latex.exe."

Options[EpsExport]={
	CorrectBB -> {0, 0, 0, 0}, 
	IncludeGraphicsOptions -> "[scale=1.0]",
	DeleteTempFiles -> True};

Begin["`Private`"]

EpsExport[fileName_String, graphics_, PSFrag_List, opts___] := 
    Module[{stream},
      Export[fileName, graphics, "EPS"];
      stream = OpenAppend[fileName];
      (*Save PSFrag syntax in file - if needed later*)
      WriteString[stream, 
        "%%PSFragBegin\n" <> StringJoin[StringInsert[PSFrag,"\n%%",1]] <> 
          "\n%%PSFragEnd"];
      Close[stream];
      
      (*run latex and ps*)
      RunLaTeX[fileName, PSFrag, opts];
      ];


RunLaTeX[fileName_String, PSFrag_List, opts___] := 
    Module[{texDat, bbText, bb, stream, w, h, workD, llx, lly, urx, ury, 
        epsFile, tmp, deleteTempFiles},
      {{cllx, clly, curx, cury}, incGrapOpts, 
          deleteTempFiles} = {CorrectBB, IncludeGraphicsOptions, 
              DeleteTempFiles} /. Flatten[{opts}] /. Options[EpsExport];
      
      (*default.tex needs to be in Graphics dir*)
      (*if needed, add packages/new commands to default.tex*)
      texDat := Module[{out},
	  out=Import["EpsTools//default.tex", "Text"];
      out
	];
 
      (*Read bounding box*)
      stream = OpenRead[fileName];
      bbText = Find[stream, "%%BoundingBox:"];
      bb = ToExpression[Drop[StringSplit[bbText], 1]];
      Close[stream];
      {w, h} = IntegerPart[{bb[[3]] - bb[[1]], bb[[4]] - bb[[2]]}];



      (*Prepare TeX dat*)
      texDat = StringReplace[texDat,
          {"psfragSyntax" -> StringJoin[StringInsert[PSFrag,"\n",1]],
            "[scaleSyntax]" -> incGrapOpts,
            "figureName" -> StringReplace[StringReplace[fileName, "/" -> $PathnameSeparator], __ ~~$PathnameSeparator~~ name_ -> name],
            "{width}" -> "{" <> ToString[w] <> "pt}",
            "{height}" -> "{" <> ToString[h] <> "pt}"
            }];
      
      
      (*set working dir*)
      workDir = Directory[];
      SetDirectory[DirectoryName[StringReplace[fileName, "/" -> $PathnameSeparator]]];

      (*Export tex*)
      Export["EpsExport.tex", texDat, "Text"];
      
      (*Run Latex*)
      Run["latex EpsExport"];
      
      (*Run dvi to ps*)
      Run["dvips -E EpsExport"];
      

      (*read bounding box*)
      stream = OpenRead["EpsExport.ps"];
      bbText = Find[stream, "%%BoundingBox:"];
      {llx, lly, urx, ury} = ToExpression[Drop[StringSplit[bbText], 1]];
      Close[stream];




      (*correct bounding box*)
      {llx, ury, lly, urx} = {urx - w + cllx, lly + h + cury, lly + clly, 
          urx + curx};
      bbText = 
        ToString[llx] <> " " <> ToString[lly] <> " " <> ToString[urx] <> " " <>
           ToString[ury];
      epsFile = Import["EpsExport.ps", "Lines"];
      epsFile = Join[
          
          StringReplace[Take[epsFile, 20], 
            StartOfLine ~~ "%%BoundingBox:" ~~ tmp__ -> 
              "%%BoundingBox: " ~~ bbText],
          Drop[epsFile, 20]
          ];
      Export[fileName, epsFile, "Lines"];
      
      (*covert to pdf*)
      (*If[convertToPdf,Run["ps2pdf "<>fileName<>" "<>StringDrop[fileName,-4]<>".pdf"];];*)

      (*delete files*)
      If[deleteTempFiles,
        DeleteFile[{"EpsExport.ps", "EpsExport.aux", "EpsExport.dvi", "EpsExport.log",
               "EpsExport.tex"}];
        ];

      
      
      
      (*reset working dir*)
      SetDirectory[workDir];
      
      ];


End[]

Protect[EpsExport]

EndPackage[]