透過命令列將 Mathematica 轉換為 PDF

透過命令列將 Mathematica 轉換為 PDF

我使用的是 Linux,想將一堆 Mathematica 8 Notebooks 轉換成 PDF。

有什麼方法可以在命令列上轉換它們嗎?我想為轉換編寫一個makefile規則,這樣我就可以批次轉換其中的許多檔案。

答案1

基本上,如果不呼叫前端,就無法將 Mathematica 筆記本轉換為 PDF。要列印或轉換它,您首先需要打開它,並天真地嘗試從數學命令列產生錯誤 FrontEndObject::不可用

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

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

這意味著您可以建立一個筆記本來進行轉換或從命令列呼叫前端。這是一個形式的解決方案數學腳本- 它可以輕鬆地變成筆記本或包文件。

將下列程式碼另存為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

相關內容