import path from 'path';
import fs from 'fs';
import { localized } from 'mailspring-exports';
import { escapeHTML } from 'underscore.string';
const { app, BrowserWindow, dialog } = require('@electron/remote');
export default class PrintWindow {
browserWin: Electron.BrowserWindow;
tmpFile: string;
constructor({ subject, account, participants, styleTags, htmlContent, printMessages }) {
// This script will create the print prompt when loaded. We can also call
// print directly from this process, but inside print.js we can make sure to
// call window.print() after we've cleaned up the dom for printing
const tmp = app.getPath('temp');
const tmpMessagesPath = path.join(tmp, 'print.messages.js');
const preloadPath = path.join(__dirname, '..', 'static', 'print-preload.js');
const scriptPath = path.join(__dirname, '..', 'static', 'print.js');
const stylesPath = path.join(__dirname, '..', 'static', 'print-styles.css');
const participantsHtml = participants
.map(part => {
return `
${escapeHTML(part.name || '')} <${escapeHTML(part.email)}>
`;
})
.join('');
const content = `
${styleTags}
${escapeHTML(subject)}
${htmlContent}
`;
this.tmpFile = path.join(tmp, 'print.html');
this.browserWin = new BrowserWindow({
width: 800,
height: 600,
title: `${localized('Print')} - ${subject}`,
webPreferences: {
preload: preloadPath,
nodeIntegration: false,
contextIsolation: false,
},
});
this.browserWin.webContents.ipc.on('print-to-pdf', async () => {
const { filePath } = await dialog.showSaveDialog({
defaultPath: `${subject}.pdf`,
});
if (!filePath) {
return;
}
const data = await this.browserWin.webContents.printToPDF({
margins: { marginType: 'none' },
pageSize: 'Letter',
printBackground: true,
landscape: false,
});
fs.writeFileSync(filePath, data);
});
this.browserWin.removeMenu();
fs.writeFileSync(tmpMessagesPath, `window.printMessages = ${printMessages}`);
fs.writeFileSync(this.tmpFile, content);
}
/**
* Load our temp html file. Once the file is loaded it will run print.js, and
* that script will pop out the print dialog.
*/
load() {
this.browserWin.loadURL(`file://${this.tmpFile}`);
}
}