在Html2Canvas中将JPEG的透明部分转换为白色

时间:2016-03-08 13:30:18

标签: javascript jquery jspdf html2canvas

我正在使用Html2Canvas将文档导出为PDF,但它将JPEG的透明部分转换为黑色(我知道它应该如何去)。但我希望它将透明背景转换为白色。在线解决方案中,建议改变脚本(Html2Canvas或JSPDF),但我不想这样做,因为它并不总是可行的。实现这一目标的最佳方法是什么?

html2canvas(form, {
imageTimeout: 2000,
removeContainer: true,
background:'#FFF',
onrendered: function (canvas) {
    var img = canvas.toDataURL("image/jpeg");
    var doc = new jsPDF({
        unit: 'pt',
        format: 'a4',
    });

    // pageHeight= doc.internal.pageSize.height;
    var image = new Image();
    image = Canvas2Image.convertToJPEG(canvas);
    doc.addImage(img, 'JPEG', 12, 15);
    var corte = (vm.a4[1] * 1.33333) - 30;
    var croppingYPosition = corte;
    var count = (image.height) / corte;
    for (var i = 1; i < count; i++) {
        doc.addPage();
        var sourceX = 0;
        var sourceY = croppingYPosition;
        var sourceWidth = image.width;
        var sourceHeight = corte;
        var destWidth = sourceWidth;
        var destHeight = sourceHeight;
        var destX = 0;
        var destY = 0;
        var canvas1 = canvas;
        canvas1.setAttribute('height', corte * i);
        canvas1.setAttribute('width', destWidth);
        var ctx = canvas1.getContext("2d");
        ctx.drawImage(image, sourceX,
                             sourceY,
                             sourceWidth,
                             sourceHeight,
                             destX,
                             destY,
                             destWidth,
                             destHeight);
        var image2 = new Image();
        image2 = Canvas2Image.convertToJPEG(canvas1);
        var image2Data = image2.src;
        doc.addImage(image2Data, 'JPEG', 12, 15);
        croppingYPosition += destHeight;
    }
    doc.save('firstPDF.pdf');
    $('.pdfTemplates').css('width', '100%');
}

});

1 个答案:

答案 0 :(得分:0)

从未真正使用过Canvas2Image,但这是一个你可以尝试的黑客。

  1. 第1步:而不是
  2.   

    convertToJPEG(画布)

    做一个

      

    Canvas2Image.convertToPNG(画布)

    PNG理想情况下应保持透明度。

    1. 第2步:现在您可以将图像绘制到白色画布上,从而结果将是具有白色背景的JPEG

      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0,0,canvas1.width,canvas1.height);
      ctx.drawImage(image, sourceX,
                           sourceY,
                           sourceWidth,
                           sourceHeight,
                           destX,
                           destY,
                           destWidth,
                           destHeight);