All files can be found at deposit-functions repository.

After marking coursework, you usually need to flatten all PDF files so students can view your comments. Some program allow you to save the file flattened. The problem with it is that you need to do it one by one. It is troublesome to revisit the assignments again and save it again flattened, overwriting the second file you created in addition to the original. It is more economic to flatten them in batch.

There are some scripts out there written for bash, but that will likely not work on windows. I also wanted to improve my python a little, so I put together a script for python based on this solution on StackOverflow by benedikt.

Install prerequisites:

pip install pdftk
pip install glob
pip install fdfgen

You might need to install pdftk outside of python too. You will get an error message if you need to.

Here is the file: flatten.py

You will go to the directory in the command line and type: python flatten.py. It will create a directory called flatten and puts all flattened files there.

And below is how it looks inside:

from fdfgen import forge_fdf
from subprocess import Popen, PIPE
import glob
import os

filenames = glob.glob('*.pdf')

newpath = r'./flatten' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

fields = [("field1", "foo"),
          ("field2", "bar")]
fdf = forge_fdf("", fields, [], [], [])
for files in filenames:
    pdftk = ["pdf2ps", files, "-", "|", "ps2pdf", "-", "flatten/" + files] 
    proc = Popen(pdftk, stdin=PIPE)
    output = proc.communicate(input=fdf)
    print(files)
    if output[1]: 
        raise IOError(output[1])

EDITED: 2019/11/29

This was fun. The advantage of this approach is cross-compatibility. Until you have all the dependencies, it will work. But the file sizes are way too large and it takes a lot of time. For Unix-based system at least, there is a simpler solution. You can use Print to File in the command line to batch-process all files in a given directory.

First, you will need to make sure you have everything you need. Most system include cups, but you might need to install cups-pdf:

sudo apt install cups-pdf

Then you will need to automate it. Create a file with this code:

#!/bin/bash
# print all files to pdf in directory
# cups-pdf is required
# the default location is /home/user/PDF
# CC BY-SA 4.0
for file in *.pdf
do
    echo "$file"

lpr -P "PDF" $file

done
echo "Done."

Then you can run it in the command line by typing: bash file

It is possible, that your printer’s name is different. You can have a look at http://localhost:631. You can also add a PDF printer if you have none.