![通过命令行将 Mathematica 转换为 PDF](https://linux22.com/image/1302547/%E9%80%9A%E8%BF%87%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%B0%86%20Mathematica%20%E8%BD%AC%E6%8D%A2%E4%B8%BA%20PDF.png)
我在 Linux 上,想要将一堆 Mathematica 8 Notebooks 转换为 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