# How do I automatically fill LaTeX templates with from a table of data?

I have a LaTeX template like

\documentclass[12pt]{article}
\begin{document}
Hello, \VAR{USER}!
\end{document}


and a table of users (for example as a csv) like

ID,USER
01,Peter
02,Michael
03,Jana
...


How can I generate pdf files hello_01.pdf, hello_02.pdf, hello_03.pdf, ... with the content being the latex document filled with the usernames? So hello_01.pdf just contains "Hello, Peter!".

Is there some application that automatically fills and compiles the pdf files for me or do I have to write something from scratch, and how would I begin doing that?

• One latex run generates one PDF file. So you need a script to run latex multiple times. Or generate multiple pages and then use a PDF splitter program to split it into multiple PDF files. May 7 at 11:22
• I don't care about the runtime of such a script, as long as I don't need to do it manually so running latex multiple times is okay. But how do I generate the latex files initially? May 7 at 11:26
• I would use what ever programming language you are comfortable with to read the csv, and generate the many latex files. Then a tool like latexmk -pdf *.tex can run latex on all the generated .tex files and convert them to PDF. I think it would be overkill til attempt to solve this purely from latex it selv. May 7 at 11:37

Here is a Python script to do it. It just replaces the \VAR{USER} text with the USER field from the row, and writes it to a file hello_ID.tex and then processes that file with latexmk. Run with the command python process.py, or if you are on Windows, probably py process.py.

Of course it could be generalised to use more variables, for example using some string-template library, but I wanted to keep it simple.

File: template.tex

\documentclass[12pt]{article}
\begin{document}
Hello, \VAR{USER}!
\end{document}


File: input.csv

ID,USER
01,Peter
02,Michael
03,Jana


File: process.py

import csv
import subprocess

def generate_file(template, id, user):
filename = f'hello_{id}.tex'
with open(filename, 'w') as latex_file:
latex = template.replace(r'\VAR{USER}', user)
latex_file.write(latex)
print(f'Generated {filename}')
subprocess.call(['latexmk', '-pdf', filename])

with open('template.tex') as template_file:
global latex_code
print (latex_code)

with open('input.csv') as csv_file: