Skip to main content

Overview

Vue Print It is written in TypeScript and provides complete type definitions for all interfaces, options, and methods. This ensures type safety and excellent IDE autocomplete support.

Type Imports

Import types from the main package:
import type {
  PrintOptions,
  GlobalPrintOptions,
  BridgePluginOptions,
  BridgePrinter,
  BridgePrintRequest,
  BridgePrintResponse,
  BridgeHealthResponse,
  PrintInstance,
  PrintStore
} from 'vue-print-it'

Core Type Definitions

PrintOptions

Configuration options for individual print operations:
interface PrintOptions {
  /** Window name for the print window (default: '_blank') */
  name?: string
  
  /** Window specifications as array of strings or object with width/height */
  specs?: string[] | { width?: number; height?: number }
  
  /** Array of custom CSS styles to apply */
  styles?: string[]
  
  /** Delay in milliseconds before printing (default: 1000) */
  timeout?: number
  
  /** Whether to automatically close the print window (default: true) */
  autoClose?: boolean
  
  /** Title for the print window */
  windowTitle?: string
  
  /** Whether to preserve original page styles (default: true) */
  preserveStyles?: boolean
  
  /** Callback executed before printing starts */
  onBeforePrint?: () => void | Promise<void>
  
  /** Callback executed after printing completes */
  onAfterPrint?: () => void | Promise<void>
  
  /** Callback executed when print error occurs */
  onPrintError?: (error: Error) => void
  
  /** Whether to use bridge for direct printing (requires bridge plugin) */
  useBridge?: boolean
  
  /** Name of the printer to use with bridge */
  printerName?: string
  
  /** Number of copies to print */
  copies?: number
  
  /** Content type for bridge printing */
  contentType?: 'html' | 'pdf'
}

GlobalPrintOptions

Global configuration options for the print plugin:
interface GlobalPrintOptions {
  /** Window name for the print window (default: '_blank') */
  name?: string
  
  /** Window specifications as array of strings or object with width/height */
  specs?: string[] | { width?: number; height?: number }
  
  /** Array of custom CSS styles to apply */
  styles?: string[]
  
  /** Delay in milliseconds before printing (default: 1000) */
  timeout?: number
  
  /** Whether to automatically close the print window (default: true) */
  autoClose?: boolean
  
  /** Title for the print window */
  windowTitle?: string
  
  /** Whether to preserve original page styles (default: true) */
  preserveStyles?: boolean
}

BridgePluginOptions

Configuration options for the bridge plugin extension:
interface BridgePluginOptions {
  /** Base URL of the bridge service (default: 'http://localhost:8765') */
  baseUrl?: string
  
  /** Port number for the bridge service (default: 8765) */
  port?: number
  
  /** Whether to automatically connect on plugin installation (default: false) */
  autoConnect?: boolean
  
  /** Whether to automatically select a default printer (default: true) */
  autoSelectDefault?: boolean
  
  /** Connection timeout in milliseconds (default: 2000) */
  timeout?: number
  
  /** Number of retry attempts for failed connections (default: 3) */
  retryAttempts?: number
  
  /** Default printer name to use (optional - will auto-select if not provided) */
  defaultPrinter?: string
  
  /** Custom headers to send with bridge requests */
  headers?: Record<string, string>
  
  /** Enable debug logging for bridge operations */
  debug?: boolean
}

Bridge Type Definitions

BridgePrinter

Printer information from the bridge service:
interface BridgePrinter {
  name: string
  is_default: boolean
  status: string
}

BridgePrintRequest

Request payload for bridge printing:
interface BridgePrintRequest {
  printer_name?: string
  content: string
  content_type: 'html' | 'pdf'
  copies?: number
  options?: Record<string, any>
}

BridgePrintResponse

Response from bridge print operation:
interface BridgePrintResponse {
  success: boolean
  job_id: string
  message: string
}

BridgeHealthResponse

Bridge service health status:
interface BridgeHealthResponse {
  status: string
  version: string
  uptime: number
}

TypeScript Usage Examples

Plugin Installation with Types

import { createApp } from 'vue'
import { createVuePrintIt, createVuePrintItBridge } from 'vue-print-it'
import type { GlobalPrintOptions, BridgePluginOptions } from 'vue-print-it'
import App from './App.vue'

const app = createApp(App)

// Global print options with type safety
const printOptions: GlobalPrintOptions = {
  windowTitle: 'My App Print',
  autoClose: true,
  timeout: 1500,
  preserveStyles: true,
  styles: [
    'body { font-family: Arial, sans-serif; }',
    '@media print { .no-print { display: none; } }'
  ]
}

// Bridge options with type safety
const bridgeOptions: BridgePluginOptions = {
  baseUrl: 'http://localhost:8765',
  autoConnect: true,
  autoSelectDefault: true,
  timeout: 3000,
  retryAttempts: 5,
  debug: true
}

app.use(createVuePrintIt(printOptions))
app.use(createVuePrintItBridge(bridgeOptions))

app.mount('#app')

Composable with Types

<script setup lang="ts">
import { ref } from 'vue'
import { usePrint } from 'vue-print-it'
import type { PrintOptions, BridgePrintResponse } from 'vue-print-it'

const { print, getBridgeStatus, getAvailablePrinters, printDirect } = usePrint()

const printContent = async () => {
  const options: PrintOptions = {
    windowTitle: 'Invoice #12345',
    autoClose: true,
    preserveStyles: true,
    onBeforePrint: async () => {
      console.log('Preparing to print...')
    },
    onAfterPrint: async () => {
      console.log('Print completed')
    },
    onPrintError: (error: Error) => {
      console.error('Print failed:', error.message)
    }
  }
  
  await print('invoice', options)
}

const printWithBridge = async () => {
  const options: PrintOptions = {
    useBridge: true,
    printerName: 'HP LaserJet Pro',
    copies: 2,
    contentType: 'html'
  }
  
  await print('invoice', options)
}

const checkBridgeStatus = async () => {
  const status = await getBridgeStatus()
  if (status) {
    console.log(`Bridge version: ${status.version}`)
    console.log(`Uptime: ${status.uptime}s`)
  }
}

const listPrinters = async () => {
  const printers = await getAvailablePrinters()
  printers.forEach(printer => {
    console.log(`${printer.name} (${printer.status})${printer.is_default ? ' [DEFAULT]' : ''}`)
  })
}

const directPrint = async () => {
  const htmlContent = '<h1>Direct Print</h1><p>This is printed directly.</p>'
  
  const response: BridgePrintResponse = await printDirect(htmlContent, {
    printer_name: 'HP LaserJet Pro',
    content_type: 'html',
    copies: 1
  })
  
  console.log(`Print job ID: ${response.job_id}`)
}
</script>

Bridge Plugin Composable with Types

<script setup lang="ts">
import { onMounted } from 'vue'
import { usePrintBridge } from 'vue-print-it'
import type { BridgePrinter } from 'vue-print-it'

const {
  bridgeClient,
  bridgeState,
  isAvailable,
  refreshPrinters,
  setDefaultPrinter,
  getDefaultPrinter,
  checkConnection
} = usePrintBridge()

onMounted(async () => {
  const connected = await checkConnection()
  
  if (connected) {
    await refreshPrinters()
    
    if (bridgeState) {
      console.log(`Connected: ${bridgeState.isConnected}`)
      console.log(`Available printers: ${bridgeState.availablePrinters.length}`)
      console.log(`Default printer: ${bridgeState.defaultPrinter}`)
    }
  }
})

const selectPrinter = (printer: BridgePrinter) => {
  const success = setDefaultPrinter(printer.name)
  if (success) {
    console.log(`Default printer set to: ${printer.name}`)
  }
}

const getCurrentPrinter = () => {
  const printer = getDefaultPrinter()
  console.log(`Current default: ${printer || 'None selected'}`)
}
</script>

<template>
  <div v-if="bridgeState">
    <p>Status: {{ bridgeState.isConnected ? 'Connected' : 'Disconnected' }}</p>
    <p>Default: {{ bridgeState.defaultPrinter || 'None' }}</p>
    
    <ul>
      <li v-for="printer in bridgeState.availablePrinters" :key="printer.name">
        {{ printer.name }}
        <button @click="selectPrinter(printer)">Select</button>
      </li>
    </ul>
  </div>
</template>

Global Methods with Types

import { getCurrentInstance } from 'vue'
import type { PrintInstance } from 'vue-print-it'

export default {
  setup() {
    const instance = getCurrentInstance()
    const $print = instance?.appContext.config.globalProperties.$print as PrintInstance
    
    const handlePrint = async () => {
      await $print.print('content', {
        windowTitle: 'Document',
        autoClose: true
      })
    }
    
    return { handlePrint }
  }
}

Advanced Type Usage

Custom Type Extensions

Extend the types for custom configurations:
import type { PrintOptions } from 'vue-print-it'

interface CustomPrintOptions extends PrintOptions {
  metadata?: {
    documentId: string
    userId: string
    timestamp: Date
  }
  branding?: {
    logo: string
    companyName: string
  }
}

const printWithMetadata = async (elementId: string, options: CustomPrintOptions) => {
  // Your custom print logic with extended options
  console.log('Metadata:', options.metadata)
}

Type Guards

Create type guards for runtime type checking:
import type { BridgePrintResponse } from 'vue-print-it'

function isBridgePrintResponse(obj: any): obj is BridgePrintResponse {
  return (
    typeof obj === 'object' &&
    typeof obj.success === 'boolean' &&
    typeof obj.job_id === 'string' &&
    typeof obj.message === 'string'
  )
}

const response = await someAsyncOperation()
if (isBridgePrintResponse(response)) {
  console.log(`Job ID: ${response.job_id}`)
}

Next Steps

Bridge Setup

Learn how to set up and configure the bridge plugin

Configuration

Explore all configuration options in detail

Build docs developers (and LLMs) love