Ad

Use Html2canvas With JsPDF To Save A PDF Of A Page

- 1 answer

I want to create a PDF from the contents of a div. I am using jsPDF. The problem is none of my styles are passed, thus the PDF looks off. I then came across an article that uses html2canvas to take a screenshot of the page.

When I try the example provided it gives me this error:

uncaught exception: Invalid orientation: [object object] <unknown>

How do I solve this problem?

Here is the JS I am using:

(function(){
var content = $('#content'),
    cache_width = content.width(),
    a4  =[ 595.28,  841.89];  // for a4 size paper width and height

$('#pdf').on('click',function(){
    $('body').scrollTop(0);
    createPDF();
});
//create pdf
function createPDF(){
    getCanvas().then(function(canvas){
        var 
        img = canvas.toDataURL("image/png"),
        doc = new jsPDF({
          unit:'px', 
          format:'a4'
        });     
        doc.addImage(img, 'JPEG', 20, 20);
        doc.save("{{this.['Student Last Name']}}-{{this.['Student Name']}}-umpire-incident-report.pdf");
        content.width(cache_width);
    });
}

// create canvas object
function getCanvas(){
    content.width((a4[0]*1.33333) -80).css('max-width','none');
    return html2canvas(content,{
        imageTimeout:2000,
        removeContainer:true
    }); 
}

}());
Ad

Answer

As I said in a comment, removing my CSS solves the problem. As @Kaiido pointed out, html2canvas hasn't implemented some CSS.

I have the following CSS in my stylesheet:

hr{
    border: 0;
    height: 1px;
    background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(0,0,0,0)), color-stop(50%,rgba(0,0,0,0.75)), color-stop(100%,rgba(0,0,0,0)));
    background: -webkit-linear-gradient(left, rgba(0,0,0,0) 0%,rgba(0,0,0,0.75) 50%,rgba(0,0,0,0) 100%);
    background: linear-gradient(to right, rgba(0,0,0,0) 0%,rgba(0,0,0,0.75) 50%,rgba(0,0,0,0) 100%);
    margin:1rem 0;
    padding:0 !important;
}

When I remove the gradients, it works perfectly fine. Instead of removing this code from my CSS, I can simply override using inline styles and it works fine!

Ad
source: stackoverflow.com
Ad