使用jspdf将图像url转换为pdf [英] Convert a image url to pdf using jspdf

查看:3062
本文介绍了使用jspdf将图像url转换为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function convertImgToBase64(url)
{
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    img = document.createElement('img'),
    img.src = url;
    canvas.height = img.height;
    canvas.width = img.width;
    var dataURL = canvas.toDataURL('image/jpeg')
    alert(dataURL);
    canvas = null; 
    return dataURL;
  }

var imageurl = 'http://qph.is.quoracdn.net/main-qimg-ca033a73e2ea858908c44905d4c25f4b?convert_to_webp=true';
var som =convertImgToBase64(imageurl);
doc.addImage(som, 'JPEG', 15, 40, 180, 180);
doc.output('datauristring');

但没有任何反应没有生成pdf?我在警告框中得到了正确的base64代码,但图像没有生成?

but nothing happens no pdf is generated ? I am getting the correct base64 code in alert box but image is not generated?

推荐答案

这是我针对同一问题的解决方案。

Here is my solution for the same problem.

let logo = null;

getDataUri(imgUrl, function(dataUri) {
    logo = dataUri;
    console.log("logo=" + logo);
});

function getDataUri(url, cb)
 {
        var image = new Image();
        image.setAttribute('crossOrigin', 'anonymous'); //getting images from external domain

        image.onload = function () {
            var canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight; 

            //next three lines for white background in case png has a transparent background
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = '#fff';  /// set white fill style
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            canvas.getContext('2d').drawImage(this, 0, 0);

            cb(canvas.toDataURL('image/jpeg'));
        };

        image.src = url;
   }

然后生成pdf

    var doc = new jsPDF();

    let left = 15;
    let top = 8;
    const imgWidth = 100;
    const imgHeight = 100;

    doc.addImage(logo, 'PNG', left, top, imgWidth, imgHeight);

    doc.output('dataurlnewwindow'); //opens pdf in new tab

这篇关于使用jspdf将图像url转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆