jsPDF:addHTML方法无法正常工作。

3
我是一名有用的助手,可以为您翻译文本。
我创建了HTML表格,并尝试使用jsPDF生成PDF文件。
我使用了以下代码:
var pdf = new jsPDF('p','pt','a4');  
pdf.addHTML(document.getElementById('pdfTable'),function() {
  console.log('pdf generated');
});
pdf.save('pdfTable.pdf');

我得到了一个空白的PDF文件。我做错了什么吗?
这是一个用于此问题的 plunker
使用 addHTML 函数的 jsPDF 的 demo 工作。

已为您解决,请查看我的答案。 - Aks
6个回答

2

为此我制作了一个在 plunker 上工作的示例:

更新:

我已经更新了 plunker 并使用 addHTML() 函数使其可用:

var pdf = new jsPDF('p','pt','a4');
//var source = document.getElementById('table-container').innerHTML;
console.log(document.getElementById('table-container'));
var margins = {
   top: 25,
   bottom: 60,
   left: 20,
   width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.text(20, 20, 'Hello world.');
pdf.addHTML(document.body, margins.top, margins.left, {}, function() {
   pdf.save('test.pdf');
});

您可以查看plunker了解更多详细信息。

我很感激你的努力,但是我只能使用addHtml方法,因为我将使用其他方法向同一PDF文件写入不同的内容。 - vinesh
你可以通过连接HTML字符串来创建纯HTML,最后使用fromhtml打印它。 - Aks
我现在使用“addHTML”函数更新了答案。@vinesh - Aks
谢谢。我会检查并告诉你。 - vinesh

1

在 app.js 中更改此内容:

  pdf.addHTML(document.getElementById('pdfTable'),function() {
      });
  pdf.save('pdfTable.pdf');

这个的翻译是:“对于这一个:”。
pdf.addHTML(document.getElementById('pdfTable'),function() {
    pdf.save('pdfTable.pdf');
});

1
我只保留了这些内容:
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script src="//html2canvas.hertzen.com/build/html2canvas.js"></script>

然后我使用了这个:
  $(document).ready(function() {

        $("#pdfDiv").click(function() {

    var pdf = new jsPDF('p','pt','letter');

    var specialElementHandlers = {
    '#rentalListCan': function (element, renderer) {
        return true;
        }
    };

    pdf.addHTML($('#rentalListCan').first(), function() {
        pdf.save("rentals.pdf");
    });
    });
});

我可以打印表格...在Chrome、Safari或Firefox中看起来很棒,但是,如果我的表格非常大,我只能得到第一页。

1
请注意,这仅适用于按照此处显示的确切顺序包含两个脚本时才能正常工作。如果您首先包含html2canvas,则它将无法正常工作。原因是jsPDF覆盖了一些html2canvas方法,我认为这是不好的做法。因此,只有在重新定义其方法后才似乎可以包含html2canvas。同样的问题在这里讨论:http://stackoverflow.com/questions/28807755/jspdf-addhtml-method-not-working-with-no-error-message/34597797#34597797 - Michbeckable

0

我已经在你的plunker中测试过了。

只需更新你的app.js文件即可。

pdf.addHTML(document.getElementById('pdfTable'), function() {
      pdf.save('pdfTable.pdf');
});

更新你的 CSS 文件:

#pdfTable{
  background-color:#fff;
}

0

在 app.js 中更改:

  pdf.addHTML(document.getElementById('pdfTable'),function() {

  });
  pdf.save('pdfTable.pdf');

  pdf.addHTML(document.getElementById('pdfTable'),function() {
      pdf.save('pdfTable.pdf');
  });

如果你看到一个黑色的背景,你可以在style.css中添加"background-color: white;"

2
由于某些原因,function()内的任何内容都没有被执行。画布正在被渲染,但是pdf.save()没有被调用。 - DevEng

0

你应该使用querySelector()而不是getElementById()

var pdf = new jsPDF('p','pt','a4');  
pdf.addHTML(document.querySelector('#pdfTable'), function () {
  console.log('pdf generated');
});

pdf.save('pdfTable.pdf');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接