react-to-print
库从我的 Electron 应用程序打印 iframe
。如何使用 iframe
参考来获取要打印的正确窗口/元素?
const handleElectronPrint = async (target: HTMLIFrameElement) {
// Instead of this (printing the whole page)
// let win = BrowserWindow.getFocusedWindow();
// How do I print just the referenced iframe?
// `target` iframe has id="printWindow", how to select it?
let win = BrowserWindow.getMyIframe();
// Is this the right way to do the print once we have the iframe?
const options = { printBackground: true };
win.webContents.print(options, (success, failureReason) => {
if (!success) console.log(failureReason);
console.log('Print Initiated');
});
};
<ReactToPrint
...
print={handleElectronPrint}
/>
您需要将 iframe 对象转换为 Data URL。并将 URL 加载到新的隐藏 BrowserWindow 对象中。
在 Renderer process 中构建数据 URL 并使用 preload 将 URL 发送到主进程。在主进程中执行 BrowserWindow.loadURL 和打印。
App.js
// Send print request to the Main process
this.handlePrint = function (target) {
return new Promise(() => {
console.log('forwarding print request to the main process...');
// convert the iframe into data url
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
let data = target.contentWindow.document.documentElement.outerHTML;
//console.log(data);
var blob = new Blob([data], { type: 'text/html' });
var url = URL.createObjectURL(blob);
window.electronAPI.printComponent(url, (response) => {
console.log('Main: ', response);
});
});
};
main.js
// List of all options at -
// https://www.electronjs.org/docs/latest/api/web-contents#contentsprintoptions-callback
const printOptions = {
silent: false,
printBackground: true,
color: true,
margin: {
marginType: 'printableArea',
},
landscape: false,
pagesPerSheet: 1,
collate: false,
copies: 1,
header: 'Page header',
footer: 'Page footer',
};
ipcMain.handle('printComponent', (event, url) => {
let win = new BrowserWindow({ show: false });
win.loadURL(url);
win.webContents.on('did-finish-load', () => {
win.webContents.print(printOptions, (success, failureReason) => {
console.log('Print Initiated in Main...');
if (!success) console.log(failureReason);
});
});
return 'done in main';
});
预加载.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
printComponent: async (url, callback) => {
let response = await ipcRenderer.invoke('printComponent', url);
callback(response);
},
});
这里是所有打印选项的列表。页面大小、边距、方向等一些选项可以在 CSS @page 规则中设置,请参阅我的演示应用程序中的 App.css。
这是 GitHub 上的演示应用程序electron-react-to-print-demo。
打印预览:由于这些原因,没有Chrome浏览器风格的内置打印预览功能。我们需要实施我们自己的解决方法。例如打印为 PDF 并在新窗口中显示 pdf:
//handle preview
ipcMain.handle('previewComponent', (event, url) => {
let win = new BrowserWindow({ title: 'Preview', show: false, autoHideMenuBar: true });
win.loadURL(url);
win.webContents.once('did-finish-load', () => {
win.webContents.printToPDF(printOptions).then((data) => {
let buf = Buffer.from(data);
var data = buf.toString('base64');
let url = 'data:application/pdf;base64,' + data;
win.webContents.on('ready-to-show', () => {
win.show();
win.setTitle('Preview');
});
win.webContents.on('closed', () => win = null;);
win.loadURL(url);
})
.catch((error) => {
console.log(error);
});
});
return 'shown preview window';
});
我在 electron-react-to-print-demo 中添加了上述预览功能。
补充之前的答案:即使在“show: false”时,以编程方式关闭窗口也是个好主意。它会占用资源。 win?.close();
虽然最小化或隐藏,BrowserWindows 仍然消耗一些系统资源,如内存和处理能力。