2
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Brilliant solution! and what if I want to disable the cell brackets? Changing "File > Printing Settings > Printing Options" doesn't disable them. $\endgroup$ – M.R. Apr 11 '17 at 23:35

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.