问题描述
我想使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!