8
$\begingroup$

In order to save computation results, I want to programmatically create some MMA notebooks and export them as PDF files.

It works fine for text:

MakeNotebook[] := 
 Module[{nb, nbobj}, nb = NotebookCreate[];
   NotebookWrite[nb,Cell["A Dynamically Created Notebook", "Title"]];
   NotebookWrite[nb, Cell["The date is " <> DateString[], "Text"]];
   nbobj = NotebookGet[nb];
   NotebookClose[nb];
   nbobj]

nb = MakeNotebook[];
Export["~/Temp/test.pdf", nb]

But I had some problems for graphics:

MakeNotebook[] := 
 Module[{nb, nbobj}, nb = NotebookCreate[];
   NotebookWrite[nb,Cell["A Dynamically Created Notebook", "Title"]];

   NotebookWrite[nb, Plot[Sin[x], {x, -2, 2}]]; (* <- not OK *)

   NotebookWrite[nb, Cell["The date is " <> DateString[], "Text"]];
   nbobj = NotebookGet[nb];
   NotebookClose[nb];
   nbobj]

does not work as you get Graphics[{{{{}, {}, Annotation[{... in your PDF instead of your plot.

So my question is: how to include graphics?

$\endgroup$
7
$\begingroup$

It took me some time to find a working solution:

MakeNotebook[] := 
 Module[{nb, nbobj}, nb = NotebookCreate[];
   NotebookWrite[nb,Cell["A Dynamically Created Notebook", "Title"]];

   NotebookWrite[nb,Cell[BoxData[ToBoxes[Plot[Sin[x],{x,-2,2}]]],"Print"]]; (*<-OK*)

   NotebookWrite[nb, Cell["The date is " <> DateString[], "Text"]];
   nbobj = NotebookGet[nb];
   NotebookClose[nb];
   nbobj]

nb = MakeNotebook[];
Export["~/Temp/test.pdf", nb]

The right line was:

NotebookWrite[nb,Cell[BoxData[ToBoxes[Plot[Sin[x],{x,-2,2}]]],"Print"]];


The result is:

enter image description here

$\endgroup$
  • 4
    $\begingroup$ You could also use Paste[nb, Plot[Sin[x],{x,-2,2}]]. $\endgroup$ – Carl Woll Mar 13 at 15:07
  • $\begingroup$ @CarlWoll Thanks! That seems simpler effectively. Maybe you can write an answer I will be happy to accept it. $\endgroup$ – Picaud Vincent Mar 13 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.