在 Electron 中使用 jsPDF

Using jsPDF with Electron

我正在尝试在我的 Electron 应用程序中创建生成 pdf 文档。当用户选择 JSON 文件时,我想解析它并创建新的 PDF 文档。我在尝试创建文档时遇到错误。

错误

Uncaught Error: Type of text must be string or Array. "undefined" is not recognized.
    at Object.H.text (/Users/antarrbyrd/dev/pathway_exporter/bower_components/jspdf/dist/jspdf.min.js:1)
    at HTMLInputElement.<anonymous> (index.html:48)
    at HTMLInputElement.dispatch (/Users/antarrbyrd/dev/pathway_exporter/lib/jquery.min.js:3)
    at HTMLInputElement.q.handle (/Users/antarrbyrd/dev/pathway_exporter/lib/jquery.min.js:3) 

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link href="./bower_components/photon/dist/css/photon.min.css" rel="stylesheet" type="text/css" />
    <title>Seremedi - Pathway Exporter</title>
  </head>
  <body>
    <div class="window">
      <header class="toolbar toolbar-header">
        <div class="btn-group">
          <button class="btn btn-large btn-default" id="open-button">
            <span class="icon icon-folder"></span>
          </button>
          <button class="active btn btn-large btn-default">
            <span class="icon icon-download"></span>
          </button>
          <button class="active btn btn-large btn-default">
            <span class="icon icon-print"></span>
          </button>
        </div>
        <input type="file" id="file-input" style="display: none;"></input>
      </header>
      <div class="window-content">
        <webview id="webview" autosize style="display:inline-flex; width:100%; height:100%"></webview>
      </div>
      <footer class="toolbar toolbar-footer">
        <h1 class="title">&copy; Seremedi - 2017</h1>
      </footer>
    </div>
  </body>
  <script>
    $ = require('jquery')
    jsPDF = require('jspdf')
    PDFDocument = require('pdfkit')

    $('#open-button').on('click',function(evt){
      evt.preventDefault();
      $('#file-input').click();
    });
    $('#file-input').on('change',function(evt){
      var location = $('#file-input')[0].files[0].path;
      source = "";
      $('#webview').prop('src', location);
      $.getJSON(location, function(json){
        source = json;
        console.log(source);
      });
      var doc = new jsPDF();
      doc.text(source.ReferenceId, 10, 10);
      doc.save('file.pdf');
    });
  </script>
</html>

Javascript 是异步的。 jsPDF 行只是在 $.getJSON() 完成之前执行。那时 source 只是一个空字符串。因此 source.ReferenceId 未定义。

$.getJSON(location, function(json){
    source = json;
    var doc = new jsPDF();
    doc.text(source.ReferenceId, 10, 10);
    doc.save('file.pdf');
});