コマンドライン経由でMathematicaをPDFに変換する

コマンドライン経由でMathematicaをPDFに変換する

私は Linux を使っており、多数の Mathematica 8 ノートブックを PDF に変換したいと考えています。

コマンドラインで変換する方法はありますか? 多数のファイルを一括変換できるように、変換用の makefile ルールを記述したいと思います。

答え1

基本的に、フロントエンドを起動せずにMathematicaノートブックをPDFに変換する方法はありません。印刷または変換するには、まずそれを開いて、Mathematica コマンドラインエラーが発生する FrontEndObject::利用不可

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

FrontEndObject::notavail: 
   A front end is not available; certain operations require a front end.

つまり、変換を行うためのノートブックを作成するか、コマンドラインからフロントエンドを呼び出すことができます。ここでは、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}]]

答え2

Mathematica 13 で動作するもの: https://knanagnostopoulos.blogspot.com/2023/01/convert-many-mathematica-notebooks-to.html

nb2pdf (){ for f in $@;do echo -n "Converting $f to pdf ... "; wolframscript -code nb=\"$f\"';FileConvert[nb, "PDF"];' ;done; } 

nb2pdf *.nb

関連情報