Skip to content

Instantly share code, notes, and snippets.

@aranair
Created December 10, 2018 15:05
Show Gist options
  • Save aranair/ea4a911f3d8550d7688de93a56bdde29 to your computer and use it in GitHub Desktop.
Save aranair/ea4a911f3d8550d7688de93a56bdde29 to your computer and use it in GitHub Desktop.
LibreOffice to convert Word .doc/x files to PDF
#!/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
# https://discussions.apple.com/thread/7848497
#
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)
dir=`dirname "${file}"`
${CMD} ${ARGS} "${file}" --outdir "${dir}" >& /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
@aranair
Copy link
Author

aranair commented Dec 10, 2018

To combine the pdfs into 1 single pdf:

cd /usr/local/bin
sudo ln -s "/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py" PDFconcat

Then run it
PDFconcat -o merged.pdf first.pdf *.pdf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment