可以生成QR码并将其导出为pdf,而无需将其渲染为Angular 6中的html [英] Can QR-code be generated and exported to pdf without rendering it to html in angular 6

查看:51
本文介绍了可以生成QR码并将其导出为pdf,而无需将其渲染为Angular 6中的html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 jsPDF 将QR码导出为pdf,而不用html显示.我尝试了很多库- qrcode angularx-qrcode .

I want to export QR-code to pdf using jsPDF without showing it in html. I tried so many libraries- qrcode, angularx-qrcode.

推荐答案

您可以使用 ngx-qrcode 生成QR码.然后从那里将QR代码嵌入模板中,然后将其取回并打印.QR代码仍在DOM中,但可以使用CSS隐藏.尝试以下

You could use ngx-qrcode to generate the QR code. And from there embed the QR code in your template and retreive it back and print it. The QR code is still in the DOM, but it can be hidden using CSS. Try the following

组件

export class AppComponent implements OnInit {
  qrvalue = 'embedded qr';

  ngOnInit() {
  }

  getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
  }

  download() {
    const qrcode = document.getElementById('qrcode');
    let doc = new jsPDF();

    let imageData= this.getBase64Image(qrcode.firstChild.firstChild);
    doc.addImage(imageData, "JPG", 10, 10);

    doc.save('FirstPdf.pdf');
  }
}

模板

<div class="container">
  <ngx-qrcode id="qrcode" [ngStyle]="{'display': 'none'}"  [qrc-element-type]="'img'" [qrc-value]="qrvalue">
  </ngx-qrcode>
  <button (click)="download()" class="btn btn-primary">Download PDF</button>
</div>

firstChild.firstChild

Explanation for firstChild.firstChild

ngx-qrcode 在DOM中的结构如下

Structure of the ngx-qrcode in DOM is as follows

<ngx-qrcode _ngcontent-c2="" id="qrcode" style="display: block;" ng-reflect-ng-style="[object Object]" ng-reflect-element-type="img" ng-reflect-value="embedded qr">
  <div class="qrcode">\
    <img src="data:image/png;base64,iVBORw0KGgoAAAANS...">
  </div>
</ngx-qrcode>

因此,我们使用 document.getElementById('qrcode').firstChild.firstChild 检索包含QR码的 img 标签.

So we use document.getElementById('qrcode').firstChild.firstChild to retrieve the img tag that contains the QR code.

工作示例: Stackblitz

这篇关于可以生成QR码并将其导出为pdf,而无需将其渲染为Angular 6中的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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