如何使用Julia生成PDF文档

Ste*_*isz 5 julia

我想使用这样的循环生成学生反馈报告:

for student in studentList
    # Report/feedback content goes here:

    # Here I want to use text with variables for example
    student * " received " * xPoints

    "Q1"
    "Good effort but missing units"

    "Q2"
    "More text ..."

    # end of the feedback
end
Run Code Online (Sandbox Code Playgroud)

我的目标是为所有学生生成30多个PDF文件,每个问题的分数,并为每个学生补充一些免费文本.我想到的一种方法是写入多个TeX文件并在最后将它们编译为PDF.

如果有一种更好的方法可以在Julia中以编程方式生成多个人类可读的报告,我并不打算输出PDF.

Mat*_*gni 5

至于现在,我们可以从基础开始并输出一个更快的HTML文件.你可以使用模板库,在这种情况下我们可以使用小胡子.模板是硬编码的,但将其包含在外部文件中很简单.

请记住安装模板库Mustache:

import Pkg; Pkg.add("Mustache")
Run Code Online (Sandbox Code Playgroud)

基本思路如下:

  • 有一个包含数据的词典列表
  • 有一个报告的模板,其中要替换的部分是{{ ... }}守卫
  • 通过迭代将单个学生的报告保存在文件html中.

您可以添加一些代码直接向学生发送邮件,甚至不保存文件,如果您的计算机配置为这样做(只要您不包含外部CSS,邮件将根据HTML说明格式化) .

using Mustache

students = [
  Dict( "name" => "John", "surname" => "Smith", "mark" => 30 ),
  Dict( "name" => "Elisa", "surname" => "White", "mark" => 100 )
]

tmpl = mt"""
<html>
<body>
Hello <b>{{name}}, {{surname}}</b>. Your mark is {{mark}}
</body>
</html>
"""

for student in students
  rendered = render(tmpl, student)
  filename = string("/tmp/", student["name"], "_", student["surname"], ".html")
  open(filename, "w") do file
    write(file, rendered)
  end
end
Run Code Online (Sandbox Code Playgroud)

单个学生的结果如下:

<html>
<body>
Hello <b>Elisa, White</b>. Your mark is 100
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢PDF,我认为更快的方法是将一块LaTeX作为模板(代替HTML模板),将Mustache的结果导出到文件中,然后通过系统调用从脚本中编译它:

using Mustache

students = [
  Dict( "name" => "John", "surname" => "Smith", "mark" => 30 ),
  Dict( "name" => "Elisa", "surname" => "White", "mark" => 100 )
]

tmpl = mt"""
\documentclass{standalone}

\begin{document}

Hello \textbf{ {{name}}, {{surname}}}. Your mark is ${{mark}}$.

\end{document}
"""

for student in students
  rendered = render(tmpl, student)
  filename = string("/tmp/", student["name"], "_", student["surname"], ".tex")
  open(filename, "w") do file
    write(file, rendered)
  end
  run(`pdflatex $filename`)
end
Run Code Online (Sandbox Code Playgroud)

这导致类似于:

在此输入图像描述

Mustache.jl的引用,您可以在其中找到有关如何使用单行模板迭代不同问题的一些说明.这是一个标记是值数组的示例(同样适用于tex):

using Mustache

students = [
  Dict( "name" => "John", "surname" => "Smith", "marks" => [25, 32, 40, 38] ),
  Dict( "name" => "Elisa", "surname" => "White", "marks" => [40, 40, 36, 35] )
]

tmpl = """
\\documentclass{article}

\\begin{document}

Hello \\textbf{ {{name}}, {{surname}} }. Your marks are: 
\\begin{itemize}
  {{#marks}} 
    \\item Mark for question is {{.}} 
  {{/marks}}
\\end{itemize}
\\end{document}
"""

for student in students
  rendered = render(tmpl, student)
  filename = string("/tmp/", student["name"], "_", student["surname"], ".tex")
  open(filename, "w") do file
    write(file, rendered)
  end
  run(`pdflatex $filename`)
end
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述