Scan to Print Labels: Build a Barcode-Triggered Workflow
Turn a barcode scan into a printed label. Build a warehouse workflow that looks up the right product, routes it to a label printer, and handles retries without duplicate output.
By the PrintScaler team · · 9 min read
You can scan to print labels by connecting a barcode scanner to a small application that looks up the scanned value and sends the matching label to a printer through an API. A common setup uses a USB scanner in keyboard mode, a browser-based scanning screen, and a label printer connected through the PrintScaler agent. The scanner supplies the identifier; your application decides what to print and where.
This guide builds a product-label workflow and explains the decisions that matter in production: scanner suffixes, label lookup, station routing, and safe retries.
How a barcode scan becomes a printed label
A barcode scanner usually does not contain your product database or know how to format a label. Connecting a scanner and printer to the same computer does not automatically connect their business logic.
A scan-to-print workflow needs four parts:
- Input: the scanner reads a product, bin, order, or shipment identifier.
- Lookup: your application finds the associated record and label content.
- Routing: your server selects an authorized printer for that workstation.
- Printing: a print service delivers the PDF or printer-language data.
For example, a receiving operator scans SKU-1042. The application finds a product label, submits it to the receiving-station printer, and shows that the job was accepted. The operator never opens a PDF or selects a printer manually.
Keep the lookup step explicit. A product barcode is not necessarily the text you want printed, and a shipment barcode might identify an existing shipping label rather than provide enough information to create one.
Choose the scanner, printer, and label format
Use keyboard mode for a simple browser station
Many USB and Bluetooth scanners support keyboard emulation, sometimes called HID keyboard mode or keyboard wedge mode. In this mode, scanning enters characters into the focused field as if someone typed them.
Configure the scanner to send an Enter suffix after each barcode. Your scanning screen can then submit the completed value without requiring a mouse click.
Before building the integration, test the scanner in a plain text editor:
- Does it preserve leading zeros?
- Does it add a prefix or suffix?
- Does each scan finish with Enter?
- Does the keyboard layout produce the expected punctuation?
- Can it read the barcode types used on your products?
Treat barcode values as strings, not numbers. Converting 00123456 to an integer changes the identifier.
Match the output format to the printer
For a Zebra or compatible printer that supports ZPL, a small ZPL label is a practical choice. For labels already generated by an ERP, carrier, or document service, send the existing PDF instead.
| Label source | Practical output | Main check |
|---|---|---|
| Product record and a controlled template | ZPL on a compatible printer | Correct language, resolution, and stock |
| Existing shipping-label document | PDF or supplied printer-language file | Correct shipment and label dimensions |
| Existing PDF product labels | Paper size and scaling | |
| Mixed printer fleet | Depends on each printer | Do not assume every device understands ZPL |
The example below uses ZPL. If you are still choosing the document format, see the guide to ZPL vs PDF for shipping labels.
Set up scan-to-print labels with PrintScaler
1. Connect and test the label printer
Install the printer locally and confirm that it can print using the appropriate driver or raw-printing setup for your operating system.
Next, install the PrintScaler agent on the computer connected to the printer. The agent supports Windows, macOS, Linux, and Raspberry Pi. Enter the pairing code in the dashboard to link the computer, then use the printer’s test-page button to check the connection.
The agent uses an outbound WebSocket connection, so this setup does not require opening inbound ports on the warehouse network. It also starts automatically after reboots.
Record the printer ID for your scanning station. Keep that ID in server-side configuration rather than allowing the browser to submit any printer ID it chooses.
2. Define what each scanned value means
Start with one unambiguous rule, such as:
Scanning a product SKU prints one approved product label at the current receiving station.
Avoid mixing product codes, order numbers, and printer-selection barcodes in the same field until you have defined how to distinguish them.
For a first test, a fixed lookup table is enough. In production, query your inventory database or ERP using an exact match and check that the operator is allowed to access that record.
The lookup result should determine:
- The label template or existing document.
- The fields that belong on the label.
- The permitted quantity.
- The intended printer or printer class.
Do not treat scanned input as a URL to fetch or as raw printer commands. It is untrusted input, even when it comes from a physical scanner.
3. Create a small server-side printing endpoint
PrintScaler accepts a print job with one HTTPS request:
POST https://api.printscaler.com/v1/printjobs
The following local demonstration uses Flask, a fixed product catalog, and base64-encoded ZPL. It never inserts the scanned value directly into printer commands.
Install the dependencies and set your server-side configuration:
python -m pip install Flask requests
export PRINTSCALER_API_KEY='psk_replace_me'
export PRINTSCALER_PRINTER_ID='123'
Save this as app.py:
import base64
import os
from uuid import UUID
import requests
from flask import Flask, jsonify, request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4096
API_KEY = os.environ['PRINTSCALER_API_KEY']
PRINTER_ID = int(os.environ['PRINTSCALER_PRINTER_ID'])
LABELS = {
'SKU-1042': (
'^XA^PW400^LL240'
'^FO24,24^A0N,28,28^FDStorage Bin Blue^FS'
'^FO24,70^BY2^BCN,90,Y,N,N^FDSKU-1042^FS'
'^XZ'
)
}
@app.post('/scan-print')
def scan_print():
data = request.get_json(silent=True)
if not isinstance(data, dict):
return jsonify(error='Expected a JSON object'), 400
sku = data.get('barcode')
try:
scan_id = str(UUID(data.get('scanId', '')))
except (ValueError, TypeError, AttributeError):
return jsonify(error='A valid scanId UUID is required'), 400
if not isinstance(sku, str) or sku not in LABELS:
return jsonify(error='Unknown product barcode'), 404
content = base64.b64encode(
LABELS[sku].encode('ascii')
).decode('ascii')
try:
response = requests.post(
'https://api.printscaler.com/v1/printjobs',
headers={
'Authorization': f'Bearer {API_KEY}',
'X-Idempotency-Key': f'scan-label-{scan_id}',
},
json={
'printerId': PRINTER_ID,
'contentType': 'raw_base64',
'content': content,
'title': f'Product label {sku}',
},
timeout=(5, 20),
)
except requests.RequestException:
return jsonify(
error='Print submission uncertain; retry the same scanId'
), 502
if not response.ok:
return jsonify(
error='Print service rejected the submission',
upstreamStatus=response.status_code,
), 502
return jsonify(status='accepted', scanId=scan_id), 202
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
Run it with python app.py. This is a localhost demonstration, not a production authentication design. Before exposing the endpoint, integrate it into your authenticated application, enforce station permissions, and add appropriate CSRF protection if you use cookie-based browser sessions.
The sample label assumes a compatible ZPL printer and stock large enough for the specified dimensions. ZPL dimensions are in dots: check the printer resolution before adapting the layout to your label size.
4. Submit one test scan
In another terminal, send a known product and a unique scan-event ID:
curl -X POST http://127.0.0.1:5000/scan-print \
-H 'Content-Type: application/json' \
-d '{
"barcode": "SKU-1042",
"scanId": "c776798c-f319-4ec9-8e23-981891bb67df"
}'
Use the same scanId if you need to retry this particular submission. Generate a new UUID for a genuinely new scan that should produce another label.
The API key stays on the server. Neither the scanner nor the browser needs access to it.
5. Connect the scanning screen
Your browser interface only needs a focused barcode field, a status message, and a submit handler. On Enter, it should:
- Read the complete barcode as a string.
- Generate a scan-event UUID, for example with
crypto.randomUUID()in a secure browser context. - Store the barcode and UUID as the pending event.
- Send them to your server endpoint.
- Show “submitted” after a successful response.
- Clear the field and restore focus for the next scan.
If the request times out, retain the pending event. A retry must reuse its UUID and barcode rather than create a new event.
For a simple station, block additional scans while a submission is unresolved. A higher-throughput application can maintain a visible queue, but each queued event still needs its own stable identity.
Prevent retries from producing extra labels
The most important distinction is between another scan and another attempt to submit the same scan.
| Event | Event ID | Intended result |
|---|---|---|
| Operator scans a product once | New ID | One label |
| Network times out during submission | Same ID on retry | No extra job from the retry |
| Operator intentionally scans the same product again | New ID | Another label |
| Browser resends a pending request after reconnecting | Same ID | No extra job from the resend |
PrintScaler supports the X-Idempotency-Key header so a retried request does not create a second print job. See the idempotency documentation before implementing your retry policy.
For production, persist the event ID, operator, station, product, selected printer, and immutable label payload in your own database. Do not rebuild a retry from a product record that may have changed since the original scan. Reject attempts to reuse an event ID for different content.
Idempotency does not prevent two genuinely separate scanner events. If a scanner sends the same barcode twice, two new event IDs can still produce two labels. Handle accidental repeated scans separately with a short, clearly communicated debounce rule or an operator confirmation flow where appropriate.
Route labels to the correct packing station
The demonstration uses one configured printer. With several stations, resolve routing on the server:
Authenticated station → approved printer ID → allowed label template
A workstation login, provisioned station identity, or authorized user selection can establish the station. Do not trust a browser-supplied printer ID without checking permissions.
Also distinguish the scanned object from the destination. Scanning a product should not silently change the active printer. If you support printer-selection barcodes, make that a separate mode and display the selected station prominently.
For shared workstations, show the active printer beside the input field. A correct label sent to the wrong packing bench is still a workflow failure.
Handle offline printers and uncertain outcomes
An accepted API request is not the same as a label physically appearing.
PrintScaler tracks states including new, sent_to_client, queued, in_progress, done, error, cancelled, and expired. Jobs can queue while a computer is offline and print when it returns, subject to their configured expiration. Review the print-job states when designing operator messages.
Use status language that reflects what you actually know:
- Submitted: the print request was accepted.
- Pending: the workflow is waiting for further progress.
- Needs attention: an error or expired job requires review.
Do not present a successful HTTP response as proof that someone received a usable label. For workflows that need stronger confirmation, add an operator acknowledgment or a second scan of the printed label.
Choose expiration behavior deliberately. A product label might remain useful after a short outage; a time-sensitive dispatch label may not. Avoid blindly submitting a replacement while the original job could still print later.
The broader guide to preventing duplicate print jobs explains how to separate safe submission retries from intentional reprints.
Test the workflow before putting it on the floor
Run a small acceptance test with actual scanners, stock, and operators:
- Scan a valid product and verify the printed barcode scans back correctly.
- Scan an unknown code and confirm that nothing prints.
- Test a code with leading zeros.
- Retry the same event ID and check that it does not create another job.
- Intentionally scan the same product twice with new IDs.
- Disconnect the agent computer and observe pending-job behavior.
- Run out of labels and confirm that staff can identify the problem.
- Switch users or stations and verify printer permissions.
- Restart the browser and check how unresolved events are recovered.
Monitor scan-to-submission time separately from submission-to-output time. Slow database lookups, network requests, offline computers, and printer problems require different fixes.
PrintScaler’s API rate limit is 10 requests per second with a burst of 30. If many stations submit through one integration, use a server-side queue and controlled retries rather than assuming every scan can trigger an immediate unrestricted request.
Start with one station and one label
A reliable scan-to-print system begins with a narrow rule: one recognized barcode selects one approved label and sends it to one authorized printer. Add durable event records, retry handling, and visible status before expanding to more stations.
PrintScaler pricing is per print request rather than per page. The Free plan includes 100 prints per month and one connected computer; check the current plans when estimating your station count and volume.
Create a free PrintScaler account, connect one label printer, and test a complete scan-to-label cycle before rolling the workflow out across your warehouse.
Frequently asked questions
Can a barcode scanner print directly to a label printer?
Usually, a scanner in keyboard mode only sends the scanned characters to an application. You need application logic to look up the record, select or generate the label, and submit it to the printer; specialized hardware may support other arrangements.
Can I scan to print labels from a browser?
Yes. A keyboard-mode scanner can enter a barcode into a browser form, which sends the value to your backend. The backend can submit the label through PrintScaler without opening the browser's print dialog.
Do the scanner and label printer need to connect to the same computer?
No. The scanner must communicate with the application receiving the scan, while the printer can connect to a separate computer running the PrintScaler agent. Your server must route each station's jobs to the correct printer.
How do I stop duplicate labels when a scan request times out?
Assign a unique ID to each scan event and reuse it as the basis for the PrintScaler idempotency key when retrying that event. A genuinely new scan gets a new ID; accidental repeated scanner events require a separate debounce or confirmation rule.
Can scanning a product barcode create a shipping label?
Not by itself. A product barcode normally identifies an item, while a shipping label requires shipment data and a label generated by a carrier or shipping system. Your application can use a scan to find and print an existing authorized shipping label.
Should I use ZPL or PDF for barcode-triggered printing?
Use ZPL when the destination printer supports it and your application controls the label template. Use PDF when your source system already supplies a correctly sized document or your printer workflow requires PDF; verify dimensions and scaling in either case.