Skip to content

.NET SDK

Printsluis.Client is the .NET client for the Printsluis API (/v1). It submits print jobs, follows their status, lists printers, aliases and agents, encrypts documents end to end, and verifies webhooks. The request and response types are in Printsluis.Contracts, which comes with it.

Other languages use the HTTP API directly: see the curl examples in the Quickstart and the API reference. For end-to-end encryption in another language, see End-to-end encryption.

Terminal window
dotnet add package Printsluis.Client
{
"Printsluis": {
"BaseAddress": "https://api.printsluis.nl/",
"ApiKey": "pgw_..."
}
}
builder.Services.AddPrintsluisClient(builder.Configuration);
  • ApiKey is an API key of your organization, from the portal’s API keys page. Keep it in a secret store, not in appsettings.json in source control.
  • The options are validated at startup. Timeout defaults to 30 seconds.
  • AddPrintsluisClient returns the IHttpClientBuilder, so you can add handlers such as AddStandardResilienceHandler(). If requests may be retried, always pass an idempotency key (see below).
  • There is also an overload that takes an Action<PrintsluisClientOptions>, to set the options in code.

Documents are encrypted end to end by default.

Without dependency injection, create the client on an HttpClient with the base address and the key. Create it once and reuse it, so its key cache works:

var http = new HttpClient { BaseAddress = new Uri("https://api.printsluis.nl/") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var printsluis = new PrintsluisClient(http);

Inject PrintsluisClient:

var job = await printsluis.PrintAsync(
new SubmitPrintJobRequest(
Target: PrintTarget.ByPrinter(user.LabelPrinterId, fallbackAlias: "labels"),
Document: PrintDocument.Zpl(zpl),
ExternalReference: order.Number),
idempotencyKey: $"order-{order.Id}-label",
cancellationToken);
  • Targets: PrintTarget.ByPrinter(printerId), optionally with a fallbackAlias, or PrintTarget.ByAlias("labels"). See Aliases.
  • Documents: PrintDocument.Zpl(string or bytes), PrintDocument.Pdf(bytes) and PrintDocument.Raw(bytes).
  • The idempotency key makes a retry safe: the same key and request return the existing job instead of printing twice. The same key with a different request fails with idempotency_key_reused. See Idempotency keys.
  • ExternalReference and Metadata are stored as plain text and are searchable. Never put personal data in them.
  • Copies, TtlSeconds and PrintOptions (for PDF) are optional.

A PDF with print options:

var job = await printsluis.PrintAsync(
new SubmitPrintJobRequest(
PrintTarget.ByAlias("office"),
PrintDocument.Pdf(await File.ReadAllBytesAsync("invoice.pdf")),
Copies: 2,
PrintOptions: new PrintOptions(
PaperSize: PaperSize.A4,
Orientation: PageOrientation.Portrait,
Scaling: PrintScaling.Fit,
Duplex: DuplexMode.LongEdge,
Color: PrintColor.Monochrome)),
idempotencyKey: $"invoice-{invoice.Id}");
Method Does
GetJobAsync(jobId) One job, with its Events: every status change
SearchJobsAsync(new PrintJobQuery(...)) Jobs by status, printer, external reference and creation time, newest first, up to 100 a page
CancelJobAsync(jobId) Cancels a job that is still Queued or Assigned
TestPrintAsync(printerId) Prints a test label, or a test page on a PDF printer
ListPrintersAsync(format) Enabled printers, for a printer choice in your application
ListAliasesAsync() The organization’s aliases
ListAgentsAsync() Agents and their health
ListAlertsAsync() Open alerts: printers that need attention, agents out of contact
var current = await printsluis.GetJobAsync(job.Id, cancellationToken);
if (current.Status == PrintJobStatus.Indeterminate)
{
// The outcome is unknown: ask someone to check the printer before printing again.
}

Rather than polling, let Printsluis call you when a job is finished: see Webhooks. What each status means is in Concepts.

A rejected request throws PrintsluisException. Its Code, such as printer_unavailable, job_not_cancellable or idempotency_key_reused, is stable and safe to branch on; Status is the HTTP status.

try
{
await printsluis.PrintAsync(request, idempotencyKey, cancellationToken);
}
catch (PrintsluisException e) when (e.Code == "printer_unavailable")
{
// No enabled printer that accepts the format matches the target: let the user choose another printer.
}

plan_limit (403) means the organization’s plan does not allow the request, such as a PDF on a plan without PDF printing, or more prints than the plan includes this month. Retrying does not help.

The common codes are listed in Concepts. The encryption codes are below.

PrintAsync encrypts every document so that only the agents that can print it can read it. Printsluis stores and routes the encrypted document, but cannot read it, and neither can anyone who gets hold of its storage or backups. Your code doesn’t change:

  1. Before submitting, the client fetches the encryption keys of the agents that can print the target: the printer’s agent, the agents of its routes, and the agents behind the fallback alias. It caches them for 5 minutes per target.
  2. It drops every key that is not signed by its agent’s identity key and, when you pin agents, every key of an agent you don’t trust.
  3. It encrypts the document for the remaining agents and submits it. The job’s Encrypted is true.

It never falls back to sending the document unencrypted. When no key is left, it throws before anything is submitted. When an agent rotated its key since the keys were fetched, the client fetches them again and retries once, with the same idempotency key.

Only the content is encrypted. Format, size, printer, copies, print options, ExternalReference and Metadata stay readable for Printsluis.

Agents need a version that supports encryption; printing to a target whose agents are all too old fails with encryption_unavailable. How it works, and what it protects against: End-to-end encryption.

Without pinning, the client trusts the keys Printsluis hands out, after checking their signatures. To also protect against a compromised Printsluis service that hands out a key of its own, list the agents you trust by their identity fingerprint:

{
"Printsluis": {
"BaseAddress": "https://api.printsluis.nl/",
"ApiKey": "pgw_...",
"Encryption": {
"TrustedAgents": [ "SHA256:A5BYxvLAy0ksUzsKTRTvd8wPeKvMztUofYShogEc+4E" ]
}
}
}
  • Get each fingerprint on the agent’s own machine: the agent prints it after pair, and diagnose shows it. Don’t copy it from the portal or the API: pinning only helps when the fingerprint did not come through Printsluis.
  • The client then only encrypts for agents in the list. A target whose agents are partly trusted is encrypted for the trusted ones only.
  • When you add an agent (a new site, a route, a replacement PC) or an agent pairs again, add its fingerprint. Until then, printing to its printers fails with encryption_untrusted; the exception’s message lists the agents’ IDs and fingerprints to compare with diagnose.
  • An entry that is not SHA256: followed by 43 base64 characters stops the application at startup.
  • An agent’s encryption key rotates every 90 days. That needs no change: the fingerprint is of the identity key, which signs each new encryption key.

GetEncryptionKeysAsync(target) returns the keys as Printsluis hands them out, for example to show the fingerprints in an admin screen:

var keys = await printsluis.GetEncryptionKeysAsync(PrintTarget.ByAlias("labels"));
foreach (var key in keys.Keys)
Console.WriteLine($"{key.AgentId}: {AgentKeyCertificate.Fingerprint(Convert.FromBase64String(key.IdentityKey))}");

Those keys are not verified or filtered; PrintAsync does that itself.

"Encryption": { "Mode": "Off" }

Mode is Required (the default) or Off. Off sends documents unencrypted, as 1.x did, for example while agents are being updated. An organization can refuse unencrypted documents (encryption_required). A document you encrypted yourself (PrintDocument with Encrypted: true) is always submitted as it is.

Without dependency injection, pass the options to the constructor: new PrintsluisClient(http, new PrintsluisEncryptionOptions { Mode = EncryptionMode.Off }).

All 422. The client throws the first two itself, before submitting anything.

Code Meaning What to do
encryption_unavailable No agent that can print the target has an encryption key, or none of the keys is signed by its agent. Update the agents; check the target.
encryption_untrusted Keys exist, but none of their agents is in TrustedAgents. The message lists the agents’ IDs and fingerprints. Compare a fingerprint with diagnose on the agent’s machine, then add it.
encryption_keys_stale The keys changed and still did after one retry, or the job was routed to an agent the document is not encrypted for. Retry later; with pinning, check that every agent of the target is trusted.
encryption_required The organization only accepts encrypted documents and Mode is Off. Turn encryption on.

The SDK verifies and parses webhook requests. Verify the raw body before you parse it:

var valid = WebhookSignature.Verify(
secret,
request.Headers[WebhookNames.TimestampHeader],
body,
request.Headers[WebhookNames.SignatureHeader],
DateTimeOffset.UtcNow);

Then WebhookEventParser.Parse(body) returns the envelope for the event type: WebhookEvent for print_job.finished, WebhookEvent<AgentStateChanged> for agent.*, WebhookEvent<PrinterStateChanged> for printer.*, and WebhookEvent<JsonElement> for a type this version doesn’t know. Deliveries can repeat (ignore a known Id) and arrive out of order (compare CreatedAt). A complete receiver is in Webhooks.

A partner (a software vendor that runs printing for its customers) uses a partner API key with organizations:read and organizations:write. Organizations creates and manages its customer organizations; ForOrganization acts inside one of them by sending the X-Organization-Id header, so the partner needs no key per customer:

var customer = await printsluis.Organizations.FindByExternalReferenceAsync(account.Number)
?? await printsluis.Organizations.CreateAsync(new CreateCustomerOrganizationRequest(account.Name, account.Number));
// The agent's install commands, with a one-time pairing code.
var pairing = await printsluis.Organizations.CreatePairingCodeAsync(customer.Id, new CreatePairingCodeRequest("Warehouse PC"));
// Print in the customer's organization; the key needs print:create.
var job = await printsluis.ForOrganization(customer.Id).PrintAsync(request, idempotencyKey: $"order-{order.Id}-label");
  • A partner key reaches only its own organizations. Anything else is organization_not_found, as is a deleted organization.
  • UpdateAsync renames or suspends an organization; a suspended organization rejects new jobs with organization_suspended. DeleteAsync revokes its keys and agents.
  • CreateApiKeyAsync creates an ordinary key of one customer organization, for software that should reach only that customer.
  • GetUsageAsync lists the organizations that printed in a month.

The assemblies have embedded PDBs, so stack traces through the SDK show file names and line numbers.

The SDK follows semantic versioning. Within a major version (2.x; the same held for 1.x):

  • The public API of both packages only grows. Types and members are not removed, renamed or changed in a way that breaks code compiled against an earlier release of that major version, at source or binary level. A new field on a request or response record gets a new constructor; the existing one stays.
  • Observable behavior stays. This covers defaults, configuration keys, the problem codes in PrintsluisException.Code, JSON names, and the webhook signature format.
  • Enums and codes can gain values. PrintJobStatus, DocumentFormat, other enums, problem codes and webhook event types may get new values in a minor release. Handle unknown values, for example with a default branch.
  • The API stays compatible. Every 1.x and 2.x client works against the current Printsluis API. /v1 changes only in ways those clients tolerate, such as new optional request fields or new response fields.
  • Dependencies. Adding a target framework is a minor release. Dropping one, or raising a Microsoft.Extensions.* dependency to a new major version, is a major release.

Not covered: the Printsluis.Contracts.Agents namespace. It is the protocol between Printsluis and its own agent, and changes with them.

A breaking change means a new major version of the SDK and, for HTTP changes, a new API version (/v2). Printsluis keeps serving /v1 until applications have moved. 2.0 changed the SDK’s behavior, not the HTTP API: it still uses /v1.

2.0 encrypts documents by default. The code that calls the SDK compiles unchanged once the names are updated; what changes is what happens when you print:

  1. Update the agents first. Every agent that can print a target (including routes and fallback aliases) needs a version that registers an encryption key. Until then, printing there fails with encryption_unavailable. GetEncryptionKeysAsync shows which agents have a key.
  2. Decide on pinning. Optionally list the agents’ fingerprints in TrustedAgents (Pinning agents).
  3. Handle the new codes encryption_unavailable, encryption_untrusted and encryption_keys_stale where you handle printer_unavailable (Encryption errors).
  4. If you can’t update the agents yet, set Encryption:Mode to Off to keep the 1.x behavior, and remove it once they are updated.

Other changes:

  • New names. 1.x was PrintGateway.Client and PrintGateway.Contracts; 2.0 is Printsluis.Client and Printsluis.Contracts on nuget.org. Replace the package references, change PrintGateway to Printsluis in the using directives, type names (PrintsluisClient, PrintsluisException, …) and the registration call (AddPrintsluisClient), and rename the configuration section PrintGateway to Printsluis. Webhook requests carry X-Printsluis-* headers; WebhookNames has them.
  • The API key needs print:create for GET /v1/encryption-keys, which a key that prints already has.
  • AddPrintsluisClient registers the client on a named HttpClient (PrintsluisClient) with a factory, and a singleton key cache. If you resolve a TimeProvider from the container, the cache uses it.
  • An encrypted document grows by 181 bytes for one agent, plus 145 bytes per further agent. The size limits apply to the document, not to that overhead.