在 js 中导出 div 为 pdf

Export div to pdf in js

我有两个 div 的 ID:element1element2

在这些 div 之间,有一个按钮。在这些 div 之后,还有一个 id 为 pdf.

的按钮

在 div 中有一个 table 和输入框。

    <div id="element1">
      Enter your name: <input><br>
      Enter your class: <input>
    </div>

    <button>Click on the button</button>

    <div id="element2">
      <table>
        <tr>
          <td>Name</td>
          <td>Class</td>
        </tr>
        <tr>
          <td><input></td>
          <td><input></td>
        </tr>
      </table>
    </div>

    <button id="pdf">Create pdf</button>

我是 JS 初学者。现在,我想创建一个 pdf 文件,其中包含两个 div 的内容,不包括两个按钮。此外,pdf 文件必须包含在输入框中输入的值。 pdf 可以包含文本或 jpg 等任何格式的 div 的内容。

请帮助我,因为我是初学者。我已经用 jspdf 做了很多尝试,但它没有给我输出。

jspdf 是最合适的库。您可以做的是在将数据放入 pdf 之前对其进行操作。我认为您最好的选择是用 or 或您想要的任何元素替换输入。然后你可以建立你的pdf。我的选择是把它放在 wrapper

里面

$('#pdf').click(function () {
    $('#PDFWrapper').find('input').each(function(){
        $(this).hide();
        $(this).after('<span>' + $(this).val() + '</span>');
    });
    $('#PDFWrapper').find('button').hide();
        
    var doc = new jsPDF();
    doc.fromHTML($('#PDFWrapper').html(), 10, 10, {
        'elementHandlers': {}
    });
    doc.save('download.pdf');
        
    $('#PDFWrapper').find('input').each(function(){
        $(this).show();
        $(this).next().remove();
    });
    $('#PDFWrapper').find('button').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<div id="PDFWrapper">
  <div id="element1">
    Enter your name: <input><br>
    Enter your class: <input>
  </div>

  <button>Click on the button</button>

  <div id="element2">
    <table>
      <tr>
        <td>Name</td>
        <td>Class</td>
      </tr>
      <tr>
        <td><input></td>
        <td><input></td>
      </tr>
    </table>
  </div>
</div>

<button id="pdf">Create pdf</button>