I am looking for the prototypical \'Hello World\' program that creates a Mathematica Notebook file.
I have this working program.
package graphica;
A method for creating a formatted notebook file is shown here:
How to create a notebook with a properly formatted expression
You can box format your Mathematica code (mathCommand) using a kernel call, e.g.
String mathCommand = "Plot[Sin[x], {x, 0, 6}]";
mathCommand = "FullForm[ToBoxes[Defer[" + mathCommand + "]]]";
MathKernel kernel = new MathKernel();
kernel.Compute(mathCommand);
mathCommand = kernel.Result.ToString();
Then encapsulate it like so, and save it with .nb extension.
Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]
Mathematica notebooks are plaintext files with structures like
Notebook[{Cell[],Cell[]}]
You can work out the required structure by viewing them with a text editor. Assuming you can get Java to create a text file, save it with a .nb
file name ending, and invoke the command-line version of Mathematica, then what you want should be doable. You will probably want to set the input cells to initialization type.
It took some research but I managed to answer the question myself.
package graphica;
import com.wolfram.jlink.*;
/**
*
* @author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\ \SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
//test-1
ml.discardAnswer();
String expr = "Sum[k,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
//test-2
expr = "UsingFrontEnd[nb=NotebookPut[Notebook[{Cell[\"Graphics3D[Cuboid[]]\", \"Input\"]}]]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
expr = "UsingFrontEnd[NotebookSave[nb,\"TERRANOVA1\"]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}