2
$\begingroup$

I am trying to convert a Cell expression to an image.

I created a new notebook and copied the cells that need to be rendered.

nb = CreateDocument[{},
    WindowSelected -> False, Visible -> True,
    WindowSize -> 650, StyleDefinitions -> "Default.nb"
];
(*Find and Copy the Cell Groups*)
image = Rasterize[nb, "Image"]

I want to automate this process now,finding all the Input|Output groups and render.


A Input|Output Group should be defined from Input to the last GeneratedCell, including Print, Message, etc.

enter image description here

Cell Style "Code" and "Program" also have Output, but I hope to eliminate them.

$\endgroup$
  • $\begingroup$ Do you care about In[]/Out[]? or only about contents? $\endgroup$ – Kuba Nov 3 '18 at 10:14
  • $\begingroup$ Yes,best to keep, I think it's Useful and beautiful. $\endgroup$ – GalAster Nov 3 '18 at 10:42
3
$\begingroup$

Let me know if this fits your needs:

rasterizeInOut[nb_NotebookObject] := Module[{printNb, image, cells},
  printNb = CreateDocument[{}, Visible -> False];
  cells = Cells[nb, CellStyle -> {"Input"}];
  cells = Flatten[
    If[ 
      Lookup[Developer`CellInformation[#], "FirstCellInGroup"], 
      SelectionMove[#, All, CellGroup]; SelectedCells[nb], 
      #
    ] & /@ cells
  ];
  NotebookWrite[printNb, #] & /@ NotebookRead /@ cells;
  image = Rasterize @ printNb;
  NotebookClose @ printNb;
  image
]

rasterizeInOut @ nb

On the left there is a source nb and on the right an image generated from filtered source:

enter image description here

$\endgroup$
  • $\begingroup$ Nice, this works. One more question, is it possible to insert an In[ ] when there only one input cell in notebook.For example, run itself in one cell: rasterizeInOut@EvaluationNotebook[] $\endgroup$ – GalAster Nov 3 '18 at 11:33
  • $\begingroup$ Strange it is not included, will try to take a closer look later. $\endgroup$ – Kuba Nov 3 '18 at 11:40

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.