使用Angular 9,如何从html元素中打印jspdf,同时使用插值法更新html中的值。

问题描述 投票:0回答:1

Html模板

  <div id="download">
    <div>
      {{name}}
    </div>
  </div>

<button type="button" class="btn btn-primary" (click)="captureScreen()">Download</button>

我想在pdf中打印一个新的页面。

  public name = 'Sample';

  captureScreen() {
    this.name = "something else";
    var img;
    var newImage;
    let filename = 'mypdf_'+'.pdf';
    var node = document.getElementById('download');
      domtoimage.toPng(node, { bgcolor: '#fff' }).then(function (dataUrl) {

        img = new Image();
        img.src = dataUrl;
        newImage = img.src;

        img.onload = function () {
          var pdfWidth = img.width;
          var pdfHeight = img.height;
          var doc;
          doc = new jspdf('l', 'px', [pdfWidth, pdfHeight]);

          var width = doc.internal.pageSize.getWidth();
          var height = doc.internal.pageSize.getHeight();

          doc.addImage(newImage, 'PNG', 10, 10, width, height);
          doc.save(filename);

        };

      }).catch(function (error) { });
    }

这段代码对于名称字段中的一个预设值可以正常工作,我想循环浏览一个名称列表,并为pdf中的每个名称打印一个新的页面。但是目前,如果我改变了这个值 this.name = "something else"。它仍然将名称输出为''。样品pdf中的'。

我如何改变名字的值在旅途中和打印pdf不同的名称?

html angular jspdf
1个回答
0
投票

1) 问题是你想使用的是 document.getElementById('download') 查询一个已经渲染的新元素,它仍然在渲染旧的元素,你需要确保先渲染新元素。2)建议使用以下方法查询元素 ViewChild 的角度。

我的建议是

<!-- Use element reference #download to query native element -->
<div #download>
  <div>
    {{name}}
  </div>
</div>
<input type="text" (keyup)="changeElementText($event.target.value)">
<button type="button" class="btn btn-primary" 
(click)="captureScreen()">Download</button>

在ts文件中

 name = 'Sample';

@ViewChild('download', {read: ElementRef})
download: ElementRef;

// Add a modify element logic, make sure modify element and render it before capture screen.
changeElementText(value: string) {
  this.name = value;
}

captureScreen() {
  let img;
  let newImage;
  const filename = 'mypdf_'+'.pdf';
  // This should provide you latest element.
  const node = this.download.nativeElement;
  console.log(node);
  /*** Your capture logic  ***/
}

栈桥演示

© www.soinside.com 2019 - 2024. All rights reserved.