jsPDF всегда возвращает бланк, в частности Html файл - PullRequest
0 голосов
/ 12 апреля 2020

Я использую jsPDF autoTable для печати PDF-файла, в моем mproyect использование Angular 7 работает довольно хорошо во всех html, но по какой-то причине в одном конкретном файле html это не так, он загружает файл, но в «пустом» режиме, если приложить изображение, которое он печатает с успехом, вот ошибка:

jspdf.plugin.autotable.js:564 Html table could not be found with input:  tableGuias

Не удается найти объявленный вход html, мой вопрос, почему.

Любая таблица, которую я пытаюсь создать, не работает, здесь я создаю фиктивную таблицу, чтобы показать вам.

<table id="tableGuias">
  <thead>
    <th>Dummy Header</th>
  </thead>
  <tbody>
    <td>Simple Test</td>
  </tbody>
</table>

теперь позволяет увидеть файл TypeScript:

    getPdfFromHtml() {
      const  idTable = document.getElementById('tableGuias');
      const doc = new jsPDF('landscape');
      doc.autoTable( { html: idTable });
      setTimeout(function() {
          doc.save('tableGuias.pdf');
      }, 1000 );
    }

Компонент хорошо настроен в декораторе @Component, поэтому Html и файл TS связаны. SetTimeout это просто потому, что я читал раньше, что, возможно, может решить проблему, это было не в моем случае.

Использование getElementById () или getElementByClassName (), или просто объявить #table таблицу тегов, сделал ' Не работает.

Не могу понять, что происходит. Я думал, что какая-то ошибка может прервать метод, но консоль не выдает никакой ошибки, кроме первой.

1 Ответ

1 голос
/ 12 апреля 2020

Вы можете просто заменить:

doc.autoTable( { html: idTable });

на

var res = doc.autoTableHtmlToJson(idTable);
doc.autoTable(res.columns, res.data);

, чтобы получить желаемый результат.

Демо:

function getPdfFromHtml() {
  const idTable = document.getElementById('tableGuias');
  const doc = new jsPDF('landscape');

  var res = doc.autoTableHtmlToJson(idTable);
  doc.autoTable(res.columns, res.data);

  setTimeout(function() {
    doc.save('tableGuias.pdf');
  }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>

<!-- EDIT: For now, add this line between the libraries -->
<!-- The reason being that jspdf includes a version of requirejs which -->
<!-- jspdf-autotable currently is not expecting. You can also use version < 2.0.21 -->
<script>
  if (window.define) delete window.define.amd;
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js"></script>

<button onclick="getPdfFromHtml()">Download PDF</button>

<table id="tableGuias">
  <thead>
    <th>Dummy Header</th>
  </thead>
  <tbody>
    <td>Simple Test</td>
  </tbody>
</table>

Кроме того, вы можете использовать опцию

const doc = new jsPDF('p', 'pt');

для лучшего вывода больших таблиц, таких как:

Демо:

function getPdfFromHtml() {
  const idTable = document.getElementById('tableGuias');
  const doc = new jsPDF('p', 'pt');

  var res = doc.autoTableHtmlToJson(idTable);
  doc.autoTable(res.columns, res.data);

  setTimeout(function() {
    doc.save('tableGuias.pdf');
  }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>

<!-- EDIT: For now, add this line between the libraries -->
<!-- The reason being that jspdf includes a version of requirejs which -->
<!-- jspdf-autotable currently is not expecting. You can also use version < 2.0.21 -->
<script>
  if (window.define) delete window.define.amd;
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js"></script>

<button onclick="getPdfFromHtml()">Download PDF</button>

<table id="tableGuias">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbköp</td>
    <td>Christina Berglund</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Königlich Essen</td>
    <td>Philip Cramer</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>Simon Crowther</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris spécialités</td>
    <td>Marie Bertrand</td>
    <td>France</td>
  </tr>
</table>
...