Skip to main content

Overview

The usePrint composable provides printing functionality for Vue 3 Composition API. It returns a set of functions for printing elements, checking bridge status, and managing printers.

Type Signature

function usePrint(): {
  print: (element: HTMLElement | string, options?: PrintOptions) => Promise<void>;
  getBridgeStatus: () => Promise<BridgeHealthResponse | null>;
  getAvailablePrinters: () => Promise<BridgePrinter[]>;
  printDirect: (content: string, options?: Partial<BridgePrintRequest>) => Promise<BridgePrintResponse>;
}

Returns

print
function
Main printing functionParameters:
  • element (HTMLElement | string): Element to print or element ID
  • options (PrintOptions, optional): Print configuration options
Returns: Promise<void>
getBridgeStatus
function
Get bridge service health status (requires bridge plugin)Returns: Promise<BridgeHealthResponse | null>Returns null if bridge plugin is not installed or unavailable.
getAvailablePrinters
function
Get list of available printers (requires bridge plugin)Returns: Promise<BridgePrinter[]>Returns empty array if bridge plugin is not installed or unavailable.
printDirect
function
Print content directly to a printer (requires bridge plugin)Parameters:
  • content (string): HTML content to print
  • options (Partial<BridgePrintRequest>, optional): Bridge print options
Returns: Promise<BridgePrintResponse>Throws error if bridge plugin is not installed or unavailable.
The print function accepts the following options:
name
string
default:"_blank"
Window name for the print window
specs
string[] | { width?: number; height?: number }
Window specifications as array of strings or object with dimensionsDefault: ['fullscreen=yes', 'titlebar=yes', 'scrollbars=yes']
styles
string[]
default:"[]"
Array of custom CSS styles to apply. Can be CSS strings or URLs to stylesheets
timeout
number
default:"1000"
Delay in milliseconds before printing starts
autoClose
boolean
default:"true"
Whether to automatically close the print window after printing
windowTitle
string
Title for the print window (defaults to current document title)
preserveStyles
boolean
default:"true"
Whether to preserve original page styles in the print output
onBeforePrint
() => void | Promise<void>
Callback executed before printing starts
onAfterPrint
() => void | Promise<void>
Callback executed after printing completes
onPrintError
(error: Error) => void
Callback executed when a print error occurs
useBridge
boolean
default:"false"
Whether to use bridge for direct printing (requires bridge plugin)
printerName
string
Name of the printer to use with bridge (auto-selects default if not specified)
copies
number
default:"1"
Number of copies to print (bridge only)
contentType
'html' | 'pdf'
default:"html"
Content type for bridge printing

Usage

Basic Usage

<template>
  <div>
    <div id="invoice">
      <h1>Invoice #12345</h1>
      <p>Amount: $1,234.56</p>
    </div>
    <button @click="handlePrint">Print Invoice</button>
  </div>
</template>

<script setup>
import { usePrint } from 'vue-print-it'

const { print } = usePrint()

const handlePrint = async () => {
  try {
    await print('invoice')
  } catch (error) {
    console.error('Print failed:', error)
  }
}
</script>

Using Element Reference

<template>
  <div>
    <div ref="contentRef">
      <h1>Content to print</h1>
    </div>
    <button @click="handlePrint">Print</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { usePrint } from 'vue-print-it'

const contentRef = ref<HTMLElement>()
const { print } = usePrint()

const handlePrint = async () => {
  if (contentRef.value) {
    await print(contentRef.value, {
      windowTitle: 'My Document'
    })
  }
}
</script>

With Custom Styles

<script setup>
import { usePrint } from 'vue-print-it'

const { print } = usePrint()

const handlePrint = async () => {
  await print('content', {
    styles: [
      // External stylesheet
      'https://cdn.example.com/print-styles.css',
      // Inline CSS
      `
        @media print {
          body { font-family: Arial, sans-serif; }
          h1 { color: #333; }
          .no-print { display: none; }
        }
      `
    ],
    preserveStyles: true
  })
}
</script>

With Lifecycle Callbacks

<script setup>
import { ref } from 'vue'
import { usePrint } from 'vue-print-it'

const { print } = usePrint()
const isPrinting = ref(false)

const handlePrint = async () => {
  await print('content', {
    onBeforePrint: async () => {
      console.log('Preparing to print...')
      isPrinting.value = true
      // Perform any pre-print operations
    },
    onAfterPrint: async () => {
      console.log('Print completed')
      isPrinting.value = false
      // Perform any post-print operations
    },
    onPrintError: (error) => {
      console.error('Print error:', error)
      isPrinting.value = false
      alert('Failed to print: ' + error.message)
    }
  })
}
</script>

Window Configuration

<script setup>
import { usePrint } from 'vue-print-it'

const { print } = usePrint()

const handlePrint = async () => {
  await print('content', {
    specs: {
      width: 800,
      height: 600
    },
    // Or use array format
    // specs: ['width=800', 'height=600', 'scrollbars=yes'],
    autoClose: false, // Keep window open after print
    timeout: 1500 // Wait 1.5s before printing
  })
}
</script>

Bridge Plugin Integration

Bridge methods require the bridge plugin to be installed. See Bridge Installation for setup instructions.
<script setup>
import { ref, onMounted } from 'vue'
import { usePrint } from 'vue-print-it'

const { print, getBridgeStatus, getAvailablePrinters } = usePrint()
const printers = ref([])
const bridgeAvailable = ref(false)

onMounted(async () => {
  // Check bridge status
  const status = await getBridgeStatus()
  bridgeAvailable.value = status !== null
  
  if (bridgeAvailable.value) {
    // Get available printers
    printers.value = await getAvailablePrinters()
  }
})

const handlePrintWithBridge = async (printerName: string) => {
  await print('content', {
    useBridge: true,
    printerName: printerName,
    copies: 2,
    contentType: 'html'
  })
}
</script>

<template>
  <div>
    <div v-if="bridgeAvailable">
      <h3>Available Printers</h3>
      <button 
        v-for="printer in printers" 
        :key="printer.name"
        @click="handlePrintWithBridge(printer.name)"
      >
        {{ printer.name }} {{ printer.is_default ? '(Default)' : '' }}
      </button>
    </div>
    <p v-else>Bridge not available. Using browser print.</p>
  </div>
</template>

Direct Printing

Print HTML content directly without referencing a DOM element:
<script setup>
import { usePrint } from 'vue-print-it'

const { printDirect } = usePrint()

const handlePrintDirect = async () => {
  try {
    const htmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <title>Direct Print</title>
          <style>
            body { font-family: Arial, sans-serif; }
          </style>
        </head>
        <body>
          <h1>Direct Print Content</h1>
          <p>This is printed directly to the printer.</p>
        </body>
      </html>
    `
    
    const result = await printDirect(htmlContent, {
      printer_name: 'HP LaserJet',
      content_type: 'html',
      copies: 1
    })
    
    console.log('Print job ID:', result.job_id)
    console.log('Message:', result.message)
  } catch (error) {
    console.error('Direct print failed:', error)
  }
}
</script>

TypeScript Support

import { usePrint } from 'vue-print-it'
import type { PrintOptions, BridgePrinter } from 'vue-print-it'

const { print, getAvailablePrinters } = usePrint()

const printOptions: PrintOptions = {
  windowTitle: 'My Print',
  autoClose: true,
  timeout: 1000,
  styles: ['body { color: black; }'],
  onBeforePrint: async () => {
    console.log('Starting print...')
  }
}

await print('element-id', printOptions)

const printers: BridgePrinter[] = await getAvailablePrinters()

Behavior Notes

  • If the plugin is installed with global options, usePrint will use those global settings
  • Local options passed to the print function override global options
  • If no global plugin is installed, usePrint creates a local print function instance
  • Bridge methods (getBridgeStatus, getAvailablePrinters, printDirect) only work if the bridge plugin is installed
  • The print function automatically falls back to browser printing if bridge is unavailable or useBridge is false

See Also

Build docs developers (and LLMs) love