Print a PDF from Python
Use the Python standard library to POST a base64 PDF. No extra print package is required. The agent prints it on the computer you chose.
For Python services generating PDFs
This page in another language: 中文
Overview
Python on a server cannot open the user's print dialog, and it should not. Read the PDF bytes, base64-encode them, and POST /v1/print-jobs with urllib or requests. The marketing site lists an official Python SDK; this sample is the REST call that SDK would make.
content_type pdf. printer_code is an integer. The Idempotency-Key header is not JSON. A replay of the same key and body returns the original job and the header Idempotency-Replayed: true.
This is the English counterpart of the Chinese Python PDF page.
Integration steps
- 01
Create an API key on the server
Use an API key (pb_live_…) in the process environment. Authorization is Bearer. Do not ship the key to browsers or mobile apps.
- 02
Install the agent beside the printer
Windows, macOS, or Linux. GET /v1/printers and keep the numeric code.
- 03
POST /v1/print-jobs
content_type is pdf or raw. Send exactly one of content (standard base64) or content_url.
- 04
Reuse the idempotency key on retry
A new key means a second physical print. HTTP 409 means the same key was reused with a different body.
- 05
Read the job before you tell the user
GET /v1/print-jobs/{id}. Paid plans can also receive print_job.completed and print_job.failed webhooks.
Python
# Python PDF
import json, os, urllib.request
body = json.dumps({
"printer_code": int(os.environ["PRINTER_CODE"]),
"content_type": "pdf",
"content": base64.b64encode(pdf).decode(),,
"copies": 1,
}).encode()
req = urllib.request.Request(
"https://api.printbase.cloud/v1/print-jobs",
data=body,
method="POST",
headers={
"Authorization": f"Bearer {os.environ['PRINTBASE_API_KEY']}",
"Content-Type": "application/json",
"Idempotency-Key": invoice_id,
},
)
with urllib.request.urlopen(req) as res:
job = json.load(res) # {"id": "job_abc", "status": "queued"}
Details for this setup
requests is optional
urllib.request is enough. Use requests if you already depend on it. The JSON does not change.
Windows versus CUPS
You do not pick that in Python. The agent on the printer computer does. The agent prints only what you send; it does not fetch the document from the platform for you.
Questions
Can I use the cups Python module instead?
Only if Python is on the printer machine. For a remote printer, use the HTTP API.
Django or Flask?
They are thin wrappers around the same call. See those pages for where to put it.
PDF from reportlab or weasyprint?
Write the bytes, then base64. The generator does not matter.
Timeouts? in this setup
The POST should return quickly. Do not set a timeout of several minutes waiting for paper.
Free plan: 100 jobs a month on one computer, no card.