首页 > 解决方案 > 如何使用 Julia 生成 PDF 文档

问题描述

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

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

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

如果有更好的方法在 Julia 中以编程方式生成多个人类可读的报告,我并没有决心输出 PDF。

标签: julia

解决方案


至于现在我们可以从基础开始,输出一个HTML文件,这样更快。您可以使用模板库,在这种情况下我们可以使用 mustache。该模板是硬编码的,但很容易将其包含在外部文件中。

记得安装模板库Mustache

import Pkg; Pkg.add("Mustache")

基本思想如下:

  • 有一个包含数据的字典列表
  • 有一个报告模板,其中要替换的部分在{{ ... }}警卫中
  • 通过迭代将单个学生的报告保存在文件 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

单个学生的结果类似于:

<html>
<body>
Hello <b>Elisa, White</b>. Your mark is 100
</body>
</html>

如果您更喜欢 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

结果如下:

在此处输入图像描述

对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

这导致:

在此处输入图像描述


推荐阅读