t2bprinter.js es la librería de navegador que permite imprimir a impresoras térmicas
directamente desde tu app web, sin plugins ni backend propio.
Carga la librería → llama a los métodos del objeto global T2bPrinter →
la librería se comunica con el agente local de Text2 Barcode, que gestiona la impresora física.
localhost:9101 (HTTPS) o localhost:9100 (HTTP),
con fallback automático si el puerto seguro no responde.
https://labeldictate.com/text2barcode/lib/t2bprinter.js
Todos los métodos son async/await. Flujo típico en 3 pasos:
<script src="https://labeldictate.com/text2barcode/lib/t2bprinter.js"></script>
const printer = await T2bPrinter.find(it => it.name.includes("Zebra"));
if (printer) {
const result = await T2bPrinter.write(printer, `^XA^FO50,50^A0N,50^FDHello^FS^XZ`);
console.log(result); // { result: true, message: "..." }
}
Propiedades del objeto global T2bPrinter. Todas tienen valores funcionales por defecto.
| Propiedad | Tipo | Default | Descripción |
|---|---|---|---|
| enableDebug | boolean | false | Activa logs en consola (console.debug / console.warn). Útil para diagnosticar conectividad en desarrollo. |
| defaultPort | number | 9100 | Puerto HTTP. Se usa cuando useSecureConnection es false o cuando HTTPS falla y la librería hace fallback. |
| securePort | number | 9101 | Puerto HTTPS. Las solicitudes van a https://127.0.0.1:9101. |
| useSecureConnection | boolean | true |
Controla HTTPS vs HTTP. Si HTTPS falla, la librería reintenta en HTTP y actualiza esta propiedad a false para el resto de la sesión.
Fallback automático: No necesitas configurarlo. La librería detecta qué puerto responde y lo recuerda.
|
T2bPrinter.enableDebug = true; // activar logs de depuración
Los métodos de descubrimiento devuelven objetos de tipo Printer:
type Printer = {
uid: string; // identificador único (nombre, IP, MAC o ID de plantilla)
name: string; // nombre visible de la impresora
manufacturer: string; // fabricante (ej: "Zebra Technologies")
connection: "driver" | "bluetooth" | "network" | "ttb";
deviceType: string; // normalmente "printer"
version: number; // versión de API del conector
}
Valores de connection:
| Valor | Descripción | Plataforma |
|---|---|---|
| driver | Impresora instalada vía driver del SO | Windows, macOS |
| bluetooth | Conexión Bluetooth | Android, iOS |
| network | Conexión de red (IP / host) | Todas |
| ttb | Conexión a través de Text2 Barcode | Todas |
Sin parámetros. Siempre resuelve, nunca rechaza.
const s = await T2bPrinter.status();
console.log("Disponible:", s.isAvailable); // true si algún puerto responde
console.log("9101 HTTPS:", s.port9101.available);
console.log("9100 HTTP:", s.port9100.available);
console.log("Puerto activo:", s.active); // null si ninguno responde
{
"port9101": { "available": true, "protocol": "https", "port": 9101, "info": { ... } },
"port9100": { "available": false, "protocol": "http", "port": 9100, "info": null },
"active": { "port": 9101, "protocol": "https" },
"isAvailable": true
}
| Campo | Tipo | Descripción |
|---|---|---|
| port9101 / port9100 | object | available (bool), protocol, port, info (JSON del servidor o null) |
| active | { port, protocol } | null | Puerto activo preferido (9101 si responde, si no 9100). null si ninguno responde. |
| isAvailable | boolean | true si al menos un puerto responde. |
Comprueba ambos puertos en paralelo y muestra el estado con indicadores visuales.
Sin parámetros.
const res = await T2bPrinter.available();
for (const p of (res.printer || [])) {
console.log(p.name, p.connection);
}
{
"printer": [
{ "uid": "ZDesigner GK420t Plus (ZPL)", "name": "ZDesigner GK420t Plus (ZPL)",
"manufacturer": "Zebra Technologies", "connection": "driver", "deviceType": "printer", "version": 4 },
{ ... }
]
}
Ejecuta T2bPrinter.available() y muestra la lista completa de impresoras detectadas.
Sin parámetros.
const printer = await T2bPrinter.default();
if (printer) console.log(printer.name);
{
"uid": "ZDesigner GK420t Plus (ZPL)", "name": "ZDesigner GK420t Plus (ZPL)",
"manufacturer": "Zebra Technologies", "connection": "driver",
"deviceType": "printer", "version": 4
}
Ejecuta T2bPrinter.default() y retorna el objeto Printer de la impresora predeterminada del sistema.
| Parámetro | Tipo | Req. | Descripción |
|---|---|---|---|
| predicate | (Printer) => boolean | ✓ | Función que recibe un Printer y retorna true para incluirlo en el resultado. |
const printers = await T2bPrinter.filter(it => it.name.includes("ZPL"));
[
{ "uid": "ZDesigner GK420t Plus (ZPL)", "name": "ZDesigner GK420t Plus (ZPL)",
"manufacturer": "Zebra Technologies", "connection": "driver", "deviceType": "printer", "version": 4 }
]
Filtra impresoras por coincidencia parcial (case-insensitive) en el campo name.
it.name.toLowerCase().includes(texto)null si ninguna coincide.| Parámetro | Tipo | Req. | Descripción |
|---|---|---|---|
| predicate | (Printer) => boolean | ✓ | Función que recibe un Printer y retorna true para seleccionarlo. |
// Por nombre exacto
const p1 = await T2bPrinter.find(it => it.name === "Zebra GK420d");
// Contiene texto
const p2 = await T2bPrinter.find(it => it.name.includes("ZPL"));
// Por tipo de conexión
const p3 = await T2bPrinter.find(it => it.connection === "driver");
{
"uid": "ZDesigner GK420t Plus (ZPL)", "name": "ZDesigner GK420t Plus (ZPL)",
"manufacturer": "Zebra Technologies", "connection": "driver",
"deviceType": "printer", "version": 4
}
Busca la primera impresora que coincida. Elige el campo y el valor para construir el predicado.
it.name === "…"{ device, data } enviado como text/plain.| Parámetro | Tipo | Req. | Descripción |
|---|---|---|---|
| printer | Printer | ✓ | Objeto Printer obtenido con find(), default(), filter(), etc. Debe incluir uid, name y connection. |
| data | string | ✓ |
Contenido del trabajo de impresión: • ZPL: bloque ^XA … ^XZ• ESC/POS: bloque <EscPos> … </EscPos>• TSPL: comandos TSPL para impresoras TSC |
const result = await T2bPrinter.write(printer, `
^XA
^PW609
^LL403
^PON
^CI28
^FO38,30^GB545,349,5^FS
^FO85,60^A0N,33,33^FH^FDZPL PRINT TEST - 3"^FS
^BY2,2,44^FO90,280^BCN,,Y,N
^FD123456789012^FS
^FO465,20^BQN,2,4
^FH\\^FDLA,123456789012^FS
^PQ1,0,1,Y
^XZ
`);
{ "result": true, "message": "messages" }
Selecciona una impresora y edita el contenido a enviar. Las impresoras se cargan al abrir este panel.
FormData con campos json (metadatos del dispositivo) y blob (datos binarios).| Parámetro | Tipo | Req. | Descripción |
|---|---|---|---|
| printer | Printer | ✓ | Objeto Printer destino. Se serializa como JSON en el campo json del FormData. |
| blob | Blob | ✓ | Datos binarios a enviar. Útil para contenido ya compilado (bytes ESC/POS, archivos ZPL desde disco). MIME recomendado: application/octet-stream. |
const zpl = '^XA^FO50,50^A0N,50,50^FDHello^FS^XZ';
const blob = new Blob([zpl], { type: "application/octet-stream" });
const result = await T2bPrinter.writeAsBlob(printer, blob);
{ "result": true, "message": "messages" }
Sube un archivo y lo envía a la impresora como Blob de tipo application/octet-stream.
application/octet-stream.| Parámetro | Tipo | Req. | Descripción |
|---|---|---|---|
| resource | Blob | File | ✓ | Archivo fuente (PNG, JPG o PDF). Puede ser un File de un <input type="file">. |
| payload | object | ✓ | Configuración de la conversión. Ver tabla de opciones abajo. |
payload.options
| Opción | Tipo | Req. | Descripción |
|---|---|---|---|
| action | "print" | "store" | "return" | ✓ |
"print" — convierte e imprime directamente (requiere device)"return" — devuelve el resultado en base64"store" — guarda el archivo en el servidor (requiere storageName)
|
| fromFormat | "png" | "jpg" | "pdf" | ✓ | Formato del archivo fuente. |
| toFormat | "zpl" | "esc-pos" | "tspl" | ✓ | Formato destino de la conversión. |
| resize | { width?, height? } | — | Redimensiona antes de convertir. Puedes pasar solo width o height; el otro lado se calcula proporcionalmente. |
| dithering | string | — |
Algoritmo para conversión a blanco/negro:"FloydSteinbergDithering" — recomendado para fotos"AtkinsonDithering" — patrones más compactos"NoDithering" — umbral simple
|
| storageName | string | — | Nombre del archivo a guardar cuando action es "store". |
payload.device (Printer) — requerido solo cuando action === "print".
const file = document.querySelector('#file-input').files[0];
const result = await T2bPrinter.convert(file, {
options: {
action: "print", // "print" | "return" | "store"
fromFormat: "png", // "png" | "jpg" | "pdf"
toFormat: "zpl", // "zpl" | "esc-pos" | "tspl"
resize: { width: 600 }, // redimensionar (proporcional si solo width/height)
dithering: "FloydSteinbergDithering" // algoritmo de dithering
},
device: printer // requerido si action === "print"
});
{
"data": "base64-encoded ZPL or format",
"width": 600,
"height": 400,
"filename": "converted.zpl"
}
Selecciona una imagen o PDF y configura las opciones. Si action es "print", elige también la impresora destino.
Busca por nombre e imprime un trabajo ZPL.
<!DOCTYPE html>
<html>
<head>
<script src="https://labeldictate.com/text2barcode/lib/t2bprinter.js"></script>
<script>
const printLabel = async () => {
const printerName = "Zebra GK420d";
const labelContent = `
^XA
^PW609
^LL403
^PON
^CI28
^FO85,60^A0N,33,33^FH^FDZPL PRINT TEST - 3"^FS
^BY2,2,44^FO90,280^BCN,,Y,N
^FD123456789012^FS
^FO465,20^BQN,2,4
^FH\\^FDLA,123456789012^FS
^PQ1,0,1,Y
^XZ
`;
try {
const printer = await T2bPrinter.find(it => it.name === printerName);
if (printer) {
const res = await T2bPrinter.write(printer, labelContent);
alert(JSON.stringify(res, null, 2));
} else {
alert(\`Printer "${printerName}" not found.\`);
}
} catch (err) {
alert(err);
}
};
window.onload = printLabel;
</script>
</head>
<body></body>
</html>
Formato XML ESC/POS para impresoras de recibos.
<!DOCTYPE html>
<html>
<head>
<script src="https://labeldictate.com/text2barcode/lib/t2bprinter.js"></script>
<script>
const printLabel = async () => {
const printerName = "Bixolon SRP-330II";
const labelContent = `
<EscPos>
<Init/>
<QrCode justification="right">QR Test Text</QrCode>
<Feed lines="1"/>
<BarCode>1234567890</BarCode>
<Feed lines="1"/>
<Text fontWidth="3" fontHeight="3">Large Text</Text>
<Text fontWidth="2" fontHeight="2">Medium Text</Text>
<Text fontWidth="1" fontHeight="1">Small Text</Text>
<Feed lines="1"/>
<Text justification="left">Left</Text>
<Text justification="center">Center</Text>
<Text justification="right">Right</Text>
<Feed lines="1"/>
<Text underline="one-dot-thick">Underline</Text>
<Text bold="true">Bold</Text>
<Text inverse="true">Inverted</Text>
<Feed lines="3" />
<Cut mode="full" />
</EscPos>
`;
try {
const printer = await T2bPrinter.find(it => it.name === printerName);
if (printer) {
const res = await T2bPrinter.write(printer, labelContent);
alert(JSON.stringify(res, null, 2));
} else {
alert(\`Printer "${printerName}" not found.\`);
}
} catch (err) {
alert(err);
}
};
window.onload = printLabel;
</script>
</head>
<body></body>
</html>
| Síntoma | Qué revisar |
|---|---|
| No aparecen impresoras | Verifica que Text2 Barcode esté corriendo. Usa status() para confirmar conectividad. Revisa permisos del navegador/SO. |
| Nombre no coincide | Llama a available() para ver el nombre real y cópialo exacto, o filtra por uid. |
| Caracteres especiales | En ZPL: asegura ^CI28 para UTF-8. En ESC/POS: verifica las banderas de charset. |
| Impresiones lentas / colas | Evita enviar múltiples trabajos simultáneos. Espera siempre el await de write() antes del siguiente. |