web端使用lodop实现打印问题总结

lodop官网

一、有些电脑能打印图片,有些电脑不能打印图片
在这里插入图片描述
解决方案:把图片转为base64
我们的图片是oss上的图片,需要把oss的桶设置为可跨域
在这里插入图片描述
请求图片资源,把图片转化为base64

function getBase64ImageByWidthHeight(path, width, height) {
    
    
  return new Promise((resolve, reject) => {
    
    
    fetch(path)
      .then(response => response.blob())
      .then(blob => {
    
    
        let img = new Image();
        let reader = new FileReader();
        reader.onloadend = function() {
    
    
            resolve(reader.result);
          img.src = reader.result;
        };
        reader.readAsDataURL(blob);
      });
  });
}

在这里插入图片描述
二、图片不清晰,出现虚线问题
解决方案:把图片设置成需要的宽高,重新生成canvas

function getBase64ImageByWidthHeight(path, width=0, height=0) {
    
    
  return new Promise((resolve, reject) => {
    
    
    fetch(path)
      .then(response => response.blob())
      .then(blob => {
    
    
        let img = new Image();
        let reader = new FileReader();
        reader.onloadend = function() {
    
    
          if (width != 0 && height != 0) {
    
    
            img.onload = function() {
    
    
              let canvas = document.createElement("canvas");
              let ctx = canvas.getContext("2d");
              console.log("radio==",window.devicePixelRatio);
              let radio = 2;
                // 设置物理像素
                canvas.width = width * radio;
                canvas.height = height * radio;
                // 设置逻辑像素
                canvas.style.width = `${
    
    width}px`;
                canvas.style.height = `${
    
    height}px`;
              ctx.drawImage(img, 0, 0,  canvas.width, canvas.height);
              ctx.scale(radio, radio);
              let base64data = canvas.toDataURL();
              resolve(base64data);
              console.log(base64data);
            };
          }else{
    
    
            console.log("base")
            resolve(reader.result);
          }
          img.src = reader.result;
        };
        reader.readAsDataURL(blob);
      });
  });
}

猜你喜欢

转载自blog.csdn.net/weixin_40466351/article/details/139658912