javascript - 将 html 表格导出为 pdf

标签 javascript html pdf html-table

我的代码有什么问题吗?我想将 html 表导出为 pdf 并保存。然后碰巧它只会打开一个空白屏幕的新浏览器。这是我的示例代码。请帮忙。谢谢。

<!DOCTYPE html>
<html>
</head>
<body>
<div id="pdf">
<table id="StudentInfoListTable">
            <thead>
                <tr>    
                    <th>Name</th>
                    <th>Email</th>
                    <th>Track</th>
                    <th>S.S.C Roll</th>
                    <th>S.S.C Division</th>
                    <th>H.S.C Roll</th>
                    <th>H.S.C Division</th>
                    <th>District</th>

                </tr>
            </thead>
            <tbody>

                    <tr>
                        <td>alimon  </td>
                        <td>Email</td>
                        <td>1</td>
                        <td>2222</td>
                        <td>as</td>
                        <td>3333</td>
                        <td>dd</td>
                        <td>33</td>
                    </tr>               
            </tbody>
        </table>
    </div>

  <!--<button >Submit</button> -->
  <li> <a href="javascript:PrintDiv()">Export to pdf</a> </li>

<script type="text/javascript">     
    function PrintDiv(htmlexportPDF) {    
       var divToPrint = document.getElementById(htmlexportPDF);
       alert('Printing: Success');
       var popupWin = window.open('', '_blank', 'width=650,height=600');
       popupWin.document.open();
       popupWin.document.write('<style type="text/css">body{ margin:0.5px;');
       popupWin.document.write('font-family:verdana,Arial;color:#000;');
       popupWin.document.write('font-family:Verdana, Geneva, sans-serif; font-size:8px;}');
       popupWin.document.write('a{color:#000;text-decoration:none;}</style>');
       popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
       popupWin.document.close();
            }
 </script>

最佳答案

您的 JavaScript 函数 printDiv 接受参数 htmlexportPDF。

function PrintDiv(htmlexportPDF) {

问题是当您从 <a> 调用 PrintDiv 时您没有提供任何参数的链接。

要解决此问题,请更改

<a href="javascript:PrintDiv()">Export to pdf</a>

<a href="javascript:PrintDiv('StudentInfoListTable')">Export to pdf</a>

此外,在您的 HTML 代码中,您从未放置过开头 <head>标签或结束语</body>标签或结束语</html>标签。

关于javascript - 将 html 表格导出为 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30993487/

相关文章:

javascript - 使用 mongoose 时,ForEach 循环代码无法在 Promise 中工作

javascript - 如何在数组的索引处插入重复项?

javascript - 对没有数据绑定(bind)的选择列表进行 knockout 验证 'option' 或 'caption'

ios - 使用 Quartz 解析 PDF 文档

javascript - 通过多个 Controller 的服务推送对象数据数组

javascript - jQuery .after() 函数有什么替代方法吗

python - Beautiful Soup 没有 'get' 完整网页

html - 如何设置列表样式以在 html 中显示为两个列

javascript - iFrame 中的 PDF 不适用于 iOS

css - 如何在将 div 下载为 PDF 时显示一个部分,但将其隐藏在屏幕上