2

I'm trying to programmatically save all input-output cell groups in a given notebook as automatically named pdfs. Is there a way to provide the filename, and save it as a PDF with cell labels but not brackets (just like "File" ► "Save Selection As...").

This is the closest I came but it misses the cell labels:

SelectionMove[EvaluationNotebook[], Previous, CellGroup, 2];
FrontEnd`SaveSelectionAs["~/out.pdf", EvaluationNotebook[], "PDF"]

This question's answer doesn't print the cell labels either, but the comments look like they might have a clue, not sure how to use "CellLabelsToTags" though.

M.R.
  • 31,425
  • 8
  • 90
  • 281

1 Answers1

3

You need to override the Notebook level CellLabelAutoDelete setting. Try the following:

SelectionMove[EvaluationNotebook[],Previous,CellGroup,2];
Internal`WithLocalSettings[
    CurrentValue[EvaluationNotebook[], CellLabelAutoDelete] = False,
    FrontEnd`SaveSelectionAs["~/out.pdf", EvaluationNotebook[], "PDF"],
    CurrentValue[EvaluationNotebook[], CellLabelAutoDelete] = Inherited
]

If you want to control other Notebook options, you can instead control the options of the FrontEnd session:

SelectionMove[EvaluationNotebook[],Previous,CellGroup,2];
Internal`WithLocalSettings[
    CurrentValue[$FrontEndSession, CellLabelAutoDelete] = False;
    CurrentValue[$FrontEndSession, ShowCellBracket] = False,
    FrontEnd`SaveSelectionAs["~/out.pdf", EvaluationNotebook[], "PDF"],
    CurrentValue[$FrontEndSession, CellLabelAutoDelete] = Inherited;
    CurrentValue[$FrontEndSession, ShowCellBracket] = Inherited
]

You can also call ExportPacket directly, the function that FrontEnd`SaveSelectionAs ultimately calls:

SelectionMove[EvaluationNotebook[],Previous,CellGroup,2];
Internal`WithLocalSettings[
    CurrentValue[$FrontEndSession, CellLabelAutoDelete] = False,
    FrontEndExecute @ ExportPacket[
        Notebook[{NotebookRead[EvaluationNotebook[]]}, ShowCellBracket->False],
        "PDF",
        "~/out.pdf"
    ],
    CurrentValue[$FrontEndSession, CellLabelAutoDelete] = Inherited
]

The ExportPacket approach allows you to directly insert Notebook options into the Notebook object.

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • Brilliant solution! and what if I want to disable the cell brackets? Changing "File > Printing Settings > Printing Options" doesn't disable them. – M.R. Apr 11 '17 at 23:35