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.