首页 > 解决方案 > 如何将 HTML 表格导出为 PDF

问题描述

我有一个要导出到 excel 的 HTML 小表单。我希望能够保持在 excel 中但在 PDF 中显示的相同格式。我尝试了许多不同的方法,但仍然无法成功导出为 PDF。请查看我的 jsfiddle。谢谢!

https://jsfiddle.net/jphuizar/dcv3mg21/

var tablesToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
    tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' +
    '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>' +
    '<Styles>' +
    '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>' +
    '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>' +
    '</Styles>' +
    '{worksheets}</Workbook>',
    tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>',
    tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      })
    }
  return function(tables, wsnames, wbname, appname) {

    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";

    /*

    for (var j = 0; j < column.length; j++)
      //goes through <select> tags
      {const select = column[j].querySelector('select');

      */



    for (var i = 0; i < tables.length; i++) {
      if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
      for (var j = 0; j < tables[i].rows.length; j++) {
        rowsXML += '<Row>'
        for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
          var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
          var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
          var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
          var select = tables[i].rows[j].cells[k].getElementsByTagName("select")[0];
          dataValue = (dataValue) ? dataValue : (select ? select.options[select.selectedIndex].value : tables[i].rows[j].cells[k].innerHTML);
          dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
          var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
          dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
          ctx = {
            attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : '',
            nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
            data: (dataFormula) ? '' : dataValue,
            attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
          };
          rowsXML += format(tmplCellXML, ctx);
        }


        rowsXML += '</Row>'
      }
      ctx = {
        rows: rowsXML,
        nameWS: wsnames[i] || 'Sheet' + i
      };
      worksheetsXML += format(tmplWorksheetXML, ctx);
      rowsXML = "";
    }

    ctx = {
      created: (new Date()).getTime(),
      worksheets: worksheetsXML
    };
    workbookXML = format(tmplWorkbookXML, ctx);

    console.log(workbookXML);

    var link = document.createElement("A");
    link.href = uri + base64(workbookXML);
    link.download = wbname || 'Workbook.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  var rows = document.querySelectorAll("table tr");
})();
<!-- 1 -->
<table id="table1">
  <p>Table 1</p>
  <hr>
  <tr>
    <td>Question 1:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 2:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>

<!-- 2 -->
<p>Table 2</p>
<hr>
<table id="table2">
  <tr>
    <td>Question 3:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 4:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>

<!-- 3 -->
<p>Table 3</p>
<hr>
<table id="table3">
  <tr>
    <td>Question 5:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 6:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>
<button onclick="tablesToExcel(['table1','table2','table3'], ['Summary','SectionA', 'SectionB'], 'TestBook.xls', 'Excel')">Export to Excel</button>

标签: javascripthtmlpdf

解决方案


使用此代码

<html>
<head>
    <title>Convert Table to PDF using JavaScript</title>
    <style>
        table
        {
            width: 300px;
            font: 17px Calibri;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="tab">
        <table> 
            <tr>
                <th>Name</th>
                    <th>Age</th>
                        <th>Job</th>
            </tr>
            <tr>
                <td>Brian</td>
                    <td>41</td>
                        <td>Blogger</td>
            </tr>
            <tr>
                <td>Matt</td>
                    <td>25</td>
                        <td>Programmer</td>
            </tr>
            <tr>
                <td>Arun</td>
                    <td>39</td>
                        <td>Writter</td>
            </tr>
        </table>
    </div>

    <p>
        <input type="button" value="Create PDF" 
            id="btPrint" onclick="createPDF()" />
    </p>
</body>
<script>
    function createPDF() {
        var sTable = document.getElementById('tab').innerHTML;

        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        // CREATE A WINDOW OBJECT.
        var win = window.open('', '', 'height=700,width=700');

        win.document.write('<html><head>');
        win.document.write('<title>Profile</title>');   // <title> FOR PDF HEADER.
        win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // THE TABLE CONTENTS INSIDE THE BODY TAG.
        win.document.write('</body></html>');

        win.document.close();   // CLOSE THE CURRENT WINDOW.

        win.print();    // PRINT THE CONTENTS.
    }
</script>
</html>


参考


推荐阅读