mcl
mcl

Reputation: 119

jsPDF output file is empty

I am trying to output a DIV as a PDF File.

I used the basic description from jsPDF on GitHub

I must have missed something because the file that is downloaded does not appear to have any visible data. I'm Using OSX Mavericks with Google Chrome, similar result with Safari. The file is 3kb larger

<!DOCTYPE html>
<html>
<head>
    <title>Untitled</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>

</head>

<body>

<div id="ResultsReport">
     <h3>Hello, this is a H3 tag : testing V2 of btnPDF</h3>

    <p>a pararaph</p>
</div>

<button id="btnPDF" onclick="btnPDF(code);">Generate PDF</button>

<script>
  var code = "UNIQ_ALL";

    function btnPDF(code) {

        var doc = new jsPDF()
        var repPDF = document.getElementById('ResultsReport').innerHTML;
        alert("REP=" + repPDF);
        doc.text(repPDF);
        //doc.text("<h4>This is just a test</h4>");
        doc.save(code + '.pdf');  
    }
</script>
</body>
</html>

Upvotes: 0

Views: 1975

Answers (1)

Marcs
Marcs

Reputation: 3838

I don't know that jspdf library but this works fine:

var code = "UNIQ_ALL";

 function btnPDF(code) {

     var doc = new jsPDF()
     var repPDF = document.getElementById('ResultsReport').innerText;
     doc.text(repPDF, 10, 10); // <-- add 10, 10
     doc.save(code + '.pdf');
 }
<!DOCTYPE html>
<html>

<head>
  <title>Untitled</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>

</head>

<body>

  <div id="ResultsReport">
    <h3>Hello, this is a H3 tag : testing V2 of btnPDF</h3>

    <p>a pararaph</p>
  </div>

  <button id="btnPDF" onclick="btnPDF(code);">Generate PDF</button>
</body>

</html>

I also changed the innerHTML property to innerText to extract text instead of HTML.

Edit:

Using an older version of jsPDF (1.0.272) you can try the method fromHTML. I think is an early stage renderer, so with fancy HTML wouldn't work probably, but for simple stuff should be fine.

html2canvas is not necessary with fromHTML but for addHTML I think it is.

var code = "UNIQ_ALL";

function btnPDF(code) {

  var doc = new jsPDF();
  doc.fromHTML($("#ResultsReport")[0], 10, 10);
  doc.save(code + '.pdf');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>

<div id="ResultsReport">
  <h3>Hello, this is a H3 tag : testing V2 of btnPDF</h3>
  <p>a <b>bold</b> pararaph</p>
</div>

<button id="btnPDF" onclick="btnPDF(code);">Generate PDF</button>

Upvotes: 1

Related Questions