convert-pdf.sh 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. # dependency: poppler-utils
  4. display_help(){
  5. echo "Usage: ${0##*/} [operation] [file(s)]"
  6. echo "Operations:"
  7. echo -e "\t img, image\tConvert PDF to image"
  8. echo -e "\t txt, text\tConvert PDF to text file"
  9. echo -e "\t compress\tCompress PDF"
  10. echo -e "\t merge\t\tMerge multiple PDFs"
  11. exit 2
  12. }
  13. [[ $# -lt 2 ]] && display_help
  14. pdf2text(){
  15. pdftotext -nopgbrk "$1"
  16. }
  17. pdf2img(){
  18. pdftoppm "-${1}" "$1" "${1%.pdf}"
  19. }
  20. pdf_compress(){
  21. output="${1%.pdf}_compressed.pdf"
  22. # images are awful with /screen
  23. # gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH "-sOutputFile=${output}" "$1"
  24. gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH "-sOutputFile=${output}" "$1"
  25. }
  26. pdfs_merge(){
  27. output="${1//.pdf/}.pdf"
  28. gs -dNOPAUSE -sDEVICE=pdfwrite "-sOUTPUTFILE=${output// /-}" -dBATCH "${@:2}"
  29. }
  30. opt="$1"
  31. files="${@:2}"
  32. case "${opt,,}" in
  33. img|image) pdf2img "$files";;
  34. txt|text) pdf2text "$files";;
  35. compress) pdf_compress "$files";;
  36. merge) pdfs_merge "$files";;
  37. h|\?|:|*) display_help ;;
  38. esac