Your billing system exports the day's invoices to a folder. If a customer needs scanned copies, you can add one command after that export. The Python script below sends each PDF to the Look Scanned API with the same grayscale settings, saves the copy under its original filename and logs any file it couldn't finish.
Bulk Scan or API Scan?
| If you need to… | Use |
|---|---|
| Convert a batch once, preview the results and keep the source files on your device | Bulk Scan runs in your browser and also takes images and Office files. |
| Convert a folder of PDFs every night or as part of an existing export | API Scan uploads the PDFs for server-side processing. Your script collects the results. |
If you're sending a single invoice by hand, use the single-invoice walkthrough.
Get a token and try one invoice
Sign in to API Scan with a Pro account and copy your API token. The page has a Try it out section if you want to check the effect on a sample PDF before setting up Python.
With Python 3.11 or later, install Requests in a virtual environment and set LOOKSCANNED_API_TOKEN in your shell or job runner. The commands below use Bash or Zsh. The token prompt keeps the value out of your shell history.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install requests
printf 'Look Scanned API token: '
read -rs LOOKSCANNED_API_TOKEN
printf '\n'
export LOOKSCANNED_API_TOKEN
Create an invoices folder beside the script and put one sample PDF in it. The settings below use grayscale at 150 DPI and a slight tilt. For invoices with colored stamps or highlighted totals, change gray to sRGB. Check the smallest print and any barcodes in the first PDF before running the whole batch.
Batch convert PDFs with Python
Download scan_invoices.py or copy the script below. For each PDF, it creates a job, uploads the original, polls for completion and saves the finished copy. The API calls use your token. The upload and download use signed URLs.
import argparse
import json
import os
import sys
import time
from pathlib import Path
from tempfile import NamedTemporaryFile
import requests
JOBS = "https://api.lookscanned.io/v1/scan-jobs"
SCAN_CONFIG = {"colorspace": "gray", "resolution": 150, "rotate": 0.5}
POLL_SECONDS = 2
POLL_LIMIT_SECONDS = 180
def wait_for_download(session, job_id, auth):
deadline = time.monotonic() + POLL_LIMIT_SECONDS
while (remaining := deadline - time.monotonic()) > 0:
response = session.get(f"{JOBS}/{job_id}", headers=auth, timeout=min(30, remaining))
response.raise_for_status()
job = response.json()
status = job["status"]
if status == "completed":
return job["downloadURL"]
if status not in {"created", "processing"}:
raise RuntimeError(f"Scan job ended with status {status}")
time.sleep(min(POLL_SECONDS, max(0, deadline - time.monotonic())))
raise RuntimeError("Timed out waiting for the scan job")
def save_pdf(session, download_url, destination):
with session.get(download_url, stream=True, timeout=60) as response:
response.raise_for_status()
file = NamedTemporaryFile(dir=destination.parent, suffix=".part", delete=False)
temporary = Path(file.name)
try:
with file:
for chunk in response.iter_content(chunk_size=128 * 1024):
file.write(chunk)
temporary.replace(destination)
finally:
temporary.unlink(missing_ok=True)
def main():
parser = argparse.ArgumentParser(description="Make scanned copies of a folder of PDFs.")
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
token = os.environ.get("LOOKSCANNED_API_TOKEN")
if not token:
parser.error("Set LOOKSCANNED_API_TOKEN before running the script.")
if not args.source.is_dir() or args.source.resolve() == args.output.resolve():
parser.error("Choose an existing source directory and a separate output directory.")
args.output.mkdir(parents=True, exist_ok=True)
auth = {"Authorization": f"Bearer {token}"}
converted = skipped = failed = 0
with requests.Session() as session:
for source in sorted(args.source.iterdir()):
if not source.is_file() or source.suffix.lower() != ".pdf":
continue
destination = args.output / source.name
if destination.is_file():
skipped += 1
continue
job_id = None
stage = "create"
try:
response = session.post(
JOBS, json={"config": SCAN_CONFIG}, headers=auth, timeout=30
)
response.raise_for_status()
job = response.json()
job_id = job["jobID"]
stage = "upload"
with source.open("rb") as pdf:
upload_headers = {
"Content-Type": "application/pdf",
"Content-Length": str(os.fstat(pdf.fileno()).st_size),
}
response = session.put(
job["uploadURL"], data=pdf, headers=upload_headers, timeout=120
)
response.raise_for_status()
stage = "poll"
download_url = wait_for_download(session, job_id, auth)
stage = "download"
save_pdf(session, download_url, destination)
except (requests.RequestException, OSError, KeyError, RuntimeError) as error:
if isinstance(error, requests.HTTPError) and error.response is not None:
reason = f"HTTP {error.response.status_code}"
elif isinstance(error, RuntimeError):
reason = str(error)
else:
reason = type(error).__name__
failure = {"file": source.name, "jobID": job_id, "stage": stage, "reason": reason}
with (args.output / "scan-failures.jsonl").open("a", encoding="utf-8") as log:
log.write(json.dumps(failure) + "\n")
print(f"{source.name}: {stage} failed ({reason})", file=sys.stderr)
failed += 1
else:
print(f"Saved {destination}")
converted += 1
print(f"{converted} converted, {skipped} already saved, {failed} failed")
return int(failed > 0)
if __name__ == "__main__":
sys.exit(main())
Run the batch and check the result
python scan_invoices.py ./invoices ./scanned
If the input is invoices/INV-1042.pdf, look for scanned/INV-1042.pdf. The script writes a download to a temporary file first, so only a finished download gets the final filename. On the next run it skips PDFs that already have a copy in the output folder. If your billing system reuses filenames, give each day's export its own output folder.
One bad PDF won't hold up the rest. scan-failures.jsonl records the filename, the step that failed and the job ID if one was assigned. The script exits with code 1 if any file failed, so a scheduled job can flag the run. If a job times out or a download fails, look up the saved job ID before submitting the file again. A job can finish after the script stops waiting, and the status endpoint returns a fresh download URL for a completed job. See the API Scan reference.
The scanned copies contain images of the pages. Keep the original PDFs handy for searching and copying invoice numbers.
Try API Scan with one PDF. When the sample looks right, add the script after the invoice export you already run.