Skip to content

Instantly share code, notes, and snippets.

@nunomcruz
Created February 4, 2020 10:15
Show Gist options
  • Save nunomcruz/98c7036394934b0e8d6e75e27025bbab to your computer and use it in GitHub Desktop.
Save nunomcruz/98c7036394934b0e8d6e75e27025bbab to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Use LibreOffice to convert Word .doc/x files to PDF in the current,
# or relative directory location, unless --outdir option used (see below).
# Tested: macOS Sierra 10.12.3
# Version: 1.2
# VikingOSX, 2017-02-02, Apple Support Communities
#
Usage () {
printf "%s\n" "Usage"
printf "%s\n" "Process every Word .doc/x document in current folder"
printf "%s\n" "./docx2pdf.sh *.doc*"
printf "\n"
printf "%s\n" "Process selected Word documents in current folder"
printf "%s\n" "./docx2pdf.sh foo.doc bar.docx baz.doc"
exit 1
}
No_app () {
printf "%s\n" "Please install latest LibreOffice -- process terminating..."
printf "%s\n" "https://www.libreoffice.org"
exit 1
}
Report_success () {
status=$1
thefile=$2
[[ $status -eq 0 ]] || printf "%s\n" "Error: failed to process $thefile."
let filecount++
printf "%s\n" "${2/.doc*/.pdf}"
}
filecount=0
CMD="/Applications/LibreOffice.app/Contents/MacOS/soffice"
# Is LibreOffice installed? See man test.
[[ -x ${CMD} ]] || No_app
# Filenames provided to script on command-line?
[[ -n "$@" ]] || Usage
# can also direct output location with --outdir [directory name]
# PDF_Folder="~/Desktop/PDF"
# ARGS='--headless --convert-to pdf:writer_pdf_Export --outdir "${PDF_Folder}"
ARGS='--headless --convert-to pdf'
# enable Regular Expressions
shopt -s extglob
for file in "$@"
do
# ignore empty files
[[ -s "${file}" ]] || continue
case "${file}" in
# allow only these extensions. More are supported.
*.+(doc|docx|rtf|odt|wpd|cwk|txt) )
# convert to PDF (quietly)
${CMD} ${ARGS} "${file}" >& /dev/null
# if no errors, output created PDF name
Report_success $? "${file}"
continue
;;
* )
printf "%s\n" ">>> Skipping invalid file: ${file}"
continue
;;
esac
done
# disable Regular Expressions
shopt -u extglob
[[ $filecount -ge 1 ]] && printf "\n%s\n" "Files processed: $filecount files"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment