使用jsPDF将div转换为pdf会产生一个带有空白页的pdf文档,其中包含" undefined"其中的文字

时间:2015-07-18 13:52:03

标签: jquery html pdf converter jspdf

我想将div#printableArea转换为PDF。代码有效,文件下载成功。当我打开文件时,它只有undefined。我似乎无法找到解决方案。你们能帮忙吗?感谢。

这是加载的js文件:

<script src="form_html.js"></script>
<script src="split_text_to_size.js"></script>
<script src="standard_fonts_metrics.js"></script>
<script src="canvas.js"></script>
<script type="text/javascript" src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script>         
    function demoFromHTML() {
        var pdf = new jsPDF();
        var source = $('#printableArea').first();
        var specialElementHandlers = {
            '#bypassme': function(element, renderer) {
                return true;
            }
        };

        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };

        pdf.fromHTML(
            source.get(), // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, // y coord
            {
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },
            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF
                //          this allow the insertion of new lines after html
                pdf.save('Test.pdf');
            },
            margins
        )
    }
</script>
<div id="printableArea">
    <table>
        <tr>
            <td>
                My contents...
            </td>
        </tr>
    </table>
</div>

1 个答案:

答案 0 :(得分:0)

我不知道你是否只想要打印第一个孩子。我需要整个div,所以尝试使用以下代码(将#container替换为必需部分):

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source = $("#container").html();

      specialElementHandlers = {
          // element with id of "bypass" - jQuery style selector
          '#noprint': function (element, renderer) {
              // true = "handled elsewhere, bypass text extraction"
              return true;
          }
      };

      pdf.fromHTML(
        source, 20, 20, { 'width': 150,
            'elementHandlers': specialElementHandlers
       },

      function (dispose) {
            // dispose: object with X, Y of the last line add to the PDF 
            //          this allow the insertion of new lines after html
            pdf.save('Test.pdf');
      }, margins);

如果有效或无效,请告诉我。谢谢!