
Product
/Security News
Introducing Socket Calm: A Syntax Highlighting Theme for VS Code, Vim, and Neovim
Socket Calm is a free, open source syntax highlighting theme for VS Code, Vim, and Neovim, inspired by Socket's design system.
trupermax/print-agent
Advanced tools
Librería PHP para comunicarse con Print Agent desde aplicaciones web.
Librería PHP para comunicarse con el servicio local Print Agent desde aplicaciones web o Laravel.
composer require trupermax/print-agent
use Trupermax\PrintAgent\PrintAgent;
use Trupermax\PrintAgent\EscPos;
$agent = new PrintAgent();
$bytes = (new EscPos())
->init()
->align('center')
->bold(true)
->textLine('Hola Mundo')
->cut()
->build();
$agent->printEscPos($bytes, useDefaultPrinter: true);
$agent = new PrintAgent(string $baseUrl = 'http://127.0.0.1:9876');
status()Retorna el estado del servicio.
$res = $agent->status();
// ['status' => 'running', 'message' => 'Print Agent funcionando correctamente']
printers()Retorna la lista de impresoras disponibles.
$printers = $agent->printers();
// [['name' => 'EPSON TM-T20', 'driver' => '...', 'port' => '...', 'is_default' => true]]
printPDF()Imprime un PDF a partir de un string en Base64.
$agent->printPDF(
pdfBase64: base64_encode(file_get_contents('documento.pdf')),
printerName: 'HP LaserJet',
copies: 2,
);
printZPL()Imprime una etiqueta ZPL en una impresora Zebra.
$agent->printZPL(
raw: '^XA^FO50,50^ADN,36,20^FDHola^FS^XZ',
printerName: 'ZDesigner GK420d',
copies: 1,
);
printEscPos()Imprime bytes ESC/POS en una impresora térmica. Recibe el string binario que retorna EscPos::build().
$bytes = (new EscPos())->init()->textLine('Hola')->cut()->build();
$agent->printEscPos(
data: $bytes,
printerName: 'EPSON TM-T20',
copies: 1,
);
escpos()Método de fábrica que retorna una nueva instancia del builder EscPos.
$builder = $agent->escpos();
$bytes = $builder->init()->textLine('Hola')->cut()->build();
Todos los métodos retornan $this para encadenarse, excepto build() que retorna el string binario final.
| Método | Descripción |
|---|---|
init() | Inicializa la impresora (resetea configuración) |
align(string) | Alineación: 'left', 'center', 'right' |
bold(bool) | Negrita: true / false |
underline(bool) | Subrayado: true / false |
fontSize(int) | Tamaño de fuente: 1 (normal) al 4 (cuádruple) |
text(string) | Agrega texto sin salto de línea |
textLine(string) | Agrega texto con salto de línea |
line(string, int) | Línea separadora (defecto: 42 guiones) |
feed(int) | Avanza el papel N líneas (defecto: 1) |
row(string, string, int) | Dos textos en la misma línea: izquierda y derecha |
columns(array, array) | Tabla con N columnas de ancho y alineación individual |
qr(string, int, string) | Código QR generado por la impresora |
barcode(string, string, int, int, string) | Código de barras generado por la impresora |
cut(bool) | Corta el papel: parcial (defecto) o completo |
raw(array) | Agrega bytes ESC/POS crudos directamente |
build() | Retorna el string binario final para enviar al endpoint |
init()Inicializa la impresora y resetea todos los ajustes. Siempre llámalo primero.
(new EscPos())->init()
align(string $value)->align('left') // izquierda (defecto)
->align('center') // centro
->align('right') // derecha
bold(bool $enabled)->bold(true)
->bold(false)
underline(bool $enabled)->underline(true)
->underline(false)
fontSize(int $size)->fontSize(1) // normal
->fontSize(2) // doble
->fontSize(3) // triple
->fontSize(4) // cuádruple
text(string $value)Agrega texto sin salto de línea.
->text('Subtotal: ')->bold(true)->text('Q.150.00')->bold(false)
textLine(string $value)Agrega texto seguido de un salto de línea.
->textLine('Hola Mundo')
line(string $char = '-', int $length = 42)->line() // 42 guiones
->line('=', 42) // 42 signos igual
->line('*', 20) // 20 asteriscos
feed(int $lines = 1)->feed() // avanza 1 línea
->feed(3) // avanza 3 líneas
row(string $left, string $right, int $width = 42)Imprime dos textos en la misma línea rellenando el espacio entre ellos. Útil para pares clave-valor.
->row('Subtotal', 'Q.150.00')
->row('IVA 12%', 'Q.18.00', 42)
->row('TOTAL', 'Q.168.00')
columns(array $cells, array $defs)Imprime N columnas con ancho y alineación individual. Ideal para tablas de productos.
->columns(
cells: ['Cant.', 'Descripción', 'Precio', 'Total'],
defs: [
['width' => 6, 'align' => 'left'],
['width' => 16, 'align' => 'left'],
['width' => 10, 'align' => 'right'],
['width' => 10, 'align' => 'right'],
]
)
Cada definición de columna:
| Campo | Tipo | Defecto | Descripción |
|---|---|---|---|
width | int | requerido | Ancho en caracteres |
align | string | 'left' | Alineación: 'left', 'center', 'right' |
La suma de todos los anchos debe coincidir con el ancho de la impresora (normalmente 42 para papel de 80mm).
qr(string $data, int $size = 4, string $errorLevel = 'M')Genera un código QR usando el hardware de la impresora.
->qr('https://miempresa.com')
->qr('https://miempresa.com', size: 6, errorLevel: 'H')
| errorLevel | Corrección |
|---|---|
'L' | 7% — más compacto |
'M' | 15% — uso general (defecto) |
'Q' | 25% — ambientes con suciedad |
'H' | 30% — máxima corrección |
barcode(string $data, string $type = 'CODE128', int $height = 60, int $width = 2, string $textPosition = 'below')Genera un código de barras usando el hardware de la impresora.
->barcode('1234567890128')
->barcode('1234567890128', type: 'EAN13', height: 80, textPosition: 'below')
Tipos de código de barras soportados:
| Tipo | Uso típico |
|---|---|
'CODE128' | Uso general, alfanumérico (defecto) |
'CODE39' | Inventario, industria |
'CODE93' | Variante compacta de CODE39 |
'EAN13' | Productos retail (13 dígitos) |
'EAN8' | Productos pequeños (8 dígitos) |
'UPC-A' | Retail USA (12 dígitos) |
'UPC-E' | Versión comprimida de UPC-A |
'ITF' | Cajas y logística |
'CODABAR' | Bibliotecas, sangre, courier |
cut(bool $partial = true)->cut() // corte parcial (defecto)
->cut(false) // corte completo
raw(array $bytes)Agrega bytes ESC/POS crudos. Útil para comandos avanzados no cubiertos por el builder.
->raw([0x1b, 0x21, 0x00])
build()Retorna el string binario final con todos los bytes acumulados para enviar al endpoint.
$bytes = (new EscPos())->init()->textLine('Hola')->cut()->build();
use Trupermax\PrintAgent\PrintAgent;
use Trupermax\PrintAgent\EscPos;
$agent = new PrintAgent();
$items = [
['code' => 'A00310', 'desc' => 'TOR HEX GR5 NC 3/8 X 1', 'qty' => 2, 'price' => 2.00],
['code' => 'A03672', 'desc' => 'FAJA A-40 LISA SUPERBELT', 'qty' => 1, 'price' => 37.00],
];
$colDefs = [
['width' => 6, 'align' => 'left'],
['width' => 10, 'align' => 'right'],
['width' => 10, 'align' => 'right'],
['width' => 16, 'align' => 'right'],
];
$escpos = (new EscPos())
->init()
->align('center')
->bold(true)
->textLine('MI EMPRESA S.A.')
->bold(false)
->textLine('NIT: 123456-7')
->feed(1)
->align('left')
->line('-', 42)
->columns(['Cant.', 'Precio', 'Desc.%', 'Total'], $colDefs)
->line('-', 42);
$total = 0;
foreach ($items as $item) {
$itemTotal = $item['qty'] * $item['price'];
$total += $itemTotal;
$escpos
->textLine("{$item['code']} - {$item['desc']}")
->columns(
[(string) $item['qty'], 'Q.' . number_format($item['price'], 2), '', 'Q.' . number_format($itemTotal, 2)],
$colDefs
)
->feed(1);
}
$escpos
->line('-', 42)
->align('right')
->bold(true)
->textLine('TOTAL: Q.' . number_format($total, 2))
->bold(false)
->feed(1)
->align('center')
->qr('https://miempresa.com', size: 4)
->feed(3)
->cut();
$bytes = $escpos->build();
$printers = $agent->printers();
$printer = collect($printers)->firstWhere('is_default', true)['name'] ?? '';
$agent->printEscPos($bytes, printerName: $printer);
El ejemplo usa
collect()de Laravel. Si usas PHP puro, reemplázalo con unforeachpara encontrar la impresora por defecto.
# Instalar dependencias
composer install
# Ejecutar la demo manual (requiere Print Agent corriendo en localhost:9876)
php test/manual.php
FAQs
Librería PHP para comunicarse con Print Agent desde aplicaciones web.
We found that trupermax/print-agent demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Product
/Security News
Socket Calm is a free, open source syntax highlighting theme for VS Code, Vim, and Neovim, inspired by Socket's design system.

Product
Fix critical RubyGems vulnerabilities without upgrading dependencies. Free security patches are now available with more ways to install and deploy them.

Threat Research
/Security News
Socket researchers uncovered 13 malicious NuGet packages linked to fake developer job assessments, DLL side-loading, credential theft, and GitHub-based malware.