work-work.work-logo: A man with brains and a shovel

work-work.work

A blog about goals and obstacles, motivation and procrastination, life's random events and getting things done.

Magic folder to separate pdf pages

Splitting a pdf file into separate pdf files for each page is just a simple command in the linux command line.

$ pdfseparate inputfile.pdf page-%d.pdf

You might need to install pdf-poppler first

$ apt install pdf-poppler

If you have Windows user in your network who regularly need to do this, you can create a folder that automagically takes the pdf files that you save there. The Windows clients can access the folder as a samba share or webdav.

You need two files:

/usr/local/bin/pdfseparate.sh

#!/bin/bash

suffix="${1##*.}"
base=$(basename $1 ".$suffix")
watchpath="/var/files/pdfseparate"

# Abort if not a pdf
if [ "${suffix^^}" != "PDF" ]; then
    echo "$1 ist keine PDF-Datei."
    exit
fi

# wait for the file write to complete
/usr/bin/lsof -- "$watchpath/$1" > /dev/null
while [[ $(/usr/bin/lsof -- "$watchpath/$1") ]]
do
    # File is still being written
    sleep 0.1
done

# separate the pages and delete the original
/usr/bin/pdfseparate "$watchpath/$1" "$watchpath/separated/${base}-page-%d.pdf" && rm "$watchpath/$1"

And you create a systemd service

/lib/systemd/system/inotify-pdfseparate.service

[Unit]
Description=pdfseparate takes pdf files in die in f:/pdfzerteilen abgelegt werden
Wants=network-online.target
After=network-online.target

[Service]
User=filedrop
Type=simple
ExecStart=/usr/bin/inotifywait -q -m -e create --exclude ._ --format %f /var/files/pdfseparate | xargs -I{} /usr/local/bin/pdfseparate.sh {};
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target

I have a user named filedrop, you might want to use a different user name to execute the commant.

The above mentioned service uses inotify-tools. Inotifywait will wait patiently wait for a file to appear in that folder (-e create), it will ignore those annoying macOS (--exclude ._), and keep doing this (-m).

Install inotify-tools:

$ apt install inotify-tools

And then active the service and start it

$ systemctrl enable inotify-pdfseparate.service

To the user, Any file that you place into the magic folder will disappear and the resulting separated pages will appear in the subfolder separated.

You can use this technique to do a lot of other stuff to files, add stationary to pdf letters, turn them to black and white, compress images, etc.