Skip to content

Instantly share code, notes, and snippets.

@DocumentAlchemy
Created April 23, 2016 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DocumentAlchemy/3e2201700d131a5b021fab15ba6d80ea to your computer and use it in GitHub Desktop.
Save DocumentAlchemy/3e2201700d131a5b021fab15ba6d80ea to your computer and use it in GitHub Desktop.
Add a cover page to one or more PDF documents using curl and https://documentalchemy.com/
#!/bin/bash
# Adds a cover page to one or more PDF documents.
# USAGE: add-cover.sh <COVER-PAGE> <FILES>
#
# EXAMPLE: add-cover.sh cover.pdf doc/*.pdf
# This is your DocumentAlchemy API key. It may be set via the
# environment variable named `DA_API_KEY`.
# (See <https://documentalchemy.com/> to get one of your own.)
API_KEY=${DA_API_KEY:-"403l1zh3dkbakyb9"}
# This is a flag that can prevent this script from `echo`ing
# unnecessary information. It can be set via the environment
# variable `QUIET`. A clever person could make this into a
# command line parameter like `-q`.
QUIET=${QUIET:-FALSE}
# Note that you can set environment variables on a per-invocation
# basis by prefixing NAME=VALUE before the command. For example:
# API_KEY=my-key QUIET=true doc2docx *.doc
# EXIT_CODE tracks the number of files we couldn't extract from.
EXIT_CODE=0
# The first argument contains the cover page.
COVER_PAGE=$1
# The rest will be filenames, so "shift" the first argument away and process the rest.
shift;
# Loop over the command line parameters....
for pdf in "$@"; do
# ...testing that is is an accessible file...
if ! [ -s "$pdf" ]; then
$QUIET || echo "WARNING: File '$pdf' was not found and will be ignored."
EXIT_CODE=$((EXIT_CODE+1))
else
# ...if so, POST to DocumentAlchemy to join the documents
outfile="`dirname "$pdf"`/covered-`basename "$pdf"`"
$QUIET || echo "Adding cover page '$COVER_PAGE' to '$pdf'...";
response=$(curl --silent \
--write-out %{http_code} -H "Authorization: da.key=$API_KEY" \
-X POST \
-F "document=@$COVER_PAGE" \
-F "document=@$pdf" \
https://documentalchemy.com/api/v1/documents/-/rendition/combined.pdf \
-o "$outfile")
# ...and report success or failure.
if ! [ "$response" -eq "200" ]; then
$QUIET || echo "WARNING: Expected a 200 response for file '$pdf', found $response instead.";
EXIT_CODE=$((EXIT_CODE+1))
else
$QUIET || echo "...OK. File '$outfile' created."
fi
fi
done
# Exit with the number of documents that could not be joined.
exit $EXIT_CODE
@DocumentAlchemy
Copy link
Author

DocumentAlchemy commented Apr 23, 2016

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