Christoph Polcin

My PDF attach_files script

pdftk is a awesome toolkit to modify PDF files. The shell script below converts a input file to a PDF file with the help of Open- or Li­bre­Of­fice and attaches the source to the end of the output file. It does an additional convertion if the input file is a docx, rft or txt file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/sh
# http://christoph-polcin.com/

TMP=/tmp

[ $# -lt 1 ] && \
    echo "usage: $(basename $0) input_file [output.pdf]" && \
    exit 1

[ ! -f "$1" ] && \
    echo "input file not found: $1" && \
    exit 1

IN=$1
NAME=$(echo -n "$IN" | sed 's/\.[^\.]*$//')

if [ $# -gt 1 ]; then
    OUT=$2
else
    OUT=./${NAME}.pdf
fi

[ -e "$OUT" ] && \
    echo "output already exists: $OUT" && \
    exit 1

if which libreoffice >/dev/null; then
    CONVERTER=libreoffice
else
    CONVERTER=openoffice
fi

EXT=$(echo -n "$IN" | sed 's/^.*\.//;s/.*/\L&/')
case "$EXT" in
    pdf)
        echo "inputfile is already a pdf: $IN"
        exit 1
        ;;
    docx|rtf|txt)
        $CONVERTER --convert-to odt --headless --outdir ${TMP} "$IN"
        IN=${TMP}/${NAME}.odt
        ;;
    *)
        ;;
esac;

$CONVERTER --convert-to pdf --headless --outdir ${TMP} "$IN"

pdftk "${TMP}/${NAME}.pdf" \
    attach_files "$IN" topage end \
    output "$OUT"

rm -f "${TMP}/${NAME}.pdf"

echo output: ${OUT}