010s01 pdftk – SCRIPT per inserire numeri di pagina in un documento PDF

13 Ottobre, 2022 (19:29) | Linux, pdftk | By: sargonsei

#!/bin/bash
# 010s01 pdftk – SCRIPT per inserire numeri di pagina in un documento PDF
#
# Per soddisfare le dipendenze:
# sudo apt install pdftk texlive-latex-extra texlive-latex-base
#
# Per avviare questo script, aprire un trminale nella medesima cartella in cui si trova il documento PDF da numerare
# ed impartire il comando:
# ./< nomeDelloScript.sh > < inputpdf > < outputpdf >
#

if ! which pdflatex > /dev/null; then
echo "Dependencies not met: pdflatex not found"
fi

if ! which pdftk > /dev/null; then
echo "Dependencies not met: pdftk not found"
fi

INPUT_PDF=${1}
OUTPUT_PDF=${2}

if ! [ -f $INPUT_PDF ]; then
echo "File '${INPUT_PDF}' does not exist."
exit -1
fi

TMP_PAGES_TEX='tmp_page_numbers.tex'
TMP_PAGES_PDF='tmp_page_numbers.pdf'
TMP_PAGES_AUX='tmp_page_numbers.aux'
TMP_PAGES_LOG='tmp_page_numbers.log'

echo "Numerazione input file: $INPUT_PDF"

NUM_PAGES=`pdftk $INPUT_PDF dump_data | grep NumberOfPages | cut -f 2 -d ' '`
echo "Page numbers in original PDF: $NUM_PAGES"

# Feel free to edit the file here:
echo "Creating latex file with just page numbers in it..."
(
# Edit the "a4paper" string if you wish:
printf '\\documentclass[12pt, a4paper]{article}\n'
printf '\\usepackage{lastpage}\n'
printf '\\usepackage{fancyhdr}\n'
printf '\\pagestyle{fancy}\n'
printf '\\fancyhf{}\n'
printf '\\renewcommand{\\headrulewidth}{0pt}\n'
printf '\\usepackage{multido}\n'
printf '\\usepackage[a4paper, hmargin=4.0cm,vmargin=1.0cm,nohead,nofoot]{geometry}\n'
# Per cambiare posizione e/o formattazione del numero delle pagine, modificare le linee sovrastanti
printf '\\cfoot{Page \\thepage\\ of \\pageref{LastPage}}\n'
printf '\\begin{document}\n'
printf '\\multido{}{'
printf "$NUM_PAGES"
printf '}{\\phantom{x}\\newpage}\n'
printf '\\end{document}\n'
) > $TMP_PAGES_TEX

# Run pdflatex TWICE; once isn't enough to make pg numbering perfect
pdflatex -interaction=batchmode $TMP_PAGES_TEX 1> /dev/null
pdflatex -interaction=batchmode $TMP_PAGES_TEX 1> /dev/null

# Now join the original and numbered PDFs together
pdftk $INPUT_PDF multistamp $TMP_PAGES_PDF output $OUTPUT_PDF

# And clean up the temp files
rm -f $TMP_PAGES_PDF $TMP_PAGES_TEX $TMP_PAGES_AUX $TMP_PAGES_LOG