美文网首页
Electron导出PDF

Electron导出PDF

作者: 我叫Aliya但是被占用了 | 来源:发表于2020-08-04 15:02 被阅读0次
import { remote } from 'electron';

exports.exportPDF = function (title) {
    return new Promise(function (resolve, reject) {
        var filename = title + "-" + new Date().getTime() + ".pdf";
        var dir = remote.dialog.showSaveDialogSync({ defaultPath: filename, showsTagField: false });
        if (!dir) {
            reject();
            return;
        }
        
        // 选中需要导出的部分
        var selection = new SelectAll();
        // electron到处PDF
        remote
            .getCurrentWebContents()
            .printToPDF({ printSelectionOnly: true, printBackground: true }) // , pageSize: 'A5'
            .then(function (data) {
                fs.writeFile(dir, data, function (error) {
                    if (error) throw error;
                    // remote.shell.showItemInFolder(dir);
                    resolve();
                });
            })
            .catch(reject)
            .finally(() => selection.clear()); // 取消选中
    });
};

导出的PDF与原HTML样式有些差异,这是因为导出的PDF没有浏览器的默认样式,需要手动添加这些样式。为了用户体验,可以把选区颜色设为透明。

class SelectAll {
    constructor(classname) {
      this.d = document.querySelector('.' + classname);
      this.selection = window.getSelection();
      if (!this.d || !this.selection) return;
      this.d.setAttribute('contenteditable', 'true');
  
      const range = document.createRange();
      range.selectNodeContents(this.d);
      this.selection.removeAllRanges();
      this.selection.addRange(range);
      
      this.changeSelectColor();
    }
  
    clear() {
      if (this.selection) this.selection.removeAllRanges();
      if (this.d) this.d.removeAttribute('contenteditable');
      this.style.remove();
    }
  
    changeSelectColor() {
      this.style.type = 'text/css';
      this.style.innerText = `
      ::selection { background: transparent; }
      @media print {
        #editor {
          width: 100vw;
        }
        ol {
          list-style-type: decimal !important;
          margin-block-start: 1em;
          margin-block-end: 1em;
          margin-inline-start: 0;
          margin-inline-end: 0;
          padding-inline-start: 40px;
          display: block;
        }
        li {
          list-style: inherit !important;
          display: list-item;
          text-align: -webkit-match-parent;
        }
        ul {
          display: block;
          list-style-type: disc !important;
          margin-block-start: 1em;
          margin-block-end: 1em;
          margin-inline-start: 0;
          margin-inline-end: 0;
          padding-inline-start: 40px;
        }
        ul ul {
          list-style-type: circle !important;
        }
      }`;
      document.head.append(this.style);
    }
}

相关文章

网友评论

      本文标题:Electron导出PDF

      本文链接:https://www.haomeiwen.com/subject/owrwrktx.html