# Ruby on Rails Printing: PDFs to Local Printers by API

> Build Ruby on Rails printing with Active Job and a cloud API. Send private PDFs to local printers, handle retries safely, and track submission status.

Published 2026-11-20 · https://printscaler.com/blog/ruby-on-rails-printing-local-printers

![Cloud-connected Rails application sending an invoice through an office computer to a local printer](https://printscaler.com/blog/images/ruby-on-rails-printing-local-printers-26.jpg)

Ruby on Rails printing to a local printer requires a connection between your hosted application and the computer that can access that printer. With PrintScaler, Rails sends an HTTPS request containing a PDF, and a background agent delivers it to the selected physical printer. Use Active Job for submission and a persistent database record to keep retries tied to the same print request.

This tutorial builds that workflow for an invoice stored in Active Storage. It keeps API credentials on the server, avoids public PDF URLs, and distinguishes API acceptance from actual printing.

## How Rails printing works outside your server

Calling a system command such as `lp` from Rails only reaches printers available to the machine running that command. On a developer laptop, that might work. Inside a hosted Rails application, it does not automatically reach a printer in an office or warehouse.

Likewise, generating a PDF does not print it. A PDF library creates the document; a transport layer must deliver that document to the right printer.

The architecture here is:

1. Rails receives an authorized request to print an invoice.
2. Rails saves an immutable print payload and a unique request key.
3. An Active Job worker submits that payload to PrintScaler.
4. The PrintScaler agent receives the job on the printer-connected computer.
5. Your application tracks subsequent printing states separately.

The browser only starts the workflow. It never receives the PrintScaler API key or opens a print dialog.

### Choose the right approach

| Requirement | Suitable approach |
|---|---|
| Let a user choose any printer available on their computer | Browser print dialog |
| Print through printers configured on the Rails server itself | Server operating-system printing |
| Automatically print at an office, warehouse, or customer site | Cloud printing API with a local agent |
| Send printer-language labels or receipts | RAW printing using the correct printer command language |

This article uses PDFs because invoices are document-oriented. PrintScaler also supports RAW ZPL, EPL, and ESC/POS, but those require different payloads and compatible printers.

## Step 1: Connect the printer and test it

Install the [PrintScaler agent](https://printscaler.com/download) on a Windows, macOS, Linux, or Raspberry Pi computer that can access the printer.

Then:

1. Confirm that the computer can print a local test page.
2. Install the agent and enter its pairing code in the PrintScaler dashboard.
3. Find the discovered printer in the dashboard.
4. Use the dashboard test-page button.
5. Record the printer ID for your Rails configuration.

The agent runs in the background, starts after reboots, and connects through an outbound WebSocket. You do not need to expose a local printer port to the internet.

For this tutorial, configure one destination printer and an API key in your deployment environment:

```bash
PRINTSCALER_API_KEY=psk_your_api_key
PRINTSCALER_PRINTER_ID=123
```

Store these through your hosting platform's secret manager or Rails encrypted credentials, not in version control. The examples read environment variables for simplicity.

In a multi-tenant application, do not trust an arbitrary printer ID from a browser. Maintain an authorized mapping between each account and its permitted printers.

## Step 2: Save a durable print request in Rails

Assume your application already has:

- An `Invoice` model with `has_one_attached :pdf`.
- A `current_account.invoices` association for authorization.
- PostgreSQL, which supports the `jsonb` column below.
- A persistent Active Job backend and a running worker.

Use a separate `PrintDelivery` record rather than treating a controller response as evidence that something printed.

```ruby
class CreatePrintDeliveries < ActiveRecord::Migration[7.1]
  def change
    create_table :print_deliveries do |t|
      t.references :invoice, null: false, foreign_key: true
      t.string :request_key, null: false
      t.jsonb :payload, null: false
      t.string :submission_state, null: false, default: "pending"
      t.integer :response_code
      t.timestamps
    end

    add_index :print_deliveries, :request_key, unique: true
  end
end
```

Add the model:

```ruby
class PrintDelivery < ApplicationRecord
  belongs_to :invoice

  validates :request_key, :payload, presence: true
end
```

The unique database index is important. Two web requests can arrive concurrently, so application-level validation alone is not enough to prevent duplicate records.

The `payload` stores the exact request that will be retried, including a snapshot of the PDF. That means a later invoice edit cannot silently change the content associated with an existing idempotency key.

For modest invoices, storing Base64 in this record is straightforward. Base64 increases binary size by roughly one third, so this design is not a recommendation to put large document archives in your transactional database. Apply document-size limits and a retention policy.

For larger files, consider private object storage and `pdf_uri`. The download URL must remain accessible to PrintScaler long enough to retrieve the document; a Rails session-protected URL will not work.

## Step 3: Create the print request from an authorized action

Declare a member route for your invoices:

```ruby
resources :invoices do
  post :print, on: :member
end
```

Then create or reuse the original-print record:

```ruby
require "base64"

class InvoicesController < ApplicationController
  def print
    invoice = current_account.invoices.find(params[:id])
    return head :unprocessable_entity unless invoice.pdf.attached?

    key = "invoice:#{invoice.id}:original:v1"

    delivery = PrintDelivery.create_or_find_by!(request_key: key) do |row|
      row.invoice = invoice
      row.payload = {
        printerId: Integer(ENV.fetch("PRINTSCALER_PRINTER_ID")),
        contentType: "pdf_base64",
        content: Base64.strict_encode64(invoice.pdf.download),
        title: "Invoice #{invoice.id}"
      }
    end

    SubmitPrintDeliveryJob.perform_later(delivery.id)

    render json: {
      print_delivery_id: delivery.id,
      submission_state: delivery.submission_state
    }, status: :accepted
  end
end
```

The deterministic key gives “print the original invoice” a stable identity. Repeated clicks reuse the same database record instead of generating a fresh print intent each time.

This assumes the invoice PDF is finalized before printing. If invoices have revisions, model those revisions explicitly and include the revision identity in the key. Do not reuse one key for different document contents.

An intentional reprint is different from a retry. Create a separate reprint action with a new, persisted request key, and make the user confirm it. Reusing the original key is appropriate when recovering from a network problem, not when someone genuinely needs another copy.

For this starter implementation, downloading and encoding the PDF happens in the controller. With larger documents or slower storage, move payload preparation to a background stage and persist the chosen document version before enqueueing it.

## Step 4: Submit the PDF through an Active Job worker

PrintScaler accepts a JSON request at `POST https://api.printscaler.com/v1/printjobs`. This service object uses Ruby's standard HTTP library and Bearer authentication.

```ruby
require "net/http"
require "json"

class PrintScalerClient
  class TransientError < StandardError; end
  class RejectedError < StandardError; end

  def submit(payload:, request_key:)
    uri = URI("https://api.printscaler.com/v1/printjobs")
    request = Net::HTTP::Post.new(uri)
    request["Authorization"] = "Bearer #{ENV.fetch('PRINTSCALER_API_KEY')}"
    request["Content-Type"] = "application/json"
    request["X-Idempotency-Key"] = request_key
    request.body = JSON.generate(payload)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.open_timeout = 5
    http.read_timeout = 30
    http.write_timeout = 30
    http.max_retries = 0

    response = http.start { |connection| connection.request(request) }
    code = response.code.to_i

    return code if (200..299).cover?(code)

    if code == 429 || (500..599).cover?(code)
      raise TransientError, "PrintScaler HTTP #{code}"
    end

    raise RejectedError, "PrintScaler HTTP #{code}"
  end
end
```

The request uses the documented `printerId`, `contentType`, `content`, and `title` fields. See the [print-job API reference](https://printscaler.com/docs#printjobs) when adding options or processing the full response.

Now call the service from Active Job:

```ruby
class SubmitPrintDeliveryJob < ApplicationJob
  queue_as :printing

  retry_on PrintScalerClient::TransientError,
           Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout,
           EOFError, Errno::ECONNRESET, Errno::ECONNREFUSED,
           wait: :polynomially_longer, attempts: 8

  def perform(delivery_id)
    delivery = PrintDelivery.find(delivery_id)
    return if delivery.submission_state == "accepted"
    return if delivery.submission_state == "rejected"

    code = PrintScalerClient.new.submit(
      payload: delivery.payload,
      request_key: delivery.request_key
    )

    delivery.update!(submission_state: "accepted", response_code: code)
  rescue PrintScalerClient::RejectedError
    delivery&.update!(submission_state: "rejected")
    raise
  end
end
```

Configure your worker to consume the `printing` queue. Do not depend on an in-process development queue for production work that must survive process restarts.

The example retries timeouts, selected connection failures, rate limiting, and server errors. Authentication failures or invalid request bodies need investigation rather than repeated submission. Add structured error reporting so a rejected job is visible to operators.

## Step 5: Make retries safe across failure boundaries

There are two distinct duplication problems:

- **Repeated business actions:** double-clicks or repeated requests to print an invoice.
- **Repeated delivery attempts:** a worker retries because it does not know whether the API received the first request.

The database key handles the first problem. The `X-Idempotency-Key` header handles the second.

Consider a timeout after PrintScaler accepts a job but before Rails receives the response. Without idempotency, retrying could produce another physical copy. With the same key and unchanged payload, the retry represents the same print request.

The same protection matters if PrintScaler accepts the request but Rails crashes before saving `accepted`. On retry, the database still says `pending`, but the API request carries the original key.

Review the [idempotency documentation](https://printscaler.com/docs#idempotency) before defining your production retry and retention policies. For a deeper treatment of request identity, see our guide to [preventing duplicate print jobs](https://printscaler.com/blog/prevent-duplicate-print-jobs).

### Close the database-to-queue gap

Saving a database record and enqueueing a background job are not automatically one atomic operation. A process can crash between those steps.

Because this implementation saves `PrintDelivery` first, you can recover by periodically enqueueing stale `pending` records. Treat the table as a small outbox, and have a scheduled task scan it in batches.

Also alert on old pending records. A pending record could mean the worker never ran, retries were exhausted, or a queue is not being consumed. Avoid endlessly re-enqueueing unresolved failures without an operational policy.

## Step 6: Track printing separately from submission

An HTTP success response means the API accepted the submission. It does not mean paper has emerged from the printer.

Keep your application's submission state separate from PrintScaler's job states:

| State or signal | Meaning |
|---|---|
| Local `pending` | Rails has a saved request awaiting successful submission |
| Local `accepted` | Rails received a successful API response |
| PrintScaler `queued` | The print job is queued |
| PrintScaler `in_progress` | Printing is reported as in progress |
| PrintScaler `done` | The printing workflow reports completion |
| PrintScaler `error`, `cancelled`, or `expired` | The job needs failure-specific handling |

PrintScaler also exposes `new` and `sent_to_client`, with full job history. Computers that are offline can have jobs queued until they reconnect, subject to configurable expiration.

For production tracking, extend the client to parse the documented response and persist the returned job identifier. Then configure [print-job webhooks](https://printscaler.com/docs#webhooks) and associate events with your local delivery record.

Verify webhook HMAC-SHA256 signatures before accepting events. Since webhooks are retried, process repeated events safely and keep event handling separate from creating new print requests.

For invoices, delayed printing may be fine. For time-sensitive documents, choose expiration deliberately so yesterday's work does not unexpectedly print this morning.

## Test the complete Rails-to-printer workflow

Test failure behavior as well as the happy path:

1. **Normal submission:** confirm that one authorized action produces one expected document.
2. **Repeated click:** confirm that the original request key is reused.
3. **Ambiguous timeout:** simulate a lost response and verify that retries keep the same payload and key.
4. **Worker interruption:** restart the worker and recover the saved request.
5. **Offline computer:** confirm queued behavior and your chosen expiration policy.
6. **Rejected request:** use an invalid test configuration and confirm that operators can identify the failure.
7. **Unauthorized access:** verify that one account cannot print another account's invoice.

Inspect the physical output too. Correct submission does not guarantee correct paper size, tray selection, duplex behavior, or margins. PrintScaler supports PDF options and exposes printer capabilities through the API; choose settings that the destination printer actually supports.

If the requirement is for customers to print through their own browser rather than a configured business printer, compare this architecture with our [silent browser printing guide](https://printscaler.com/blog/silent-printing-from-browser).

## Put Rails printing into production

A reliable integration needs more than an HTTP call: save the print intent, keep its payload stable, submit it through a durable worker, and distinguish submission from reported completion. Those boundaries make failures diagnosable without turning every retry into another invoice.

PrintScaler pricing is per print request, not per page. The Free plan includes 100 prints per month and one connected computer, which is enough to test this workflow; check the [current plans](https://printscaler.com/pricing) before rolling it out more broadly.

[Create a free PrintScaler account](https://printscaler.com/signup), connect a test printer, and run one finalized invoice through the complete workflow before enabling automatic printing.

## Frequently asked questions

### Can Ruby on Rails print directly to a user's local printer?

A hosted Rails server cannot automatically access printers on a user's private network. Use a browser print dialog for user-controlled printing, or connect the destination printer through an agent and submit jobs from Rails through a printing API.

### Can Rails print an Active Storage PDF without making it public?

Yes. Rails can download the authorized attachment on the server, Base64-encode it, and submit it with the pdf_base64 content type. This avoids exposing a public PDF URL, although document size and storage retention still need attention.

### Should printing run inside a Rails controller or Active Job?

Use the controller to authorize the action and persist the print intent, then use Active Job for the network request. A persistent queue keeps submission work separate from the browser request and supports controlled retries.

### How do I stop Rails job retries from printing extra copies?

Persist one idempotency key for each intended print action and send it in the X-Idempotency-Key header on every retry. Keep the payload unchanged, and create a new key only when a genuinely new print action, such as an intentional reprint, is requested.

### Does a successful printing API response mean the invoice printed?

No. It means the API accepted the request, not that physical output has been verified. Store the returned job identifier and use job history or signed webhooks to track subsequent states and identify errors or expiration.
