我最近发布了NPM软件包,用于从Node.js和Electron打印PDF文件。您可以将PDF文件发送到默认打印机或特定打印机。在Windows和类似Unix的操作系统上可以正常工作:https : //github.com/artiebits/pdf-to-printer。
它很容易安装,只要(如果使用yarn):
yarn add pdf-to-printer
Run Code Online (Sandbox Code Playgroud)
或(如果使用npm):
npm install --save pdf-to-printer
Run Code Online (Sandbox Code Playgroud)
然后,要将文件以静默方式打印到默认打印机,请执行以下操作:
import printer from "pdf-to-printer";
printer
.print("assets/pdf-sample.pdf")
.then(console.log)
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
首先,几乎不可能理解"静音"印刷的含义.因为一旦您向系统打印机发送打印指令,根本不会保持沉默.在Windows上,例如,一旦给出订单,至少系统托盘图标将指示正在发生的事情.也就是说,用电子打印有很好的描述功能,即使是"静音"也是其中之一:
如果您不想使用默认打印机,则需要获取所有系统打印机:
contents.getPrinters()
Run Code Online (Sandbox Code Playgroud)
哪个会返回一个PrinterInfo[]Object.
以下是电子PrtinerInfo文档中对象的外观示例:
{
name: 'Zebra_LP2844',
description: 'Zebra LP2844',
status: 3,
isDefault: false,
options: {
copies: '1',
'device-uri': 'usb://Zebra/LP2844?location=14200000',
finishings: '3',
'job-cancel-after': '10800',
'job-hold-until': 'no-hold',
'job-priority': '50',
'job-sheets': 'none,none',
'marker-change-time': '0',
'number-up': '1',
'printer-commands': 'none',
'printer-info': 'Zebra LP2844',
'printer-is-accepting-jobs': 'true',
'printer-is-shared': 'true',
'printer-location': '',
'printer-make-and-model': 'Zebra EPL2 Label Printer',
'printer-state': '3',
'printer-state-change-time': '1484872644',
'printer-state-reasons': 'offline-report',
'printer-type': '36932',
'printer-uri-supported': 'ipp://localhost/printers/Zebra_LP2844',
system_driverinfo: 'Z'
}
}
Run Code Online (Sandbox Code Playgroud)
要打印文件,您可以使用它
contents.print([options])
Run Code Online (Sandbox Code Playgroud)
这些选项在contents.print()的文档中进行了描述:
打印窗口的网页.当silent设置为true时,Electron将选择系统的默认打印机(如果deviceName为空)和打印的默认设置.
window.print()在网页中调用等同于调用webContents.print({silent: false, printBackground: false, deviceName: ''}).
使用page-break-before: always;CSS样式强制打印到新页面.
因此,您只需将PDF加载到隐藏窗口中,然后在标记设置为静音的情况下触发在电子中实现的打印方法.
// In the main process.
const {app, BrowserWindow} = require('electron');
let win = null;
app.on('ready', () => {
// Create window
win = new BrowserWindow({width: 800, height: 600, show: false });
// Could be redundant, try if you need this.
win.once('ready-to-show', () => win.hide())
// load PDF.
win.loadURL(`file://directory/to/pdf/document.pdf`);
// if pdf is loaded start printing.
win.webContents.on('did-finish-load', () => {
win.webContents.print({silent: true});
// close window after print order.
win = null;
});
});
Run Code Online (Sandbox Code Playgroud)
但是,让我给你一点警告:一旦你开始打印,它会变得令人沮丧,因为那里有驱动程序会以稍微不同的方式解释数据.这意味着可以忽略边际等等.由于您已经拥有PDF,因此很可能不会发生此问题.但是,如果您想要使用此方法 ,请记住这一点contents.printToPDF(options, callback).有人说,有很多选项可以避免像使用这个问题中描述的预定义样式表一样受挫:打印:如何在每个页面底部粘贴页脚?
如果你想搜索电子中的特征而你不知道它们可以隐藏在哪里,你所要做的就是去"所有"文档并使用你的搜索功能:https://electron.atom.io/docs /所有/
问候,Megajin
| 归档时间: |
|
| 查看次数: |
12420 次 |
| 最近记录: |