如何使用Javascript在pdf上打印表格

How to print tables on pdf with Javascript?

本文关键字:打印 表格 pdf 何使用 Javascript      更新时间:2023-09-26

用JavaScript以PDF格式打印表格的最佳方式是什么?

例如,我有下一个代码,如果你点击"显示PDF",表格将以PDF格式显示在一个新窗口中。有可能用jsPDF库实现这一点吗?

<body>
    <table>
        <tr>
            <th>example</th>
            <th>example2</th>
        </tr>
        <tr>
            <td>value1</td>
            <td>value2</td>
        </tr>
    </table>
    <br>
    <input type="button" value="Show PDF">
</body>

我也遇到了同样的问题,这就是我解决它的方法。

//inputs starts here
var T_X =20 //Starting X of Table
var T_Y =25 //Starting Y of Table
var T_W =170 //Width of Table
var T_H =10 //Height of each cell
var Px  =7 // Scale of width in each columns
var Fs  =17 //Font size
var Tp  =7 //Y of all cells text, must change with `Fs`
var c = new Array() //Input Each Row by Adding new c[i]
c[0] = new Array("1","2","3","4","5","6","7");
c[1] = new Array("a","b","c","d","e","f","g");
c[2] = new Array("A","B","C","D","E","F","G");
//c[3] = new Array("Alpha","Beta","Gamma","Delta","Epsilon","Zeta","Eta");
//inputs ends here
//From This Part to bottom, there is no more inputs, no need to read them.
//i found this function here "http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript"
String.prototype.width = function() {
  var f = Px+'px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();
  o.remove();
  return w;
}

var doc = new jsPDF();
doc.text(85, 15, "Table example");
doc.setDrawColor(50,215,50);
doc.setLineWidth(0.5);
var i
var rows = c[0].length
var cols = c.length
var max = new Array()
for(i=0;i<cols;i++)
    max[i]=0
doc.setFontSize(Fs);
for(i=0;i<rows;i+=1)
{
    doc.line(T_X, T_Y+T_H*i,T_W + T_X, T_Y+T_H*i);
    for(var j=0;j<cols;j+=1)
        if(c[j][i].width()>max[j])
            max[j]=c[j][i].width(); 
}
    doc.line(T_X, T_Y+T_H*rows,T_W + T_X, T_Y+T_H*i);
var m = 0
for(i=0;i<cols;i+=1)
{
    for(var j=0;j<rows;j+=1)
        doc.text(T_X + 0.5 + m, Tp+T_Y+T_H*j,c[i][j]);
    doc.line(T_X + m, T_Y ,T_X + m, T_Y + rows * T_H);
    m += max[i];   
}
doc.line(T_X + T_W, T_Y ,T_X + T_W, T_Y + rows * T_H);

希望它能有所帮助,但为时已晚!

jsPDF的AutoTable插件自动化了制作表格或列表所需的许多任务。对于您的示例,唯一需要的就是首先将表转换为json,然后将其传递给autoTable()方法。查看演示或repo了解更多高级示例。

function generatePdf() {
    var doc = new jsPDF('p', 'pt');
    var json = doc.autoTableHtmlToJson(document.getElementById("table"));
    doc.autoTable(false, json);
    doc.save('table.pdf');
}

function generatePdf() {
   var doc = new jsPDF('p', 'pt');
   var json = doc.autoTableHtmlToJson(document.getElementById("table"));
   doc.autoTable(false, json);
   doc.save('table.pdf');
}
<table id="table">
  <tr>
    <th>example</th>
    <th>example2</th>
  </tr>
  <tr>
    <td>value1</td>
    <td>value2</td>
  </tr>
</table>
<br>
<input type="button" onclick="generatePdf()" value="Show PDF">
<script src="https://rawgit.com/MrRio/jsPDF/master/dist/jspdf.debug.js"></script>
<script src="https://rawgit.com/someatoms/jsPDF-AutoTable/master/jspdf.plugin.autotable.js"></script>

下面是一个没有任何插件或库的例子,可以使用JavaScript 打印HTML表

<html>
<head>
    <style>
      * { font-family: calibri; font-size: 20px; }
      table
      {
        width: 100%;
      }
      table, th, td 
      {
        border: solid 1px #DDD;
        text-align: center;
      }
    </style>
</head>
<body id="myTable">
    <table>
        <tr>
            <th>example1</th>
            <th>example2</th>
        </tr>
        <tr>
            <td>value1</td>
            <td>value2</td>
        </tr>
      <tr>
            <td>value3</td>
            <td>value4</td>
        </tr>
    </table>
    <br>
   
  <p>
    <input type="button" value="Show PDF" 
           id="btPrint" onclick="createPDF()" />
  </p>
  
  
</body>
<script>
    function createPDF() {
        var sTable = document.getElementById('myTable').innerHTML;
         // add all the css and styling for the table 
        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #000; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";
        // here we creat our window object
        var win = window.open('', '', 'height=700,width=700');
        win.document.write('<html><head>');
        win.document.write('<title>my table</title>');   // title or name for pdf
        win.document.write(style);          // add our css.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // table content. 
        win.document.write('</body></html>');
        win.document.close();   // close the window.
        win.print();    // print the table.
    }
</script>
</html>

您应该使用DOMPDF,:
DOMPDF是一个HTML到PDF的转换器。从本质上讲,dompdf(主要)是用PHP编写的符合CSS2.1的HTML布局和渲染引擎。它是一个样式驱动的呈现器:它将下载和读取外部样式表、内联样式标记和单个HTML元素的样式属性。它还支持大多数表示HTML属性。

下载domPDF

http://code.google.com/p/dompdf/

<?
require  "dompdf_config.inc.php";
$html = <<<STY
<table>
<tr>
<th>example</th>
<th>example2</th>
</tr>
<tr>
<td>value1</td>
<td>value2</td>
</tr>
</table>
</body>
STY;
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();    
$dompdf->stream("mypdf.pdf", array("Attachment" => 0));
?>