Batch Print PDF Files Automatically With a Cloud API

Stop opening PDFs one at a time. Build a manifest-driven batch printing workflow that routes documents to local printers, resumes interrupted runs, and avoids duplicate submissions.

By the PrintScaler team · · 10 min read

Illustration of a laptop routing a batch of PDF documents to two office printers.

You can batch print PDF files by having a script submit each document to a printing API, with a destination printer and a stable identifier for every job. With PrintScaler, that script can run on your laptop or a cloud server while a small agent delivers the documents to physical printers. The important part is making the batch resumable—not just looping through a folder and hoping every request succeeds.

This guide builds a practical Python workflow for invoices, packing slips, reports, and other existing PDFs. It covers printer setup, a CSV batch manifest, safe restarts, and the difference between submitting a document and confirming its print-job status.

Choose the right approach for bulk PDF printing

There are several ways to print multiple PDFs. The right choice depends on whether this is a one-time desktop task or an unattended business process.

Approach Best fit Main consideration
Desktop multi-file printing Occasional batches on one computer Behavior depends on the operating system and associated PDF application
Merge PDFs, then print once Documents sharing one destination and compatible settings Individual document tracking and selective retries become harder
Submit each PDF through an API Recurring batches, remote printers, or multiple destinations Requires a small integration and explicit job tracking

For a one-time stack of documents, your desktop tools may be sufficient. An API becomes useful when your application generates hundreds of invoices overnight, your warehouse printers are somewhere else, or operators need a reliable record of what was submitted.

PrintScaler accepts one print job per HTTPS request. This tutorial creates a batch in your application by submitting individual requests; it does not rely on an undocumented bulk endpoint.

Define what belongs in one print job

A useful default is one PDF document per print job.

A 12-page report remains one job. Twenty separate invoice PDFs become twenty jobs. This preserves a clear relationship between a source document, its destination, and its submission history.

Keeping documents separate also makes it easier to:

  • Retry a failed submission without resending the whole batch.
  • Route invoices and packing slips to different printers.
  • Find a particular document in the dashboard.
  • Request an intentional reprint of one document.
  • Investigate which documents were submitted before an interruption.

Merging files is still reasonable when the entire set belongs together. For example, a report and its appendices may be easier to manage as one PDF. But merging unrelated orders solely to reduce the number of requests trades away document-level control.

Also distinguish submission order from physical output order. Sending requests sequentially does not establish a guarantee that paper will emerge in that sequence across printers, spoolers, or competing workloads. If strict document order is essential, consider producing one combined PDF for that ordered set.

Step 1: Connect and test the destination printers

Start at the computer that can access the physical printers.

  1. Install the PrintScaler agent for Windows, macOS, Linux, or Raspberry Pi.
  2. Enter the dashboard pairing code to link the computer.
  3. Confirm that the expected printers appear in the dashboard.
  4. Use the test-page button to check the destination printer.
  5. Record each printer ID for your batch manifest.

The agent runs in the background, starts after reboots, and connects outbound through a WebSocket. You do not need to open inbound ports for this agent-based setup.

The computer running your batch script does not have to be the computer connected to the printer. A cloud worker can submit the PDFs while an office computer running the agent handles local delivery.

Test a representative PDF as well as a test page. A successful test page verifies basic connectivity; it does not prove that a landscape report, a small label, or a tray-specific form will use the correct settings.

Step 2: Prepare a CSV batch manifest

A folder contains files, but it does not explain where they belong or whether a particular document has already been submitted. A manifest makes those decisions explicit.

Create a directory containing your script, a CSV file, and a pdfs subdirectory:

batch-printing/
  print_batch.py
  batch.csv
  pdfs/
    invoice-1042.pdf
    invoice-1043.pdf
    packing-slip-1043.pdf

Use this structure for batch.csv:

job_key,printer_id,pdf_path,title
invoice-1042-original,123,pdfs/invoice-1042.pdf,Invoice 1042
invoice-1043-original,123,pdfs/invoice-1043.pdf,Invoice 1043
packing-slip-1043-original,456,pdfs/packing-slip-1043.pdf,Packing slip 1043

Each column has a specific purpose:

  • job_key: A unique, stable identifier for this intended print action.
  • printer_id: The PrintScaler destination printer ID.
  • pdf_path: A local path, resolved relative to the CSV file.
  • title: A readable description for troubleshooting.

Use business identifiers rather than row numbers for job keys. invoice-1042-original stays meaningful if you rearrange the CSV; row-1 does not.

Keep keys unique across your application’s print actions, not merely within one CSV. If you intentionally need another copy later, create a new action such as invoice-1042-reprint-1. Do not change the key just because a request timed out.

Step 3: Understand the PDF printing request

The script will send this request for every PDF:

POST https://api.printscaler.com/v1/printjobs
Authorization: Bearer psk_...
Content-Type: application/json
X-Idempotency-Key: stable-key-for-this-print-action

Its JSON body uses the documented fields:

{
  "printerId": 123,
  "contentType": "pdf_base64",
  "content": "BASE64_ENCODED_PDF",
  "title": "Invoice 1042"
}

pdf_base64 is convenient when the script already has access to local files. It avoids making those PDFs available at downloadable URLs, although encoding increases the request payload size.

Alternatively, pdf_uri lets you submit a URL instead of embedding the file. That URL must be retrievable by the printing service; a private filesystem path or an application URL requiring an interactive login will not work. See the print-job API reference for request details.

For sensitive documents, keep API credentials out of source control and avoid putting customer details in job titles unless your operational requirements justify it.

Step 4: Run a resumable Python batch script

Install the HTTP client:

python -m pip install requests

Set an environment variable in the shell that will run the script. For example, in Bash or Zsh:

export PRINTSCALER_API_KEY='psk_replace_with_your_key'

The script below uses two safeguards:

  1. A local checkpoint records successful submissions.
  2. A stable idempotency key protects retries when the HTTP outcome is uncertain.

It also fingerprints each job’s destination, title, and PDF bytes. If you change an already-started action, it stops rather than silently treating different content as the same job.

Save this as print_batch.py:

import base64
import csv
import hashlib
import json
import os
import sys
import time
from pathlib import Path

import requests

API_URL = "https://api.printscaler.com/v1/printjobs"
manifest = Path(sys.argv[1]).resolve()
checkpoint = manifest.with_suffix(".state.json")
api_key = os.environ["PRINTSCALER_API_KEY"]

state = (
    json.loads(checkpoint.read_text(encoding="utf-8"))
    if checkpoint.exists() else {}
)


def save_state():
    temporary = checkpoint.with_suffix(".tmp")
    temporary.write_text(json.dumps(state, indent=2), encoding="utf-8")
    temporary.replace(checkpoint)


with manifest.open(newline="", encoding="utf-8-sig") as handle:
    rows = list(csv.DictReader(handle))

required = {"job_key", "printer_id", "pdf_path", "title"}
seen = set()

# Validate the manifest before making any printing requests.
for row in rows:
    if not required.issubset(row) or any(
        not (row.get(name) or "").strip() for name in required
    ):
        raise ValueError("Missing or empty required CSV field")
    key = row["job_key"]
    if key in seen:
        raise ValueError(f"Duplicate job_key: {key}")
    seen.add(key)
    int(row["printer_id"])
    path = manifest.parent / row["pdf_path"]
    if not path.is_file():
        raise FileNotFoundError(path)

with requests.Session() as session:
    session.headers["Authorization"] = f"Bearer {api_key}"

    for row in rows:
        key = row["job_key"]
        pdf = (manifest.parent / row["pdf_path"]).read_bytes()
        printer_id = int(row["printer_id"])
        metadata = json.dumps(
            [printer_id, row["title"]], ensure_ascii=False
        ).encode("utf-8")
        fingerprint = hashlib.sha256(metadata + b"\0" + pdf).hexdigest()

        previous = state.get(key)
        if previous and previous["fingerprint"] != fingerprint:
            raise ValueError(f"Previously started job changed: {key}")
        if previous and previous["submitted"]:
            print(f"SKIP submitted: {key}")
            continue

        # Persist intent before sending, including uncertain attempts.
        state[key] = {"fingerprint": fingerprint, "submitted": False}
        save_state()

        idempotency_key = hashlib.sha256(
            ("pdf-batch:" + key).encode("utf-8")
        ).hexdigest()
        response = session.post(
            API_URL,
            headers={"X-Idempotency-Key": idempotency_key},
            json={
                "printerId": printer_id,
                "contentType": "pdf_base64",
                "content": base64.b64encode(pdf).decode("ascii"),
                "title": row["title"],
            },
            timeout=(10, 60),
        )
        response.raise_for_status()
        state[key]["submitted"] = True
        save_state()
        print(f"SUBMITTED: {key}")
        time.sleep(0.2)

Run it with:

python print_batch.py batch.csv

This is a single-worker reference implementation, not a complete production queue. Run only one process against a checkpoint file, retain the manifest and checkpoint together, and restrict access to the PDFs and credentials.

Before a large run, test with two ordinary documents and one controlled interruption. Verify that restarting skips previously submitted rows and retains the same identity for the interrupted action.

Step 5: Resume interruptions without creating a new batch

If a network request fails, the script stops. Inspect the error, resolve its cause, and rerun the same command with the unchanged manifest.

Rows marked submitted are skipped locally. A row with an uncertain outcome is sent again using its original idempotency key, allowing PrintScaler to recognize the retry rather than create a second print action.

This matters because a timeout does not necessarily mean that the API rejected the document. The service may have accepted it before the response was lost.

Keep these two concepts separate:

  • Retry: Repeat the same intended action with the same key.
  • Reprint: Create a new intended action with a new key.

Review the idempotency documentation before designing longer-lived retry workflows. For a broader treatment of ambiguous responses and retry behavior, see the guide to preventing duplicate print jobs.

The fingerprint check is an additional local guard, not a replacement for idempotency. It prevents accidental edits from being hidden behind a previously used key.

Track print status separately from submission

A successful HTTP response is not proof that a finished document is sitting in the output tray. In this script, submitted deliberately means only that the API request succeeded.

PrintScaler exposes job states including new, sent_to_client, queued, in_progress, done, error, cancelled, and expired, with job history available for investigation.

For a production batch dashboard, store the job identifier returned by the API according to its documented response schema, then track status changes through printjob.state events. PrintScaler provides signed webhooks with retries; implement signature verification using the webhook documentation.

Maintain distinct application fields for submission and job status. Otherwise, an operator may see a green “printed” label when the request was only accepted or when the destination computer is still offline.

Jobs can queue while a computer is offline and print when it reconnects, subject to their configured expiration. Decide whether an old document remains useful before allowing a long expiration window. Yesterday’s packing slip may require review rather than automatic output today.

For sensitive or high-consequence workflows, add an operator confirmation or downstream scan when you need evidence of physical handling. Software job status alone should not be treated as a universal paper-delivery guarantee.

Handle mixed paper sizes, trays, and batch throughput

The example sends PDFs without explicit print options. That is appropriate only when your tested defaults match the documents.

Before mixing document types, establish which settings each group requires:

  • A4 versus Letter paper.
  • Single-sided versus duplex output.
  • Specific paper trays.
  • Color versus monochrome.
  • Actual-size output versus fit-to-page behavior.
  • Copies and collation.

PrintScaler supports PDF options for these requirements, and printer capabilities are readable through the API. Validate settings against the destination printer rather than assuming every device supports the same paper or tray names.

If you are batching shipping-label PDFs, test their dimensions separately. The guide to printing 4×6 PDF shipping labels covers the scaling problems that a successful API submission cannot fix.

For throughput, the reference script submits sequentially and pauses between requests. PrintScaler’s rate limit is 10 requests per second, with a burst allowance of 30. Shared account traffic must fit within that budget too; a burst allowance is not a sustained throughput target.

A production worker should handle rate limits with bounded retries and backoff while preserving each job’s idempotency key. More parallel requests will not necessarily make a physical printer produce pages faster.

Estimate cost by requests, not PDF pages

PrintScaler pricing is per print request, not per page. Under the one-document-per-request approach, a batch of 80 PDFs creates 80 print requests, whether each PDF contains one page or several.

The Free plan includes 100 prints per month and one connected computer. That can support a small workflow test, provided your total monthly usage stays within the allowance. For larger workloads, compare request volume and connected-computer requirements on the pricing page.

Do not choose your document boundaries solely to minimize requests. Independent routing, troubleshooting, and selective reprints may be worth more operationally than combining everything into one large file.

Build a batch you can safely restart

Reliable bulk PDF printing needs explicit destinations, stable action identifiers, and separate tracking for submission and print status. A CSV manifest and a resumable script provide a practical starting point without requiring your cloud application to access local printer drivers directly.

Create a free PrintScaler account, connect one printer, and test a small batch before scheduling unattended runs.

Frequently asked questions

Can I batch print PDF files without opening each document?

Yes. A script can read a folder or manifest and submit each PDF to a printing API without opening a desktop PDF viewer. With PrintScaler, the destination printers connect through an agent, while the script can run locally or on a cloud server.

Can one PDF batch print to different printers?

Yes. Assign a printer ID to each document in your manifest and submit each PDF as a separate print job. Check paper sizes and other required options for every destination before running the full batch.

Should I merge PDFs before batch printing?

Merge PDFs when they form one ordered document with a common destination and compatible settings. Keep them separate when you need document-level routing, tracking, or selective reprints. Sequential API submissions alone should not be treated as a guarantee of physical output order.

How do I avoid duplicate prints after a timeout?

Reuse the same idempotency key for the same intended print action, including after an uncertain HTTP outcome. Keep a persistent submission record and do not generate a new key just because you are restarting the script. An intentional reprint should use a new action identifier.

Will a PDF batch print if the destination computer is offline?

PrintScaler can queue jobs while the computer is offline and deliver them when it reconnects, subject to configurable expiration. Set expiration according to how long each document remains useful, and track job status separately from successful submission.

Does a multipage PDF count as multiple print requests?

No. PrintScaler pricing is per print request rather than per page. Submitting one multipage PDF in one request is one print request; submitting 20 separate PDFs individually creates 20 requests.

Related articles