summaryrefslogtreecommitdiff
path: root/open-as-pdf
blob: 99e5e22bfce9bc089cc852fe09177a41bbc4c262 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env bash

set -euo pipefail

# @describe Convert document files to PDF and open them.
# @arg files+ Input document files (e.g., .docx, .xlsx, .pptx) to convert and view as PDF
# @flag -n --no-cache Prevent caching of converted PDFs
# @meta require-tools sha512sum,soffice,xdg-open
# @env OPEN_AS_PDF_CACHE_DIR Cache directory (default: $XDG_CACHE_HOME/open-as-pdf)

_open_as_pdf() {
  if [ -n "${argc_no_cache:-}" ]; then
    OUTPUT_DIR=$(mktemp --directory)
    trap 'rm -rf "$OUTPUT_DIR"' EXIT

    soffice --convert-to pdf --outdir "$OUTPUT_DIR" "$1"
    xdg-open "$OUTPUT_DIR"/*.pdf && sleep 5
  else
    local file_hash file_cach_dir
    file_hash=$(sha512sum "$1" | cut -d' ' -f 1)
    file_cach_dir="${OPEN_AS_PDF_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/open-as-pdf}/$file_hash"

    if [ ! -d "$file_cach_dir" ]; then
      OUTPUT_DIR=$(mktemp --directory)
      trap 'rm -rf "$OUTPUT_DIR"' EXIT

      soffice --convert-to pdf --outdir "$OUTPUT_DIR" "$1"

      mkdir -p "$file_cach_dir"
      mv "$OUTPUT_DIR"/*.pdf "$file_cach_dir"
    fi

    xdg-open "$file_cach_dir"/*.pdf
  fi
}

main() {
  for file in "${argc_files[@]?}"; do
    _open_as_pdf "$file"
  done
}

eval "$(argc --argc-eval "$0" "$@")"