简体   繁体   中英

How to export canvas image using jsPDF?

I am developing an application that generates some graphics using canvas . Now I need to export these graphics to PDF. What's wrong with my code?

I think the problem is the src using dataURI :

function uri(obj) {
  var canvas = document.getElementById(obj);
  var dataURL = canvas.toDataURL("image/jpeg,1.0");
  var img = document.getElementById('minha_imagem');
  img.src = dataURL;
}

CodePen

This was my question too.

var canvas = document.getElementById(canvas_obj);
doc.addImage(canvas.toDataURL("image/jpeg"), 'JPEG', 0, 0, 100, 100);

Its resulting a pdf with black image.

http://codepen.io/doriclaudino/pen/KprqzR

I think you need use a last version of JSPDF with anothers includes.

I know is too late but I need to do the same and solved it with jsPDF and html2canvas

const canvasElement = await html2canvas(
      document.querySelector('#wave-spectrogram')
    );

You have yout canvasElement, just pass it to jsPDF

pdf.addImage(canvasElement, 'PNG', x, y, width, height)
pdf.save()

That's all

a bit late maybe,

I just had the same issue a month ago, I resolved it like this

function getPDFFileButton () {
            return html2canvas($("#toSaveAsPDF"), {
                background: "#ffffff",
                onrendered: function(canvas) {
                    var myImage = canvas.toDataURL("image/jpeg");
                    var imgWidth = (canvas.width * 25.4) / 240;
                    var imgHeight = (canvas.height * 25.4) / 240; 
                    var table = new jsPDF('p', 'mm', 'a4');
                    table.addImage(myImage, 'JPEG', 15, 2, imgWidth, imgHeight); // 2: 19
                    table.save('Statistiques.pdf');
                }
            });
        }

you can set the background of your generated PDF with this line background: "#ffffff",

Hope this can be helpful,

To avoid a black background of your image when exporting from canvas, choose png compression instead. That works fine !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM