print

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package print prints BDF documents on printers: it picks what to send (the pages as a PDF file or a PostScript file, or as PWG Raster, Apple Raster or PCLm drawn by raster/imagebdf), turns a Ticket of what the job asks into the attributes of IPP, and sends the job to a printer or a queue with package print/ipp, waiting for it to be done.

The name of the package is that of the builtin print function, which it hides only where it is imported.

Index

Constants

View Source
const (
	FormatCUPSRaw     = "application/vnd.cups-raw"
	FormatOctetStream = "application/octet-stream"
)

Formats of the data of a printer's own language, sent to an IPP queue that passes it on (a raw queue of CUPS).

View Source
const (
	FormatPDF        = "application/pdf"
	FormatPostScript = "application/postscript"
	FormatPWGRaster  = "image/pwg-raster"
	FormatURF        = "image/urf"
	FormatPCLm       = "application/PCLm"
)

Document formats.

Variables

View Source
var (
	// ErrPrinterStopped is returned when the printer is stopped or not
	// accepting jobs: its state reasons tell why (media-empty …).
	ErrPrinterStopped = errors.New("print: the printer is stopped")
	// ErrUnsupported is returned, with Options.Strict, when the printer
	// does not support what the ticket asks.
	ErrUnsupported = errors.New("print: the printer does not support what the ticket asks")
	// ErrAborted is returned when the printer aborted the job.
	ErrAborted = errors.New("print: the printer aborted the job")
	// ErrCanceled is returned when the job was canceled, at the printer
	// or because the context was.
	ErrCanceled = errors.New("print: the job was canceled")
	// ErrTimeout is returned when the job is not done in Options.Wait.
	ErrTimeout = errors.New("print: the job is not done yet")
	// ErrJobLost is returned when the printer lost the job before it had
	// the document: it was restarted after Create-Job, and its job of the
	// id is gone or another's. Nothing was printed; the job can be sent
	// again.
	ErrJobLost = errors.New("print: the printer lost the job before it had the document")
)

Errors of a job, which bdf print tells apart by its exit status.

View Source
var ErrNoPages = errors.New("print: the document has no pages to print")

ErrNoPages is returned for a document without pages to print.

Functions

func Check

func Check(ctx context.Context, c *ipp.Client, last *ipp.JobStatus) (*ipp.JobStatus, error)

Check asks the printer once for the state of a job it was sent, and returns it merged into the last state known. A job canceled or aborted at the printer returns its state with ErrCanceled or ErrAborted; a job not done yet, or completed, returns no error. When the printer could not be asked, the state is nil.

func ChooseMedia

func ChooseMedia(w, h float64, ready, supported []string) string

ChooseMedia picks the media of a page of w × h points among a printer's: the first of ready (media-ready) that matches the page, else the first of supported (media-supported) that does; "" when none does. Names that are not self-describing are passed over.

func FormatName

func FormatName(s string) (format string, ok bool)

FormatName reads a format as Options.Format takes it: a short name ("pdf", "ps", "pwg-raster", "urf", "pclm") or a MIME type of a format that is written, as its MIME type; "" or "auto" as "". ok is false for others.

func FormatTitle

func FormatTitle(format string) string

FormatTitle names a format (a MIME type) for people: "PDF", "PostScript", "PWG Raster", "Apple Raster", "PCLm"; the type itself for others.

func IsDeviceFormat

func IsDeviceFormat(format string) bool

IsDeviceFormat reports whether a format (Options.Format) is the language of a printer of labels, receipts or forms.

func PlacePS

func PlacePS(media string, scaling raster.Scaling, orientation raster.Orientation) func(w, h float64) (float64, float64, [6]float64)

PlacePS returns how the pages of a PostScript file go on the paper of a media (a PWG media name), for psbdf.Options.Place: scaled, turned and centred as raster pages are (raster.Fit). It is nil for a media that is not known: each page is then printed on a sheet of its size.

func PrintView

func PrintView(doc *bdf.Document, id string) (*bdf.View, error)

PrintView returns the view of a document that is printed: the view of the id, or the first view of pages (fixed or flow), or the first scroll view, whose strips are pages too.

func RawCapabilities

func RawCapabilities(p *raw.Printer) *ipp.Printer

RawCapabilities is what a raw printer is known to support: the format of its URL, and no more.

Types

type Event

type Event struct {
	// Kind is "created", "sent" or "state".
	Kind string
	Job  *ipp.JobStatus
	// Bytes is the size of the document, once sent.
	Bytes int64
}

Event is something that happened to a job.

type Media

type Media struct {
	Name string
	// Width and Height are in points (1/72 inch).
	Width, Height float64
}

Media is a size of paper by its PWG name (PWG 5101.1), such as "iso_a4_210x297mm": a class, a name, and the size, which the name carries itself, so that any name a printer reports can be read.

func ParseMedia

func ParseMedia(name string) (Media, error)

ParseMedia reads the size of a PWG self-describing media name: its last part, "<w>x<h>mm" or "<w>x<h>in".

func ResolveMedia

func ResolveMedia(s string) (Media, error)

ResolveMedia turns a -media value into a PWG name: a short name ("a4", "b5", "hagaki", "letter"), a size alone ("104x150mm", "4x6in", a custom_ name), or a PWG name as it is.

func (Media) Matches

func (m Media) Matches(w, h float64) bool

Matches reports whether a page of w × h points is the size of the media, upright or turned.

type Meta

type Meta struct {
	// AccountID is job-account-id and AccountingUserID
	// job-accounting-user-id (PWG 5100.7): the account a job is charged
	// to (a department, a project, a cost centre) and the user of the
	// account. A printer that says it takes them
	// (job-account-id-supported) is asked them.
	AccountID        string `json:"job-account-id,omitempty"`
	AccountingUserID string `json:"job-accounting-user-id,omitempty"`
	// Metadata is document-metadata (PWG 5100.13): "key=value" strings
	// that describe the document, with the keys of Dublin Core ("title",
	// "creator", "identifier", "subject", "description", "date" …) or
	// keys of one's own that begin with "x-". It goes with the document
	// (Print-Job, Send-Document); a printer keeps it with the job.
	Metadata []string `json:"document-metadata,omitempty"`
	// Custom are job attributes of one's own, sent as they are: their
	// names begin with "x-" (RFC 8011 §7.2 leaves vendors their own
	// prefixes), their values are strings (name on the wire). A printer
	// that does not know one says so, and prints the job without it.
	Custom map[string]Strings `json:"bdf-attributes,omitempty"`
}

Meta is what a job says about itself besides how it is printed: the account it is charged to, what describes its document, and attributes of one's own. A ticket carries it under IPP's names; the client sends it to the printer with the job, and the IPP server keeps it with a job and tells it back (Get-Job-Attributes), as a printer does.

func (*Meta) Attrs

func (m *Meta) Attrs() []ipp.Attribute

Attrs are the attributes a job carries of the meta: job-account-id, job-accounting-user-id and the attributes of one's own (job template attributes), and document-metadata (a job status attribute, as a printer keeps it). An empty meta has none.

func (*Meta) Check

func (m *Meta) Check() error

Check validates the meta: the lengths, the keys of document-metadata and the names of the attributes of one's own.

func (*Meta) Empty

func (m *Meta) Empty() bool

Empty tells a meta that says nothing.

func (*Meta) Take

func (m *Meta) Take(a ipp.Attribute) (known, ok bool)

Take reads an attribute of a request that makes a job into the meta when it is one of the meta's: job-account-id, job-accounting-user-id, one named x-… (job template attributes) or document-metadata (an operation attribute). known tells it is one of them; ok that its value was taken, else the attribute is unsupported as it came.

type Options

type Options struct {
	Ticket Ticket
	// Format is "pdf", "ps" (PostScript), "pwg-raster", "urf" (Apple
	// Raster), "pclm", or "" (or "auto") to choose: PDF when the printer
	// takes it, else PostScript, else PWG Raster, else Apple Raster, else
	// PCLm. It may be the language of a printer of labels, receipts or
	// forms too ("zpl", "sbpl", "tpcl", "escpos", "escp"; print/pdl),
	// which an IPP queue that passes data on as it is (a raw queue of
	// CUPS) is sent.
	Format string
	// Profile is the printer a language of print/pdl is written for: nil
	// for the profile of a raw printer's URL, or the language's default.
	Profile *pdl.Profile
	// RasterIfLossy sends PWG Raster instead of PDF when the PDF file
	// would leave out what the document draws (FILTER, composite
	// operations of Canvas, shadows past their limits …) and the printer
	// takes PWG Raster: the page is then printed as the viewer shows it.
	RasterIfLossy bool
	// View is the id of the view to print; "" prints the first view of
	// pages.
	View string
	// SkipRoles are the roles of the layers left out (bdf.RoleBackground,
	// bdf.RoleMaster): for paper that has them printed already.
	SkipRoles []string
	// Strict makes what the printer does not support an error; without
	// it, it is left out with a warning.
	Strict bool
	// FontFS, FontDirs and NoSystemFonts find the fonts of the text of
	// fonts referred to by name, for PDF files and raster pages alike.
	FontFS        fs.FS
	FontDirs      []string
	NoSystemFonts bool
	// Wait is how long to wait for the job to be done: 0 returns once
	// the document is sent; a negative value waits for as long as the
	// context lets it.
	Wait time.Duration
	// MaxImpressions bounds the pages sent (pages times copies the
	// client makes): 10,000 when 0.
	MaxImpressions int
	// Progress is told what happens: the job created, its document
	// sent, and each state the printer reports.
	Progress func(Event)
	// BandRows and BandWorkers are those of the renderer of raster pages
	// (imagebdf.Options).
	BandRows, BandWorkers int
	// Printer is what the printer supports, when the caller asked it
	// already: Get-Printer-Attributes is then not sent again. Whether the
	// printer is stopped is still checked, from its state in Printer.
	Printer *ipp.Printer
	// OnCreated is called with the job the printer made, before the
	// document is sent (after it when the printer has no Create-Job and
	// takes Print-Job). A spool records the job's id there, to know after
	// a crash whether the printer has the job already. An error cancels
	// the job at the printer and is returned.
	OnCreated func(*ipp.JobStatus) error
	// OnSent is called once the printer has the whole document. An
	// error is returned; the job is left to the printer.
	OnSent func(*ipp.JobStatus) error
}

Options are a job: its ticket, how the document is sent, and how its end is waited for.

type Result

type Result struct {
	Printer *ipp.Printer
	// Format is the format the document was sent in, and Media the
	// paper asked for ("" for the printer's default).
	Format string
	Media  string
	// Sheets are the pages sent (as images or as pages of the PDF
	// file), copies the client made included.
	Sheets int
	// Bytes is the size of the document sent.
	Bytes int64
	// Job is the last state the printer reported of the job; nil when
	// it was not created.
	Job *ipp.JobStatus
	// Unsupported are the attributes of the ticket that the printer
	// does not support and that were left out (name=value).
	Unsupported []string
	Warnings    []string
}

Result is what happened to a job.

func Print

func Print(ctx context.Context, c *ipp.Client, doc *bdf.Document, opts *Options) (*Result, error)

Print prints a document on the printer of a client: it asks the printer what it supports, makes the job's attributes of the ticket, sends the document as PDF or PWG Raster, and waits for the job to be done as Options.Wait says. When the context is canceled after the job is created, the job is canceled at the printer.

func PrintRaw

func PrintRaw(ctx context.Context, p *raw.Printer, doc *bdf.Document, opts *Options) (*Result, error)

PrintRaw prints a document on a printer that does not speak IPP (package print/raw: 9100, LPD, a serial port, a USB device file, a queue of Windows), as PostScript or PDF, or in the language of a printer of labels, receipts or forms (print/pdl), as the printer's URL or Options.Format says. A language is written for the profile of Options.Profile, else of the URL, with the copies, the paper and the settings of the ticket in it. Such a printer is told of the job only in its file: PostScript asks for the paper (the pages placed on it as on an IPP printer), the copies, the sides and the media type with setpagedevice; PDF holds its copies as pages again, and asks for the sides, the paper and gray in its PJL header. What neither carries is left out (or, with Strict, refused). The job ends when the printer has the document, which is all the protocols tell: Options.Wait is not waited for.

OnCreated is called before the printer may begin to print the job (with a job status of no id), OnSent once it has it. An error after the first wraps raw.ErrPartial: the printer may have printed a part of the job.

type Strings

type Strings []string

Strings are the values of an attribute: in JSON a string, or a list of strings.

func (Strings) MarshalJSON

func (s Strings) MarshalJSON() ([]byte, error)

MarshalJSON writes one value as a string, more as a list.

func (*Strings) UnmarshalJSON

func (s *Strings) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a string or a list of strings.

type Ticket

type Ticket struct {
	// JobName is the job-name (the document's file name, usually).
	JobName string `json:"job-name,omitempty"`
	// Copies of the document (copies); 0 or 1 for one.
	Copies int `json:"copies,omitempty"`
	// Collate is "collated" (1 2 3 1 2 3), "uncollated" (1 1 2 2 3 3)
	// or "" for the printer's default.
	Collate string `json:"collate,omitempty"`
	// Sides is "one-sided", "two-sided-long-edge" or
	// "two-sided-short-edge" (sides), "" for the default.
	Sides string `json:"sides,omitempty"`
	// Media is a PWG media name; "" picks the paper of the size of the
	// first page among the printer's (media-ready first).
	Media string `json:"media,omitempty"`
	// MediaSource ("tray-1", "manual" …) and MediaType ("stationery",
	// "labels" …) go in media-col.
	MediaSource string `json:"media-source,omitempty"`
	MediaType   string `json:"media-type,omitempty"`
	// ColorMode is "color", "monochrome" or "auto" (print-color-mode),
	// "" for the default.
	ColorMode string `json:"print-color-mode,omitempty"`
	// Bilevel draws black and white, without gray, when the colour mode
	// is monochrome and the document is sent as PWG Raster (black_1 or
	// sgray_1): line drawings and text, at a sixth of the size.
	Bilevel bool `json:"bilevel,omitempty"`
	// Quality is print-quality: 3 draft, 4 normal, 5 high, 0 the default.
	Quality int `json:"print-quality,omitempty"`
	// Resolution in dots per inch (printer-resolution, and the raster's);
	// 0 picks one.
	Resolution int `json:"printer-resolution,omitempty"`
	// Pages are the one-based pages to print, in order; nil prints all.
	Pages []int `json:"pages,omitempty"`
	// Scaling is print-scaling: how a page is fitted to the paper.
	Scaling raster.Scaling `json:"print-scaling,omitempty"`
	// Orientation is orientation-requested; 0 turns landscape pages
	// onto portrait paper by itself.
	Orientation raster.Orientation `json:"orientation-requested,omitempty"`
	// Finishings are the enums of finishings (4 staple, 5 punch …).
	Finishings []int `json:"finishings,omitempty"`
	// OutputBin is output-bin.
	OutputBin string `json:"output-bin,omitempty"`
	// HoldUntil is job-hold-until ("indefinite", "night" …).
	HoldUntil string `json:"job-hold-until,omitempty"`
	// Priority is job-priority, 1 to 100; 0 for the default.
	Priority int `json:"job-priority,omitempty"`

	// What a printer of labels, receipts or forms is asked (print/pdl):
	// Darkness is print-darkness (-100 to 100, 0 the printer's), Speed
	// print-speed (hundredths of a millimetre a second), MediaTracking
	// media-tracking ("continuous", "gap", "mark"), as PWG 5100.13 names
	// them; an IPP printer that supports the first two is asked them.
	Darkness      int    `json:"print-darkness,omitempty"`
	Speed         int    `json:"print-speed,omitempty"`
	MediaTracking string `json:"media-tracking,omitempty"`
	// LabelGap is the gap between labels in hundredths of a millimetre
	// (TPCL asks it); 0 for 3 mm.
	LabelGap int `json:"bdf-label-gap,omitempty"`
	// Cut is "none", "page" or "job": after each label or receipt, or
	// after the last ("" for the language's default).
	Cut string `json:"bdf-cut,omitempty"`
	// CashDrawer opens the drawer on a receipt printer's pin 2 (1) or 5
	// (2) at the end of the job.
	CashDrawer int `json:"bdf-cash-drawer,omitempty"`
	// PerforationSkip skips the perforation of a continuous form, in
	// hundredths of a millimetre (ESC/P).
	PerforationSkip int `json:"bdf-perforation-skip,omitempty"`
	// NoPrinterBarcodes draws the QR codes and barcodes that a label
	// printer would print with its own commands.
	NoPrinterBarcodes bool `json:"bdf-no-printer-barcodes,omitempty"`
	// PrintMode is "raster" (the dots of the pages) or "text" (ESC/P and
	// ESC/POS: the characters of the print image of a form filled from a
	// template of text, in the printer's fonts); "" for the language's
	// default: the text mode for ESC/P when the document has a print image,
	// else the dots.
	PrintMode string `json:"bdf-print-mode,omitempty"`

	// Meta is what the job says about itself: the account it is charged
	// to, what describes its document, attributes of one's own.
	Meta
}

Ticket is what a job asks of a printer, named as IPP names it (its JSON keys are the IPP attributes' names). The zero value asks for nothing: the printer's defaults.

func (*Ticket) Check

func (t *Ticket) Check() error

Check validates the values of a ticket that do not depend on the printer.

func (Ticket) Merge

func (t Ticket) Merge(defaults Ticket) Ticket

Merge fills what a ticket does not ask with what defaults ask: the defaults of a queue under the ticket of a job.

Directories

Path Synopsis
Package fakeidp is an OpenID Provider for tests: discovery, a JWKS, the authorization code flow with PKCE (S256) and RS256 ID tokens, with the people of a test and their groups in a claim of any path ("groups", "roles", Keycloak's "realm_access.roles").
Package fakeidp is an OpenID Provider for tests: discovery, a JWKS, the authorization code flow with PKCE (S256) and RS256 ID tokens, with the people of a test and their groups in a claim of any path ("groups", "roles", Keycloak's "realm_access.roles").
Package fakeprinter is printers that are not there, for tests and for trying bdf print and bdf printd without paper.
Package fakeprinter is printers that are not there, for tests and for trying bdf print and bdf printd without paper.
readback
Package readback turns what a fake printer received back into pages: the images of PWG Raster and Apple Raster as they are, PDF and PCLm drawn (converter/pdf, then raster/imagebdf), PostScript drawn by Ghostscript where it is, JPEG and PNG decoded, and the label, receipt and dot-matrix languages read as their printers print them (print/pdl): their dots, and the commands of the printer's own barcodes.
Package readback turns what a fake printer received back into pages: the images of PWG Raster and Apple Raster as they are, PDF and PCLm drawn (converter/pdf, then raster/imagebdf), PostScript drawn by Ghostscript where it is, JPEG and PNG decoded, and the label, receipt and dot-matrix languages read as their printers print them (print/pdl): their dots, and the commands of the printer's own barcodes.
Package ipp reads and writes the messages of the Internet Printing Protocol (RFC 8010) and speaks it to printers (RFC 8011, PWG 5100.12: IPP/2.x).
Package ipp reads and writes the messages of the Internet Printing Protocol (RFC 8010) and speaks it to printers (RFC 8011, PWG 5100.12: IPP/2.x).
Package pdl writes BDF pages in the languages of printers of labels, receipts and continuous forms, which take neither PDF nor PostScript: ZPL (Zebra), SBPL (SATO) and TPCL (Toshiba TEC) for labels, ESC/POS (Epson TM and the printers like it) for receipts, and ESC/P (Epson VP and the dot-matrix printers like it) for continuous forms.
Package pdl writes BDF pages in the languages of printers of labels, receipts and continuous forms, which take neither PDF nor PostScript: ZPL (Zebra), SBPL (SATO) and TPCL (Toshiba TEC) for labels, ESC/POS (Epson TM and the printers like it) for receipts, and ESC/P (Epson VP and the dot-matrix printers like it) for continuous forms.
Package printconv converts the documents a print server receives into .bdf documents of pages, with the converters registered in package converter (import converter/all, or the converters a program needs) and print/raster for the rasters of driverless clients.
Package printconv converts the documents a print server receives into .bdf documents of pages, with the converters registered in package converter (import converter/all, or the converters a program needs) and print/raster for the rasters of driverless clients.
Package raster writes the raster formats of driverless printing: PWG Raster (PWG 5102.4, image/pwg-raster), which IPP Everywhere printers take, Apple Raster (image/urf), which AirPrint printers take, and PCLm (application/PCLm), which Mopria printers take.
Package raster writes the raster formats of driverless printing: PWG Raster (PWG 5102.4, image/pwg-raster), which IPP Everywhere printers take, Apple Raster (image/urf), which AirPrint printers take, and PCLm (application/PCLm), which Mopria printers take.
Package raw sends documents to printers that do not speak IPP: over the raw socket of port 9100 (AppSocket, JetDirect), the line printer daemon protocol (LPD, RFC 1179), a serial port (and a Bluetooth printer of the serial port profile, which the OS shows as one), the device file of a USB printer (Linux and the BSDs), and a queue of Windows whose driver passes RAW data on (winspool).
Package raw sends documents to printers that do not speak IPP: over the raw socket of port 9100 (AppSocket, JetDirect), the line printer daemon protocol (LPD, RFC 1179), a serial port (and a Bluetooth printer of the serial port profile, which the OS shows as one), the device file of a USB printer (Linux and the BSDs), and a queue of Windows whose driver passes RAW data on (winspool).
Package server is the print server: a spool (print/spool) of the queues and printers of a configuration file, its HTTP API (/api/v1), the changes as Server-Sent Events, /metrics, and a page of its state.
Package server is the print server: a spool (print/spool) of the queues and printers of a configuration file, its HTTP API (/api/v1), the changes as Server-Sent Events, /metrics, and a page of its state.
client
Package client talks to a print server (bdf printd) over its HTTP API: it submits documents, follows and changes jobs, and reads the queues, the printers and the accounting.
Package client talks to a print server (bdf printd) over its HTTP API: it submits documents, follows and changes jobs, and reads the queues, the printers and the accounting.
Package spool keeps print jobs and sends them to printers: it takes a job and its document, keeps both across restarts, queues the job, sends it to a printer of its queue as print.Print does, follows it until the printer is done, retries what failed for want of the printer, and never prints a job twice after a crash.
Package spool keeps print jobs and sends them to printers: it takes a job and its document, keeps both across restarts, queues the job, sends it to a printer of its queue as print.Print does, follows it until the printer is done, retries what failed for want of the printer, and never prints a job twice after a crash.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL