通过命令行将 Mathematica 转换为 PDF

Mar*_*ing 3 batch mathematica conversion mathematica-notebook

我在 Linux 上,想将一堆 Mathematica 8 Notebooks 转换为 PDF。

有什么方法可以在命令行上转换它们吗?我想为转换编写一个 makefile 规则,以便我可以批量转换其中的许多。

Sim*_*mon 6

基本上,不调用前端就无法将 Mathematica 笔记本转换为 PDF。要打印或转换它,您首先需要打开它,从Mathematica 命令行尝试打开笔记本会产生错误 FrontEndObject::notavail

In[1]:= NotebookOpen["file.nb"]

FrontEndObject::notavail: 
   A front end is not available; certain operations require a front end.
Run Code Online (Sandbox Code Playgroud)

这意味着您可以制作一个笔记本来进行转换,也可以从命令行调用前端。这是一个Mathematica 脚本形式的解决方案- 它可以轻松地转换为笔记本或包文件。

将以下代码另存为nb2pdf,使其可执行并将其放置在包含要转换的文件的目录或路径中的某个位置。

#!/usr/local/bin/MathematicaScript -script

(* Convert Mathematica notebooks to PDFs                              *)
(*   usage: nb2pdf file1.nb file2.nb etc...                           *)
(* outputs: file1.pdf file2.pdf etc...  into the current directoy     *)
(* If called with no filenames, this script                           *)
(*    will convert all notebook files in the current directory        *)

dir = Directory[];
files = {};
expandNb = False; (* Expand all cell groups in the Notebook *)

If[Length[$ScriptCommandLine] > 1, 
  Do[If[FileExistsQ[file], 
    AppendTo[files, file], 
    Print["File " <> file <> " does not exist"]],
    {file, Rest[$ScriptCommandLine]}],
  files = FileNames["*.nb"]];

With[{UFE = UsingFrontEnd},
 Do[nb = UFE@NotebookOpen[FileNameJoin[{dir, file}]];
  If[expandNb, UFE@SelectionMove[nb, All, Notebook]; 
               UFE@FrontEndExecute[FrontEndToken["SelectionOpenAllGroups"]]];
  UFE@NotebookPrint[nb, FileNameJoin[{dir, FileBaseName[file]<>".pdf"}]];
  UFE@NotebookClose[nb], {file, files}]]
Run Code Online (Sandbox Code Playgroud)