Last active
February 5, 2017 11:00
-
-
Save JohnStarich/662a947a08eef08a66da539d18455fd3 to your computer and use it in GitHub Desktop.
Convert and concatenate all arguments into a single PDF (Mac only for the moment)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
function usage() { | |
echo "Usage: $(basename $0) FILE [FILE [FILE ...]]" >&2 | |
} | |
# Validate args | |
if [[ -z "$@" ]]; then | |
echo 'Please provide files to convert and join into a PDF' >&2 | |
usage | |
exit 2 | |
fi | |
FILES=( "$@" ) | |
for file in "${FILES[@]}"; do | |
if [[ ! -f "$file" ]]; then | |
echo "Could not find file named: $file" >&2 | |
err=1 | |
fi | |
done | |
if [[ $err == 1 ]]; then | |
exit 2 | |
fi | |
# Set up environment | |
WORKING_DIR=$(mktemp -d) | |
if [[ -z "$WORKING_DIR" || ! -d "$WORKING_DIR" ]]; then | |
echo 'Error creating temporary working directory.' >&2 | |
exit 1 | |
fi | |
SOFFICE_PATH=/Applications/LibreOffice.app/Contents/MacOS/soffice | |
PDF_COMBINER_PATH=/System/Library/Automator/Combine\ PDF\ Pages.action/Contents/Resources/join.py | |
FILES_TO_CONVERT=() | |
PDF_FILES=() | |
for file in "${FILES[@]}"; do | |
if [[ "$file" =~ \.pdf$ ]]; then | |
PDF_FILES+=("$file") | |
else | |
PDF_FILES+=("$(echo "$file" | sed -e 's@\.[^\.]*[email protected]@' -e "s@^@$WORKING_DIR/@")") | |
FILES_TO_CONVERT+=("$(basename "$file")") | |
fi | |
done | |
# Convert non-PDF files | |
if [[ ! -z "${FILES_TO_CONVERT[@]}" ]] && which "$SOFFICE_PATH" > /dev/null; then | |
"$SOFFICE_PATH" \ | |
--convert-to pdf \ | |
-env:UserInstallation="file://$WORKING_DIR" \ | |
--outdir "$WORKING_DIR" \ | |
"${FILES_TO_CONVERT[@]}" | |
else | |
echo 'ERROR: Could not convert input files. Is LibreOffice installed in /Applications/?' >&2 | |
exit 1 | |
fi | |
# Combine PDFs | |
if ! which "$PDF_COMBINER_PATH" > /dev/null; then | |
echo "Could not join PDFs. You can find the (potentially converted) PDFs here: $WORKING_DIR" >&2 | |
else | |
"$PDF_COMBINER_PATH" \ | |
--output /tmp/output.pdf \ | |
"${PDF_FILES[@]}" | |
rm -rf "$WORKING_DIR" | |
open /tmp/output.pdf | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment