moe-pdf.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * This file is part of Moeditor.
  3. *
  4. * Copyright (c) 2016 Menci <huanghaorui301@gmail.com>
  5. *
  6. * Moeditor is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Moeditor is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Moeditor. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. 'use strict';
  20. const {BrowserWindow, ipcMain, shell} = require('electron');
  21. const os = require('os');
  22. const path = require('path');
  23. const MoeditorFile = require('./moe-file');
  24. var workerWindow, fileName, tmp, errorHandler;
  25. function exportPDF(content, cb) {
  26. workerWindow = new BrowserWindow({ show: false });
  27. function randString(n) {
  28. function rand(l, r) {
  29. return Math.floor(Math.random() * 100000000) % (r - l + 1) + l;
  30. }
  31. var s = '';
  32. for (var i = 0; i < n; i++) {
  33. var r = rand(1, 3);
  34. if (r == 1) s += String.fromCharCode(rand('0'.charCodeAt(0), '9'.charCodeAt(0)));
  35. else if (r == 2) s += String.fromCharCode(rand('a'.charCodeAt(0), 'z'.charCodeAt(0)));
  36. else if (r == 3) s += String.fromCharCode(rand('A'.charCodeAt(0), 'Z'.charCodeAt(0)));
  37. }
  38. return s;
  39. }
  40. tmp = path.join(os.tmpdir(), 'HexoEditor-export-' + randString(10) + '.html');
  41. MoeditorFile.write(tmp, content.s);
  42. fileName = content.path;
  43. errorHandler = cb;
  44. workerWindow.loadURL('file://' + tmp);
  45. // workerWindow.webContents.openDevTools();
  46. }
  47. ipcMain.on('ready-export-pdf', (event) => {
  48. setTimeout(() => {
  49. workerWindow.webContents.printToPDF({
  50. printBackground: true
  51. }, (error, data) => {
  52. MoeditorFile.writeAsync(fileName, data, (error) => {
  53. if (error) errorHandler(error);
  54. else {
  55. shell.openItem(fileName);
  56. workerWindow.destroy();
  57. workerWindow = undefined;
  58. MoeditorFile.remove(tmp);
  59. }
  60. })
  61. })
  62. }, 1000);
  63. });
  64. module.exports = exportPDF;