22

I am currently working on a school management software that usually requires exporting of html contents that contains data tables and div tag.

I have tried all possible means to write a code that will be able to export my html data in a good way, with css preferably. After checking some question and answers here, I tried using spdf, but no luck.

It keeps destroying my table alignment, then I read about html2canvas but to implement it with jspdf was my problem, i would like to capture the content if a div tag with html2canvas then send the canvas to jspdf to export the canvas as pdf.

Here is my code below:

<script src="assets/js/pdfconvert/jspdf.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.from_html.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.split_text_to_size.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.standard_fonts_metrics.js">  </script>
<script src="assets/js/pdfconvert/jspdf.plugin.addhtml.js"></script>
<script src="assets/js/pdfconvert/filesaver.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.cell.js"></script>
<script src="assets/js/pdfconvert/html2canvas.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.addimage.js"></script>

here is the js code

var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
pdf.save('Test.pdf');
});
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
Tobi Owolawi
  • 550
  • 1
  • 4
  • 14

4 Answers4

25

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

Razan Paul
  • 13,618
  • 3
  • 69
  • 61
  • 1
    Sweet! This works great in Chrome. In Safari, though, I just get a blank page when I click the download button. – Andrew Philpott Dec 11 '14 at 19:01
  • 1
    Thanks Andrerw. Is is Safari 5.1.7? It seems Safari version 6 and 7 does not support windows? JSpdf has some issues with safari.http://stackoverflow.com/questions/21755171/jspdf-not-working-on-safari Have you tried doc.output('dataurlnewwindow');? – Razan Paul Dec 12 '14 at 01:17
  • 1
    I tested it in Safari 8 on OS X. I'm wondering if the issue might be with saving the canvas data as PNG data. I was having issues getting things to work in Safari on a project I'm working on, but then I switched to JPEG and it suddenly started working. – Andrew Philpott Dec 12 '14 at 14:07
  • If i have two canvas i.e canvas1 and canvas2 and want to export to in a single pdf using the html2canvas, than what will be the code ?? help me..Please – Ananta Prasad Sep 01 '15 at 07:02
  • @Ananta, one option is to put the both canvases inside a div and use the div ID in html2canvas call. – Razan Paul Sep 01 '15 at 22:44
  • If i dont want to put canvases inside a div , then ?? – Ananta Prasad Sep 02 '15 at 06:44
  • Another option is making separate html2canvas call with each canvas and onrendered method, converting the canvases to images. Then, adding two images using doc.addImage method to the pdf. Note: you need to use promise here to make sure that both image conversions have been completed before you call doc.save method. – Razan Paul Sep 02 '15 at 22:55
  • IT WORKS PERFECT! THANKS – Pablo Glez Dec 29 '15 at 18:07
  • I get the following errors on the jsfiddle: `Failed to load resource: net::ERR_BLOCKED_BY_CLIENT` then `parall.ax/products/jspdf/dist/jspdf.debug.js:1 Uncaught SyntaxError: Unexpected token <` and then `(index):93 Uncaught ReferenceError: jsPDF is not defined(…)` – Benjamin Crouzier Nov 29 '16 at 14:57
  • How can I add a loader as soon the user clicks the button? – Johnson Samuel May 09 '18 at 14:38
  • it throws: onrendered option is deprecated – Dainius Kreivys Jun 15 '18 at 13:13
  • What should i do if i want to save pdf file on my custom path. – umarbilal Dec 05 '18 at 07:25
  • How we can add the page split automatically based on height of page? – kantsverma Mar 12 '21 at 10:02
  • 1
    jsfiddle Uncaught ReferenceError: html2canvas is not defined – duyue Sep 13 '22 at 09:21
13

This one shows how to print only selected element on the page with dpi/resolution adjustments

HTML:

<html>

  <body>
    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>
  </body>

</html>

CSS:

body {
  background: beige;
}

header {
  background: red;
}

footer {
  background: blue;
}

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
}

JS:

$('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {
    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);
      doc.save('sample-file.pdf');
    }
  });
});

jsfiddle: https://jsfiddle.net/marksalvania/dum8bfco/

Mark Salvania
  • 486
  • 3
  • 17
1

Changing this line:

var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);

To fix the dimensions.

Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
0

This worked when you add "useCORS: true". Grabs google map as it is rendered on the screen and puts it in a pdf

function create_pdf() {
         return html2canvas($('#map'), {
             useCORS: true,
             background: "#ffffff",
             onrendered: function(canvas) {
                 var myImage = canvas.toDataURL("image/jpeg,1.0");
                 // Adjust width and height
                 var imgWidth =  (canvas.width * 60) / 240;
                 var imgHeight = (canvas.height * 70) / 240;
                 // jspdf changes
                 var pdf = new jsPDF('p', 'mm', 'a4');
                 pdf.addImage(myImage, 'png', 15, 2, imgWidth, imgHeight); // 2: 19
                 pdf.save(`Budgeting ${$('.pdf-title').text()}.pdf`);
             }
         });