简体   繁体   English

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

[英]How to print tables on pdf with Javascript?

What's the best way to print tables in PDF with JavaScript?使用 JavaScript 打印 PDF 中的表格的最佳方法是什么?

For example, I have the next code, and if you click on "Show PDF", the table appears in PDF in a new window. Is it possible to implement this with the jsPDF library?例如,我有下一个代码,如果你点击“显示PDF”,表格出现在一个新的window中的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>

Bytescout has new javascript product "PDF Generator SDK for Javascript" which is capable of generating PDF files 100% on client side, probably you may generate PDF with text, images, graphics. Bytescout拥有新的JavaScript产品“用于Javascript的PDF Generator SDK”,它能够在客户端上100%生成PDF文件,可能您可以生成带有文本,图像,图形的PDF。 Full HTML formatting is not supported, but you can use , , html tags inside text to use rich formatting (new version will include support for and html tags inside text) 不支持完整的HTML格式,但是您可以在文本内使用,,html标签以使用丰富的格式(新版本将在文本内包含对和html标签的支持)

Demo of invoice with logo and table generated: http://bytescout.com/products/developer/pdfgeneratorsdkjs/create_pdf_invoice_javascript.html 带有徽标和表格的发票演示: http : //bytescout.com/products/developer/pdfgeneratorsdkjs/create_pdf_invoice_javascript.html

I had the same problem, This is the way that i solved it. 我有同样的问题,这就是我解决问题的方法。

//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);

Hope it helps, However it is late! 希望对您有所帮助,但是已经晚了!

Try witch TCPDF 试试女巫TCPDF
TCPDF is a PHP class for generating PDF files on-the-fly without requiring external extensions. TCPDF是一个PHP类,用于在不需要外部扩展的情况下即时生成PDF文件。 This library includes also a class to extract data from existing PDF documents and classes to generate 1D and 2D barcodes in various formats. 该库还包括一个从现有的PDF文档中提取数据的类,以及一个以各种格式生成一维和二维条形码的类。

The AutoTable plugin for jsPDF automates a lot of the tasks required to make tables or lists. jsPDF的AutoTable插件可自动执行制作表或列表所需的许多任务。 The only thing required for your example is first converting the table to json and then passing it to the autoTable() method. 您的示例所需的唯一操作是首先将表转换为json,然后将其传递给autoTable()方法。 Check out the demos or repo for more advanced examples. 查看演示回购以获取更多高级示例。

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> 

Here is an example without any plugin or libraries to print out HTML table using JavaScript这是一个没有任何插件或库的示例,使用 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>

You should to use DOMPDF, : 您应该使用DOMPDF ,:
dompdf is an HTML to PDF converter. dompdf是HTML到PDF的转换器。 At its heart, dompdf is (mostly) CSS 2.1 compliant HTML layout and rendering engine written in PHP. dompdf的本质是(大多数)PHP兼容的CSS 2.1 HTML布局和呈现引擎。 It is a style-driven renderer: it will download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. 它是样式驱动的渲染器:它将下载和读取外部样式表,内联样式标签以及单个HTML元素的样式属性。 It also supports most presentational HTML attributes. 它还支持大多数演示HTML属性。

Download domPDF 下载domPDF

http://code.google.com/p/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));
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM