2023-06-22 06:34:32 +00:00
|
|
|
import { emitMainProcessError } from 'backend/helpers';
|
2022-05-19 12:08:46 +00:00
|
|
|
import { App, BrowserWindow } from 'electron';
|
|
|
|
import fs from 'fs/promises';
|
|
|
|
import path from 'path';
|
|
|
|
|
|
|
|
export async function saveHtmlAsPdf(
|
|
|
|
html: string,
|
|
|
|
savePath: string,
|
2023-06-02 14:20:32 +00:00
|
|
|
app: App,
|
|
|
|
width: number, // centimeters
|
|
|
|
height: number // centimeters
|
2022-05-19 12:08:46 +00:00
|
|
|
): Promise<boolean> {
|
|
|
|
/**
|
|
|
|
* Store received html as a file in a tempdir,
|
|
|
|
* this will be loaded into the print view
|
|
|
|
*/
|
|
|
|
const tempRoot = app.getPath('temp');
|
|
|
|
const filename = path.parse(savePath).name;
|
|
|
|
const htmlPath = path.join(tempRoot, `${filename}.html`);
|
|
|
|
await fs.writeFile(htmlPath, html, { encoding: 'utf-8' });
|
|
|
|
|
2023-06-22 06:34:32 +00:00
|
|
|
const printWindow = await getInitializedPrintWindow(htmlPath, width, height);
|
2023-06-02 14:20:32 +00:00
|
|
|
const printOptions = {
|
|
|
|
marginsType: 1, // no margin
|
|
|
|
pageSize: {
|
|
|
|
height: height * 10_000, // micrometers
|
|
|
|
width: width * 10_000, // micrometers
|
|
|
|
},
|
|
|
|
printBackground: true,
|
|
|
|
printBackgrounds: true,
|
|
|
|
printSelectionOnly: false,
|
|
|
|
};
|
2022-05-19 12:08:46 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* After the printWindow content is ready, save as pdf and
|
|
|
|
* then close the window and delete the temp html file.
|
|
|
|
*/
|
|
|
|
return await new Promise((resolve) => {
|
|
|
|
printWindow.webContents.once('did-finish-load', () => {
|
2023-06-22 06:34:32 +00:00
|
|
|
printWindow.webContents
|
|
|
|
.printToPDF(printOptions)
|
|
|
|
.then((data) => {
|
|
|
|
fs.writeFile(savePath, data)
|
|
|
|
.then(() => {
|
|
|
|
printWindow.close();
|
|
|
|
fs.unlink(htmlPath)
|
|
|
|
.then(() => {
|
|
|
|
resolve(true);
|
|
|
|
})
|
|
|
|
.catch((err) => emitMainProcessError(err));
|
|
|
|
})
|
|
|
|
.catch((err) => emitMainProcessError(err));
|
|
|
|
})
|
|
|
|
.catch((err) => emitMainProcessError(err));
|
2022-05-19 12:08:46 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-06-22 06:34:32 +00:00
|
|
|
async function getInitializedPrintWindow(
|
2023-06-02 14:20:32 +00:00
|
|
|
printFilePath: string,
|
|
|
|
width: number,
|
|
|
|
height: number
|
|
|
|
) {
|
2022-05-19 12:08:46 +00:00
|
|
|
const printWindow = new BrowserWindow({
|
2023-06-02 14:20:32 +00:00
|
|
|
width: Math.floor(width * 28.333333), // pixels
|
|
|
|
height: Math.floor(height * 28.333333), // pixels
|
2022-05-19 12:08:46 +00:00
|
|
|
show: false,
|
|
|
|
});
|
|
|
|
|
2023-06-22 06:34:32 +00:00
|
|
|
await printWindow.loadFile(printFilePath);
|
2022-05-19 12:08:46 +00:00
|
|
|
return printWindow;
|
|
|
|
}
|