It is possible to export a notebook to plain text format (practically just extracting all the text from it and discarding formatting) using the File -> Save As...
menu item.
How can a notebook be exported to plain text programmatically, without making use of any GUI?
With all the other document formats, such as PDF, HTML, NB, LaTeX, etc. it is possible to simply use Export
:
ExportString[NotebookGet@EvaluationNotebook[], "LaTeX"]
This does not work with the export format "Text"
though. It simply exports the notebook expression in a Mathematica expression format. Is there an export format which will export the contents of the notebook to plain text instead of the expression representing it?
I would prefer a method that can produce an in-memory string as well (just like ExportString
), and can avoid writing on disk.
EDIT: Based on this answer, I found First@FrontEndExecute[ FrontEnd`ExportPacket[NotebookGet@InputNotebook[], "InputText"]]
. I'd prefer something documented though, if it exists.
Answer
Saving is done by the front end, which you can exploit programatically by using FrontEndExecute
. I think this is what you need:
nb=InputNotebook[];
fn=FileNameJoin[{"output.txt"}];
FrontEndExecute[FrontEndToken[nb,"Save",{fn,"Text"}]]
Edit: Of course you can also save it as a package by replacing "Text" with "Package".
Comments
Post a Comment