Vue Print Next

repository·master·Indexed 41 days ago

https://github.com/alessandro-pang/vue-print-next

A lightweight printing plugin for Vue 2 and Vue 3 providing a directive wrapper for simple and fast printing. It supports directive-based and class-based manual printing via the VuePrintNext class, featuring print previews, custom paper sizes (A0-A8, Letter, Legal, Tabloid), orientation control, and the ability to exclude specific elements using noPrintSelector.

Tokens
18.1K
Snippets
64
Records
79
Agent score
47%

What's inside Vue Print Next

  1. Overview of Vue Print Next

    master

    Vue Print Next is an efficient and flexible printing solution for Vue applications. It supports both Vue 2 and Vue 3, providing a seamless transition for projects upgrading or using mixed Vue versions.

    Key Features

    • Simple Integration: Easy to use via global plugin registration or local directive calls.
    • Efficient Printing: Supports high-speed document generation and real-time print previews.
    • Flexible Configuration: Rich parameters for configuring document types, print previews, and ignoring specific elements.
    • TypeScript Support: Full type definitions and intelligent code completion.
    • URL Printing: Ability to print content from a specific URL, including handling asynchronous loading and cross-origin resources.
    • Detailed Style Control: Supports additional CSS and <head> content injection to ensure print layouts match design requirements.
    • Print Content Inspection: Built-in preview functionality to verify content before actual printing.
  2. Overview of VuePrintNext

    master

    VuePrintNext is a lightweight Vue printing plugin compatible with both Vue 2 and Vue 3. It is a TypeScript-based rewrite/improvement of vue3-print-nb, designed to provide better support and extensibility for Vue 3 environments.

    Key Capabilities:

    • Dual Compatibility: Works seamlessly in Vue 2 and Vue 3 via directives or API calls.
    • Flexible Printing Modes: Supports full-page printing and targeted partial-page (local) printing.
    • Print Preview: Allows users to preview content before sending it to the printer.
    • Style Customization:
      • Use extraCss to inject additional styles for the print job.
      • Use noPrintSelector to exclude specific elements from the print output.
    • Targeting Methods: Specify print areas using either DOM nodes or CSS selectors.
    • Remote Content: Supports printing content from a remote URL with asynchronous loading capabilities.
  3. Use VuePrintNext in non-Vue environments

    master
    VuePrintNext is implemented as a pure JavaScript class and is framework-agnostic. You can use it in other frameworks or vanilla JavaScript environments by calling the VuePrintNext class directly. Note that the Vue-specific directive (v-print) and plugin modes will not be available in these environments; you must use the API calls.
  4. Use lifecycle hooks in VuePrintNext

    master
    VuePrintNext provides a series of lifecycle hooks that allow you to execute custom logic at different stages of the printing process. These hooks can be defined within your print configuration object. They are useful for data processing, logging user interactions, or modifying DOM structures and styles before or after the print window/preview opens.
  5. Customize the print preview interface

    master

    The preview interface can be customized using several parameters:

    • preview: Boolean to enable/disable preview mode.
    • darkMode: Boolean to enable dark mode in the preview.
    • windowMode: Boolean to use a popup mode instead of fullscreen.
    • defaultScale: Number to set the default zoom ratio (e.g., 0.8 for 80%).
    • previewTools: Object to toggle specific toolbar buttons:
      • zoom: Boolean
      • theme: Boolean
      • fullscreen: Boolean
    const printObj = {
      el: '#printMe',
      preview: true,
      darkMode: true,
      windowMode: true,
      defaultScale: 0.8,
      previewTools: {
        zoom: true,
        theme: true,
        fullscreen: false
      }
    }
  6. How custom printing works in Vue3

    master

    Custom printing in a Vue3 environment (and web applications in general) is achieved by isolating the content to be printed into a separate execution context, such as an iframe or a new browser window, and then invoking the native window.print() method.

    The core workflow involves:

    1. Identifying the target area: Using a CSS selector or a direct DOM element.
    2. Cloning the content: Performing a deep clone of the target element to prevent dynamic changes in the main UI from affecting the print job and to allow for modifications (like removing elements with a .no-print class).
    3. Creating a new context: Spawning a hidden iframe or a new window to host the cloned content.
    4. Restoring styles: Injecting the original page's CSS links and <style> rules into the new context so the printed output matches the visual design.
    5. Triggering the print: Calling window.print() once the new context has loaded, and subsequently cleaning up the temporary iframe or window to prevent memory leaks.
  7. Configure paper size and orientation

    master

    Control the physical print properties using paperSize and orientation.

    Standard Sizes:

    • paperSize: Set to 'A4', 'A3', etc.
    • orientation: Set to 'portrait' or 'landscape'.

    Custom Sizes: Set paperSize to 'custom' and provide a customSize object.

    Custom Size Object Schema:

    • width: Number
    • height: Number
    • unit: 'mm', 'cm', 'in', or 'px'
    // Standard A4 Landscape
    const printObj = {
      el: '#printMe',
      paperSize: 'A4',
      orientation: 'landscape',
      preview: true
    }
    
    // Custom Size
    const printObj = {
      el: '#printMe',
      paperSize: 'custom',
      customSize: {
        width: '100',
        height: '150',
        unit: 'mm'
      },
      preview: true
    }
  8. Restrict user interaction in preview mode

    master

    You can selectively disable features to control how users interact with the preview. For example, to disable zooming while keeping theme and fullscreen options available:

    useVuePrintNext({
      el: '#print-content',
      preview: true,
      previewTools: {
        zoom: false,    // 禁用缩放
        theme: true,    // 允许切换主题
        fullscreen: true // 允许全屏切换
      }
    });

    Note: Even if all tool buttons are hidden, the close button will always remain visible so users can exit the preview window. Additionally, disabling a button only removes the UI toggle; you can still set the initial state of these features using other configuration options like darkMode, windowMode, or defaultScale.

    useVuePrintNext({
      el: '#print-content',
      preview: true,
      previewTools: {
        zoom: false,
        theme: true,
        fullscreen: true
      }
    });
  9. Setup vue-print-next in a Vue 3 project

    master

    To use vue-print-next in Vue 3, register the printPlugin globally in your main.ts (or main.js) file. Once registered, you can use the v-print directive in your components to print either the entire page or specific elements by passing a CSS selector.

    // 1. Global Registration in main.ts
    import { createApp } from 'vue';
    import App from './App.vue';
    import { printPlugin } from 'vue-print-next';
    
    const app = createApp(App);
    app.use(printPlugin);
    app.mount('#app');
    <!-- 2. Usage in Component -->
    <template>
      <div>
        <!-- Prints the entire page -->
        <button v-print>打印整个页面</button>
        
        <!-- Prints the element with ID 'printMe' -->
        <button v-print="'#printMe'">打印局部内容</button>
        
        <div id="printMe">
          <p>这是需要打印的局部内容</p>
          <p>更多内容...</p>
        </div>
      </div>
    </template>
  10. Migrate from vue-print-nb to vue-print-next

    master

    If you are migrating from vue-print-nb or vue3-print-nb, vue-print-next is a complete rewrite that offers better TypeScript support, full Vue 3 Composition API support, and enhanced printing features like custom paper sizes and dark mode.

    Key changes to note:

    1. The id parameter is renamed to el (supports both CSS selectors and HTMLElement).
    2. Import paths have changed: use printPlugin, vPrint, or VuePrintNext from vue-print-next.
    3. The standard parameter now accepts 'strict' | 'loose' | 'html5' (defaults to 'html5').
    npm install vue-print-next --save
    # or
    yarn add vue-print-next
    # or
    pnpm add vue-print-next