根据图像宽度和高度设置pdf宽度和高度

时间:2017-12-13 12:09:29

标签: javascript angularjs pdf jspdf

我想将PDF宽度和高度设置为等于图像的宽度和高度。但图像的宽度和高度为0。

我也使用了image.onload()但是没有被调用。

这是HTML:

<span class="col-sm-3 padding0">
    <button id="downloadModel" class="btn btn-md btn-default"
            style="height:100px;width: 210px" 
            ng-click="downloadWorkModel()">
          Download Work Model
    </button>
</span>

CODE:

$scope.downloadWorkModel= function(){
  var image = new Image();
  image.src = 'data:image/png;base64,'+$scope.workData.image;
  document.body.appendChild(image);
  console.log("image width: "+image.width); //coming 0
  console.log("image height: "+image.height); //coming 0
  var pdf = new jsPDF("l", "mm");
  pdf.addImage(image, 'png', 0, 0);
  pdf.save('workModel.pdf');
};

注:

这也不起作用(它不会进入onload) -

$scope.downloadWorkModel= function(){
    var image = new Image();
    var width, height;
    image.onload = function() {
        width= this.width;
        height= this.height;
    };
    image.src = 'data:image/png;base64,'+$scope.workData.image;
    document.body.appendChild(image);
    console.log("image width: "+image.width); //coming 0
    console.log("image height: "+image.height); //coming 0
    var pdf = new jsPDF("l", "mm", [width, height]);
    pdf.addImage(image, 'png', 0, 0);
    pdf.save('workModel.pdf');
};

@mplungjan -

在下载代码之后,下载pdf内容变得太小而无法查看 -

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个。负载非同步,直到负载

后才显示大小
$scope.downloadWorkModel = function() {
  var image = new Image();
  var width, height;
  image.onload = function() {
    width = this.width;
    height = this.height;
    document.body.appendChild(this);
    console.log("image width: " + width);
    console.log("image height: " +height);
    var pdf = new jsPDF("l", "mm", [width, height]);
    pdf.addImage(this, 'png', 0, 0);
    if (done) {  // something needs to decide when this is true
      pdf.save('workModel.pdf'); 
    }
  };
  image.src = 'data:image/png;base64,' + $scope.workData.image;
};

答案 1 :(得分:0)

$scope.downloadWorkModel= function(){
      let image = new Image();
      let width, height;
      image.src = 'data:image/png;base64,'+$scope.workData.image;
      let addedImage = document.body.appendChild(image);
      width = addedImage.width;
      height = addedImage.height;
      console.log("image width: "+width); //coming 0
      console.log("image height: "+height); //coming 0
      var pdf = new jsPDF("l", "mm", [width, height]);
      pdf.addImage(image, 'png', 0, 0);
      pdf.save('workModel.pdf');
    };