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$

1 Answer 1

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$
2
  • 4
    $\begingroup$ You could also use Paste[nb, Plot[Sin[x],{x,-2,2}]]. $\endgroup$ Commented Mar 13, 2019 at 15:07
  • $\begingroup$ @CarlWoll Thanks! That seems simpler effectively. Maybe you can write an answer I will be happy to accept it. $\endgroup$ Commented Mar 13, 2019 at 15:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.