Handy script to work with PDF files

PDF is commonly used printing file format. Creating & organising it might be a bit hard if without Acrobat Pro’s help.

Today I discovered some open source lib to manipulate PDF files, including Creating, Splitting, Merging, and Re-Ordering PDF pages.

Below is the script line for creating PDF,

echo 'Hello World!' | enscript -B -o - | ps2pdf - content.pdf

-B for enscript omit the header for the output


Here is the script for re-ordering the raw PDF into a book-style printable version.

#!/bin/bash

if [ $# -ne 2 ] ; then
    echo "Invalid input supplied, please choose input PDF and page counts"
    echo "    example : ./format.sh <input.pdf> <pageCount>"
    exit 1
fi

echo "Formatting begins ... "
file="$1"
pageCount="$2"

let "blankPageCount = $pageCount % 4"

# Check if blank page padding needed, if so create one
if [ $blankPageCount -ne 0 ] ; then
    echo ' ' | ps2pdf - blank.pdf 
fi

# setup each fold loop - one fold means one print page
let "foldCount = $pageCount / 4"
startFold=0
pageOrganizor=''

echo "    total $foldCount printing slides generated";
echo "    with $blankPageCount blank pages";

while [ $startFold -lt $foldCount ] ; do
    let "coverPrintpage = $startFold * 4 + 4"
    let "leftPrintpage = $startFold * 4 + 1"
    let "backPrintpage = $startFold * 4 + 3"
    pageOrganizor="$pageOrganizor A$coverPrintpage A$leftPrintpage-$backPrintpage"
    let "startFold += 1"
done

if [ $blankPageCount -eq 0 ] ; then
    cmd="pdftk A=$file cat$pageOrganizor output fmt_output.pdf"
elif [ $blankPageCount -eq 3 ] ; then
    let "blankStartPage = $pageCount-2"
    cmd="pdftk A=$file B=blank.pdf cat$pageOrganizor B A$blankStartPage-$pageCount output fmt_output.pdf"
elif [ $blankPageCount -eq 2 ] ; then
    let "blankStartPage = $pageCount-1"
    cmd="pdftk A=$file B=blank.pdf cat$pageOrganizor B A$blankStartPage A$pageCount B output fmt_output.pdf"
else
    cmd="pdftk A=$file B=blank.pdf cat$pageOrganizor B A$pageCount B B output fmt_output.pdf"
fi

echo "Merging pdfs ... "
$cmd

# cleanning up
echo "Cleanup and done"
if [ -e "blank.pdf" ] ; then
    rm blank.pdf
fi