Closed karlhorky closed 1 year ago
A separate GitHub Actions workflow to do this using ghostscript
(generate an access token for this and add it as a GitHub repo secret called PDF_COMPRESSION_GITHUB_TOKEN
):
name: Compress PDFs
on:
pull_request:
# Run only when PDF files are added or changed
paths:
- '**.pdf'
jobs:
build:
# Only run on Pull Requests within the same repository, and not from forks.
if: github.event.pull_request.head.repo.full_name == github.repository
name: Compress PDFs
runs-on: ubuntu-latest
steps:
- name: Run apt update
run: sudo apt update
- name: Install Ghostscript for compression
run: sudo apt install -y ghostscript
- name: Checkout Repo
uses: actions/checkout@v3
with:
ref: ${{ github.head_ref }}
- name: Compress PDFs
run: |
find . -type f -iname '*.pdf' -not -path "./node_modules/*" | while read file; do
echo "Compressing $file"
# Compress the file for screen using Ghostscript
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile="./temp.pdf" "$file"
mv ./temp.pdf "$file"
done
- name: Commit files
run: |
git config user.email github-actions@github.com
git config user.name github-actions
# Discard modified compressed files that are not more
# than 10KB smaller than the previous version
git ls-files -z --modified '*.pdf' | while IFS= read -r -d '' file; do
old_size=$(git cat-file -s "HEAD:$file")
new_size=$(wc -c < "$file" | tr -d ' ')
if [[ $(($old_size - $new_size)) -lt 10000 ]]; then
echo "Discarding changes to $file, compressed file size $new_size is not >10KB smaller than old size $old_size"
git checkout -- "$file"
continue
fi
echo "Compressed $file from $old_size to $new_size bytes"
done
git add **/*.pdf
if [ -z "$(git status --porcelain)" ]; then
exit 0
fi
git commit -m "Compress PDFs"
git push origin HEAD:${{ github.head_ref }}
env:
GITHUB_TOKEN: ${{ secrets.PDF_COMPRESSION_GITHUB_TOKEN }}
Thanks for sharing this recipe @karlhorky.
We're not interested in adding PDF support to image-actions.
What problem would this feature solve?
Compress PDFs, which are often a lot larger than they need to be (recently converted a 10MB PDF to ~1MB)
Describe the solution you’d like to see
Support for PDF files
Are you willing to work on implementing this solution?
No
Describe alternatives you’ve considered
Additional context
No response
Code of Conduct