[javascript] how to use html2canvas and jspdf to export to pdf in a proper and simple way

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');
});

This question is related to javascript jquery html css jspdf

The answer is


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.


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/


Changing this line:

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

To fix the dimensions.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to jspdf

How to set image to fit width of the page using jsPDF? how to use html2canvas and jspdf to export to pdf in a proper and simple way Exporting PDF with jspdf not rendering CSS Where to change default pdf page width and font size in jspdf.debug.js? Export HTML table to pdf using jspdf How to export the Html Tables data into PDF using Jspdf Export HTML page to PDF on user click using JavaScript jsPDF multi page PDF with HTML renderer Add image in pdf using jspdf Generate pdf from HTML in div using Javascript