首页 > 解决方案 > 使用 electron.js 打印当前的 vue-view

问题描述

使用electron时如何打印vue渲染的当前网页视图?正常的 js 函数window.print()打印为空。那么什么是电子方式呢?是否有可能在不转换为 .pdf 的情况下进行静默打印?

标签: javascriptvue.jselectron

解决方案


要打印当前窗口,请使用以下代码

let win = BrowserWindow.getFocusedWindow(); 

或者

 let win = BrowserWindow.getAllWindows()[0]; 

打印

  win.webContents.print(options, (success, failureReason) => { 
            if (!success) console.log(failureReason); 
      
            console.log('Print Initiated'); 
        }); 
    }); 

全码:

const electron = require('electron') 
const BrowserWindow = electron.remote.BrowserWindow; 
  
var current = document.getElementById('current');  
var options = { 
    silent: false, 
    printBackground: true, 
    color: false, 
    landscape: false, 
    pagesPerSheet: 1, 
    collate: false, 
    copies: 1, 
    header: 'Header of the Page', 
    footer: 'Footer of the Page'
} 
  
current.addEventListener('click', (event) => { 
    let win = BrowserWindow.getFocusedWindow(); 
    
  
    win.webContents.print(options, (success, failureReason) => { 
        if (!success) console.log(failureReason); 
  
        console.log('Print Initiated'); 
    }); 
}); 

推荐阅读