5
$\begingroup$

Sorry if this was asked before. I googled and could not find anything.

Many times I need to export a cell to a PDF. It is always the cell above. Currently I do this using the GUI, by selecting the cell first, then File->Save selection As then save it to a PDF file.

But sometimes I lose track of what file I saved the cell to (If I do not remember to add a comment).

Is it possible to use the Export command? This way by looking at the command below the cell, I know the name of the file.

With plots and graphics, this is easy to do, since I could do p=Plot[...] then do Export["plot.pdf",p]

Any suggestions how to do this for cell? It will always be the cell above where the command is issued, if this makes it any easier. (So can't use any hardcoded specific current cell number, since the cell numbers can change when modifying the notebook)

Mathematica graphics

I am using V12 on windows 10.

$\endgroup$
2
  • 1
    $\begingroup$ Does Export["code.pdf", NotebookRead[PreviousCell[]]] do what you want? $\endgroup$
    – Carl Woll
    Commented Sep 29, 2019 at 2:53
  • $\begingroup$ @CarlWoll Yes !, thank you, that is very good command. If you post that as answer, will be happy to accept it. $\endgroup$
    – Nasser
    Commented Sep 29, 2019 at 2:58

2 Answers 2

7
$\begingroup$

You can use PreviousCell for this purpose. For example:

Export["code.pdf", NotebookRead[PreviousCell[]]]

should grab the cell contents of the previous cell, and save it to your file.

$\endgroup$
1
$\begingroup$

(An addition to the answer by Carl Woll.)

It's worth knowing that we can also export an entire CellGroup using the same method, in which case the cells are exported with their brackets (which can be useful in some cases):

SelectionMove[PreviousCell[], All, CellGroup];
Export["CellGroup.pdf", NotebookRead[EvaluationNotebook[]]]

screenshot

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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