Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Canvas content to PDF

I am working on something using HTML5 Canvas. It's all working great, except right now, I can export the canvas content to PNG using Canvas2image. But I would like to export it to PDF. I've made some research and I'm pretty sure it's possible...but I can't seem to understand what I need to change in my code to make it work. I've read about a plugin called pdf.js...but I can't figure out how to implent it in my code.

First part :

function showDownloadText() {
        document.getElementById("buttoncontainer").style.display = "none";
        document.getElementById("textdownload").style.display = "block";
    }

    function hideDownloadText() {
        document.getElementById("buttoncontainer").style.display = "block";
        document.getElementById("textdownload").style.display = "none";
    }

    function convertCanvas(strType) {
        if (strType == "PNG")
            var oImg = Canvas2Image.saveAsPNG(oCanvas, true);
        if (strType == "BMP")
            var oImg = Canvas2Image.saveAsBMP(oCanvas, true);
        if (strType == "JPEG")
            var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);

        if (!oImg) {
            alert("Sorry, this browser is not capable of saving " + strType + " files!");
            return false;
        }

        oImg.id = "canvasimage";

        oImg.style.border = oCanvas.style.border;
        oCanvas.parentNode.replaceChild(oImg, oCanvas);

        showDownloadText();
    }

And the JS to that saves the image :

    document.getElementById("convertpngbtn").onclick = function() {
        convertCanvas("PNG");
    }

    document.getElementById("resetbtn").onclick = function() {
        var oImg = document.getElementById("canvasimage");
        oImg.parentNode.replaceChild(oCanvas, oImg);

        hideDownloadText();
    }

}
like image 841
larin555 Avatar asked Nov 02 '12 19:11

larin555


1 Answers

You need to use 2 plugins for this: 1) jsPDF 2) canvas-toBlob.js

Then add this piece of code to generate light weight PDF:

canvas.toBlob(function (blob) {
    var url = window.URL || window.webkitURL;
    var imgSrc = url.createObjectURL(blob);
    var img = new Image();
    img.src = imgSrc;
    img.onload = function () {
        var pdf = new jsPDF('p', 'px', [img.height, img.width]);
        pdf.addImage(img, 0, 0, img.width, img.height);
        pdf.save(fileName + '.pdf');
    }; 
});
like image 63
Temp O'rary Avatar answered Sep 22 '22 11:09

Temp O'rary