Electron JS中PDF下载与打印功能失效问题求助
Hey there, let's tackle your Electron PDF download and printing problems step by step. I've looked at your code snippets, and the issues mainly stem from unhandled new window behavior and missing webPreferences configurations. Here's how to fix them:
1. Fixing PDF Download Not Responding
Your <a> tag uses target="_blank", which triggers a new window in Electron—but your main process doesn't handle this event, so the PDF doesn't load properly for download. Here are two solutions:
Option A: Handle new-window Event in Main Process
Update your main.js to listen for new window requests, create a proper window for PDFs, and manage downloads:
const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const shell = electron.shell; // Required for download handling and system actions let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ maximizable:true, closable: true, skipTaskbar: true, frame: true, autoHideMenuBar: false, kiosk: true, title: 'HR HUB', titleBarStyle:"default", webPreferences: { devTools: false, contextIsolation: false, // Explicitly set for Electron 9.x compatibility nodeIntegration: true } }); mainWindow.loadURL(`file://${__dirname}/index.html`); // Handle links with target="_blank" mainWindow.webContents.on('new-window', (event, url) => { event.preventDefault(); // Stop default unhandled window creation if (url.endsWith('.pdf')) { // Create a dedicated window for PDF viewing/download const pdfWindow = new BrowserWindow({ webPreferences: { devTools: false, contextIsolation: false } }); pdfWindow.loadURL(url); // Manage PDF download pdfWindow.webContents.session.on('will-download', (event, item) => { const savePath = `${app.getPath('downloads')}/${item.getFilename()}`; item.setSavePath(savePath); item.on('done', (event, state) => { if (state === 'completed') { console.log('PDF downloaded successfully!'); shell.showItemInFolder(savePath); // Open download folder for user } else { console.error(`Download failed: ${state}`); } }); }); } else { // Open non-PDF links in system default browser shell.openExternal(url); } }); mainWindow.on('closed', () => mainWindow = null); } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); app.on('activate', () => { if (mainWindow === null) createWindow(); });
Option B: Load PDF in Current Window
Modify your index.html to open the PDF in the same window, then add download handling to your main window:
<!DOCTYPE html> <html> <head> </head> <body> <h1>Electron Application </h1> <a href="Sample.pdf" id="pdfLink">PDF DOC</a> <script> document.getElementById('pdfLink').addEventListener('click', (e) => { e.preventDefault(); window.location.href = 'Sample.pdf'; }); </script> </body> </html>
Then add this to your main.js after mainWindow.loadURL(...):
// Handle downloads in main window mainWindow.webContents.session.on('will-download', (event, item) => { const savePath = `${app.getPath('downloads')}/${item.getFilename()}`; item.setSavePath(savePath); item.on('done', (event, state) => { if (state === 'completed') { shell.showItemInFolder(savePath); } }); });
2. Fixing Microsoft Print to PDF Not Working
The printing issue is likely due to missing webPreferences or Electron 9.x compatibility quirks. Try these fixes:
Enable Plugins in WebPreferences
Update the webPreferences in your main window (and any PDF windows) to include plugins: true:
webPreferences: { devTools: false, contextIsolation: false, nodeIntegration: true, plugins: true // Required for some printing functionality }
Test with Manual Print Trigger
Add a print button to your index.html to test direct printing:
<button id="printBtn">Print PDF</button> <script> document.getElementById('printBtn').addEventListener('click', () => { window.print(); }); </script>
Upgrade Electron (If Possible)
Electron 9.x is quite old—consider upgrading to a newer stable version (e.g., 12.x+) as it includes fixes for printing compatibility issues with Microsoft Print to PDF.
Additional Checks
- Ensure
Sample.pdfis in the same directory asindex.html(or update the link path correctly). - When packaging with
electron-packager, make sure the PDF file is included in your build. If usingasarpackaging, add--asar-unpack="*.pdf"to your packager command to keep PDFs accessible.
内容的提问来源于stack exchange,提问作者Hari




