Primeros Pasos
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-printer`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/es/docs/plugins/printer/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
Instalar el paquete
Ventana de terminal npm i @Capgo/Capacitor-printerVentana de terminal pnpm add @Capgo/Capacitor-printerVentana de terminal yarn add @Capgo/Capacitor-printerVentana de terminal bun add @Capgo/Capacitor-printer -
Sincronizar con proyectos nativos
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync
Importa el Plugin e imprime varios tipos de contenido:
import { Printer } from '@capgo/capacitor-printer';
// Imprimir contenido HTMLconst printHTML = async () => { await Printer.print({ content: '<h1>Hola Mundo</h1><p>Esta es una impresión de prueba.</p>', name: 'test-print' });};
// Imprimir un archivo PDFconst printPDF = async () => { await Printer.print({ content: 'file:///path/to/document.pdf', name: 'my-document' });};
// Imprimir una imagenconst printImage = async () => { await Printer.print({ content: 'file:///path/to/image.jpg', name: 'my-image' });};Referencia de API
Section titled “Referencia de API”print(Opciones)
Section titled “print(Opciones)”Abre el diálogo de impresión nativo con el contenido especificado.
interface PrintOptions { content: string; // Cadena HTML, URI de archivo o datos base64 name?: string; // Nombre del trabajo de impresión orientation?: 'portrait' | 'landscape'; grayscale?: boolean; // Imprimir en escala de grises (por defecto: false)}
await Printer.print(options);canPrint()
Section titled “canPrint()”Verifica si la impresión está disponible en el dispositivo.
const { value } = await Printer.canPrint();console.log('Impresión disponible:', value);Ejemplo Completo
Section titled “Ejemplo Completo”import { Printer } from '@capgo/capacitor-printer';import { Filesystem, Directory } from '@capacitor/filesystem';
export class PrintService { async checkPrintAvailability(): Promise<boolean> { const { value } = await Printer.canPrint(); return value; }
async printHTML(htmlContent: string, jobName: string = 'Document') { try { const canPrint = await this.checkPrintAvailability(); if (!canPrint) { throw new Error('La impresión no está disponible en este dispositivo'); }
await Printer.print({ content: htmlContent, name: jobName, orientation: 'portrait' }); } catch (error) { console.error('Impresión fallida:', error); throw error; } }
async printDocument(filePath: string, jobName?: string) { await Printer.print({ content: filePath, name: jobName || 'Document' }); }
async printReceipt(receiptData: any) { const html = ` <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; padding: 20px; } .header { text-align: center; margin-bottom: 20px; } .item { display: flex; justify-content: space-between; margin: 10px 0; } .total { font-weight: bold; font-size: 1.2em; margin-top: 20px; padding-top: 10px; border-top: 2px solid #000; } </style> </head> <body> <div class="header"> <h2>Recibo</h2> <p>Fecha: ${new Date().toLocaleDateString()}</p> </div> ${receiptData.items.map((item: any) => ` <div class="item"> <span>${item.name}</span> <span>$${item.price.toFixed(2)}</span> </div> `).join('')} <div class="total"> <div class="item"> <span>Total:</span> <span>$${receiptData.total.toFixed(2)}</span> </div> </div> </body> </html> `;
await this.printHTML(html, 'Receipt'); }
async printFromURL(url: string) { // Descargar el archivo primero const response = await fetch(url); const blob = await response.blob(); const reader = new FileReader();
return new Promise((resolve, reject) => { reader.onloadend = async () => { try { await Printer.print({ content: reader.result as string, name: 'Downloaded Document' }); resolve(true); } catch (error) { reject(error); } }; reader.onerror = reject; reader.readAsDataURL(blob); }); }}Uso Avanzado
Section titled “Uso Avanzado”Impresión con Estilo Personalizado
Section titled “Impresión con Estilo Personalizado”const printStyledDocument = async () => { const html = ` <!DOCTYPE html> <html> <head> <style> @page { size: A4; margin: 2cm; } body { font-family: 'Times New Roman', serif; line-height: 1.6; } h1 { color: #333; border-bottom: 2px solid #333; padding-bottom: 10px; } .content { margin-top: 20px; } </style> </head> <body> <h1>Documento Profesional</h1> <div class="content"> <p>Este es un documento con estilo profesional listo para imprimir.</p> </div> </body> </html> `;
await Printer.print({ content: html, name: 'Styled Document', orientation: 'portrait' });};Impresión de Tablas
Section titled “Impresión de Tablas”const printTable = async (data: any[]) => { const tableRows = data.map(row => ` <tr> <td>${row.id}</td> <td>${row.name}</td> <td>${row.value}</td> </tr> `).join('');
const html = ` <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; font-weight: bold; } </style> </head> <body> <table> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Valor</th> </tr> </thead> <tbody> ${tableRows} </tbody> </table> </body> </html> `;
await Printer.print({ content: html, name: 'Data Table' });};Impresión de Imágenes
Section titled “Impresión de Imágenes”const printImageWithDetails = async (imagePath: string, title: string) => { const html = ` <!DOCTYPE html> <html> <head> <style> body { text-align: center; padding: 20px; } h2 { margin-bottom: 20px; } img { max-width: 100%; height: auto; } </style> </head> <body> <h2>${title}</h2> <img src="${imagePath}" alt="${title}" /> </body> </html> `;
await Printer.print({ content: html, name: title });};Mejores Prácticas
Section titled “Mejores Prácticas”- Verificar Disponibilidad: Siempre verifica si la impresión está disponible antes de intentar imprimir
- Contenido Válido: Asegúrate de que el HTML esté bien formado y las rutas de archivo sean válidas
- Nombres de Trabajo: Usa nombres descriptivos para trabajos de impresión para ayudar a los usuarios a identificarlos
- Estilización: Usa CSS en línea o estilos embebidos para salida de impresión consistente
- Manejo de Errores: Envuelve las llamadas de impresión en bloques try-catch para retroalimentación al usuario
Solución de Problemas
Section titled “Solución de Problemas”Problemas Comunes
Section titled “Problemas Comunes”El diálogo de impresión no aparece: Verifica que la impresión esté disponible con canPrint() El contenido no se imprime: Verifica que el HTML sea válido y las rutas de archivo sean correctas Las imágenes no se muestran: Asegúrate de que las rutas de imagen sean absolutas y los archivos sean accesibles Problemas de estilo: Usa reglas CSS @page y prueba la salida de impresión