# Automate PDF Page Checks on a Hosted Mac

Canonical: https://figment.so/blog/mac-pdf-page-automation

Run pdfinfo and pdffonts (from Homebrew's poppler) over each PDF, write a TSV report, and let launchd process the spool folder. The Intel Mac VM ($25 a month) is enough for file-based checks.

**Install poppler with Homebrew, run `pdfinfo` and `pdffonts` over each PDF, write the results to a TSV report, and let launchd process a spool folder as files arrive.** For file-based checks like these, Figment's Intel Mac VM ($25 a month) is enough.

If PDFs arrive from agencies, clients or automated exports, you need a repeatable check that each file meets your spec before print, a document system or a downstream pipeline. A hosted Mac keeps [PDFKit](https://developer.apple.com/documentation/pdfkit) and Homebrew's `pdfinfo` and `pdffonts` running without you managing hardware.

## What should each PDF check do?

Map your quality requirements to concrete checks before writing code. PDF validation is light on CPU: reading page counts, dimensions and font tables with `pdfinfo` and `pdffonts` typically takes well under a second per file. macOS ships `mdls` for Spotlight metadata, and Homebrew provides both tools in the poppler package.

| Check | Tool | Pass criterion | On fail |
|-------|------|----------------|---------|
| File is readable, not corrupted | `pdfinfo` exit code | Exit 0 | Reject; alert operator |
| Page count matches manifest | `pdfinfo` Pages field | Exact match to expected | Flag `PAGE_COUNT_MISMATCH` |
| No suspiciously small pages | `pdfinfo -f 1 -l N` Page size | Width and height at least 72 pt on every page | Flag `TINY_PAGE` |
| Page dimensions within spec | `pdfinfo` Page size | Within ±2 pt of target | Flag to review when a target size is known |
| All fonts embedded | `pdffonts` `emb` column | No `no` entries | Flag `UNEMBEDDED_FONTS` |
| File is not encrypted | `pdfinfo` Encrypted field | `no` | Log and skip |
| At least one page | `pdfinfo` Pages field | Pages at least 1 | Reject `EMPTY` |

Run this worksheet by hand on 20 representative files before automating anything. Unexpected dimension variance and unembedded subset fonts almost always show up on production samples, not synthetic test PDFs.

1. Pick five known-good PDFs and five known-bad PDFs from recent jobs. The bad set should include one truncated file, one encrypted file, one with a 10×10 pt thumbnail page, one with an unembedded Helvetica and one with the wrong page count.
2. Run `pdfinfo <file>` on each and record the `Pages`, `Encrypted` and `Page size` lines. For mixed page sizes, repeat with `pdfinfo -f 1 -l <N> <file>`, because the default `Page size` line reports only the first page.
3. Run `pdffonts <file>` on each and count rows where the `emb` column is `no`.
4. Fill in the worksheet by hand. Confirm every bad file flags the category you expected and every good file passes.
5. Wire the same logic into `pdf_check.sh` below, and re-run the ten files through it to confirm the output matches your hand answers.

## What does the check script need?

- Read access to the PDF drop folder (an SFTP upload you host, an S3 sync you install, or a mounted share).
- Write access to a results directory for the TSV reports.
- Homebrew with poppler: `brew install poppler`.
- No permission prompts: file-based PDF processing is not gated by Accessibility or Screen Recording.

`mdls -name kMDItemNumberOfPages` can return page counts, but only after Spotlight has indexed the file. When files are processed seconds after arrival, read the PDF directly with `pdfinfo`, which parses the file and does not depend on the index.

## How do I run the checks on a folder of PDFs?

Save this as `pdf_check.sh`. It is an educational example, not an executed benchmark. Run it against the worksheet samples first and adjust the thresholds to your spec.

```bash
#!/usr/bin/env bash
# pdf_check.sh — page count, dimensions, and font check for a directory of PDFs
# Usage: ./pdf_check.sh <input-dir> <results-dir> [expected-pages]
set -euo pipefail

INPUT_DIR="$1"
RESULTS_DIR="$2"
EXPECTED_PAGES="${3:-}"
mkdir -p "$RESULTS_DIR"
REPORT="${RESULTS_DIR}/report_$(date +%Y%m%d_%H%M%S)_$$.tsv"

printf 'file\tpages\twidth_pt\theight_pt\tunembedded_fonts\tencrypted\tstatus\n' \
  > "$REPORT"

check_pdf() {
    local pdf="$1"
    local name status="OK"
    name=$(basename "$pdf")

    local info
    if ! info=$(pdfinfo "$pdf" 2>&1); then
        printf '%s\t-\t-\t-\t-\t-\tPDFINFO_ERROR\n' "$name" >> "$REPORT"
        return 0
    fi

    local pages encrypted width_pt height_pt
    pages=$(printf '%s\n' "$info"     | awk '/^Pages:/{print $2; exit}')
    encrypted=$(printf '%s\n' "$info" | awk '/^Encrypted:/{print $2; exit}')
    # "Page size: 595.28 x 841.89 pts (A4)" — first-page dimensions only.
    width_pt=$(printf '%s\n' "$info"  | awk '/^Page size:/{print $3; exit}')
    height_pt=$(printf '%s\n' "$info" | awk '/^Page size:/{print $5; exit}')

    [[ "${pages:-0}" -eq 0 ]] && status="EMPTY"
    [[ "${encrypted:-no}" != "no" ]] && status="${status};ENCRYPTED"
    [[ -n "$EXPECTED_PAGES" && "${pages:-0}" != "$EXPECTED_PAGES" ]] \
        && status="${status};PAGE_COUNT_MISMATCH"

    local w_int h_int
    w_int=$(awk -v v="${width_pt:-0}"  'BEGIN{printf "%d", v}')
    h_int=$(awk -v v="${height_pt:-0}" 'BEGIN{printf "%d", v}')
    [[ "$w_int" -lt 72 || "$h_int" -lt 72 ]] && status="${status};TINY_PAGE"

    # pdffonts type can be 1-3 words ("TrueType", "Type 1", "CID Type 0C"),
    # so counting fields from the right is unreliable. Find the 'emb'
    # column's byte offset in the header, then read the same offset on
    # each data row.
    local unembedded
    unembedded=$(pdffonts "$pdf" 2>/dev/null | awk '
        NR==1 { c = index($0, "emb"); next }
        NR==2 { next }
        c && substr($0, c, 3) == "no " { n++ }
        END { print n+0 }
    ') || unembedded=0
    unembedded="${unembedded:-0}"
    [[ "$unembedded" -gt 0 ]] && status="${status};UNEMBEDDED_FONTS"

    status="${status#;}"

    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
        "$name" "${pages:-0}" "${width_pt:--}" "${height_pt:--}" \
        "$unembedded" "${encrypted:-unknown}" "$status" \
        >> "$REPORT"
}

find "$INPUT_DIR" -type f -name '*.pdf' -print0 \
  | while IFS= read -r -d '' pdf; do
        check_pdf "$pdf" || printf '%s\t-\t-\t-\t-\t-\tSCRIPT_ERROR\n' \
            "$(basename "$pdf")" >> "$REPORT"
    done

echo "Report written to $REPORT"
```

Make it executable and run it on the sample set:

```bash
chmod +x ~/scripts/pdf_check.sh
~/scripts/pdf_check.sh ~/pdf-samples ~/pdf-results 2
column -t -s $'\t' ~/pdf-results/report_*.tsv | head -20
```

The TSV opens in Numbers, imports into Airtable or feeds a Slack alert step. Each row is one file, and the `status` column carries semicolon-delimited failure codes you can search for:

```bash
grep 'UNEMBEDDED_FONTS' ~/pdf-results/report_*.tsv
```

If your PDFs may have mixed page sizes, replace the single `Page size` read with a loop that runs `pdfinfo -f N -l N` for each page index from 1 through `Pages`, and apply the tiny-page and spec checks to every page before writing the row.

## How do I process files as they arrive?

Use launchd's [`QueueDirectories`](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) key. Apple's documentation states that launchd keeps the job running while the listed directories are non-empty and stops it when they drain.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourdomain.pdf-check</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/agent/scripts/pdf_check.sh</string>
        <string>/Users/agent/pdf-spool</string>
        <string>/Users/agent/pdf-results</string>
    </array>
    <key>QueueDirectories</key>
    <array>
        <string>/Users/agent/pdf-spool</string>
    </array>
    <key>StandardOutPath</key>
    <string>/Users/agent/Library/Logs/pdf_check/out.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/agent/Library/Logs/pdf_check/err.log</string>
</dict>
</plist>
```

Save it as `~/Library/LaunchAgents/com.yourdomain.pdf-check.plist` and load it with `launchctl load ~/Library/LaunchAgents/com.yourdomain.pdf-check.plist`. There is no polling loop and no CPU use between batches.

## What if a check fails or the job stops?

- **`PDFINFO_ERROR`:** the file is corrupted or truncated. Move it to a `quarantine/` folder and alert. Do not retry blindly, because a truncated upload may still be in flight. Add a size-stable check (the same byte count across two reads 10 seconds apart) before processing.
- **Mid-batch crash:** keep the job idempotent by appending each successful filename to a `processed.txt` manifest, and skip names already listed with a `grep -qF` check on restart.
- **Encrypted files:** log and skip rather than crash the batch. If encrypted PDFs in the spool point to a producer-side error, route them to a separate alert.
- **Disk fill:** the VM disk also holds macOS, Homebrew and your tools, so only part of it is usable for spool and results. Sync finished reports off the Mac and move originals to a completed folder or your own storage after each batch.

## How do you size a Mac for your daily PDF volume?

These are planning estimates, not measured benchmarks. Run the script on 50 representative files from your production set and record the wall time before choosing a plan. `pdffonts` on a heavily fonted 100-page print file takes noticeably longer than a two-page invoice.

| Volume per day | Avg file size | Approx run time | Candidate plan |
|----------------|---------------|------------------|-----------------|
| 200 PDFs | 2 to 5 MB | under 5 min | Intel Mac VM, $25 a month |
| 1,000 PDFs | 2 to 5 MB | 15 to 25 min | Intel Mac VM, $25 a month |
| 1,000 PDFs | 50 MB | 45 to 90 min | Apple Silicon Mac VM, $39 a month |
| 5,000 PDFs | 20 MB | 2 to 4 hours | Apple Silicon Mac VM, or Dedicated M4 Pro ($349 a month) for several parallel batches |

The Intel VM has 4 shared vCPUs, 4GB of RAM and an 80GB SSD, and it runs macOS Sequoia. Move up when memory or parallel batches become the limit, or when the same Mac also builds with Xcode 26.4 or later or needs arm64-only tools. Plans are on [Figment Mac Hosting](/mac-hosting).

## How do I set this up on a new Mac?

1. Install poppler: `brew install poppler`.
2. Copy `pdf_check.sh` into `~/scripts/` over SSH, or clone it from your Git repository.
3. Create the spool and results directories: `mkdir ~/pdf-spool ~/pdf-results`.
4. Install and load the launchd plist above.
5. Drop a test PDF into `~/pdf-spool` and confirm a `report_*.tsv` lands in `~/pdf-results`.
6. Wire in your own alerting on non-zero exit, such as a Slack webhook from a wrapper script or your log aggregator.

**Related guides:**
- [Run a Mac API agent runtime](/blog/mac-api-agent-runtime)
- [Reboot recovery for Mac agents](/blog/mac-agent-reboot-recovery)
- [Self-hosted GitHub Actions runner on Mac](/blog/mac-github-actions-self-hosted-runner)
