简体   繁体   中英

Barcode doesn't shown on PDF in Angular 6 (jsPDF & jsBarcode)

I want to print my HTML to PDF. Everything is almost OK, but barcode shown correctly only on my web application page, but on the PDF shown partly, I don't know why.

my HTML code

<div *ngIf="flight" #content>
<div>
<label>departureCity: </label> {{flight.departureCity}}
</div>
<div>
<label>destinationCity: </label> {{flight.destinationCity}}
</div>
<label>List of tickets: </label>
<div *ngFor="let ticket of flight.tickets">
<label>Name: </label> {{ ticket.name }}<br/>
<label>Surname: </label> {{ ticket.surname }}<br/>
</div>
<svg id="barcode1"></svg>
<hr/>
</div>
<button (click)="downloadPDF()"> Download </button>

my typescript code

@ViewChild('content') content: ElementRef;
public downloadPDF() {
const doc = new jsPDF(this.getBarcode());

const specialElementHandlers = {
  '#editor': function(element, renderer) {
    return true;
  }
};
const content = this.content.nativeElement;
doc.fromHTML(content.innerHTML, 15, 15, {
  'width': 190,
  'elementHandlers': specialElementHandlers
 });
doc.save('Test.pdf');
}

getBarcode() {
JsBarcode('#barcode1', this.getOrderNumber(), {
  format: 'CODE128',
  displayValue: true,
    <!---->
});
}

getOrderNumber() {
const number = 'R' + Math.floor(Math.random() * 100000000000);
return number;
}

On my web application page everything is OK:

在此处输入图片说明

But on the PDF barcode shown only partly

在此处输入图片说明

Try canvg for that to covert SVG to Canvas. Then convert the canvas to base64 string using .toDataURL().

More detailed answer is here https://stackoverflow.com/a/35788928/2090459

And Demo here enter link description here

Note that this means the SVG is converted to a bitmap before being integrated into the PDF, so you'll lose the benefits of a vector format

My answer, now it works.

I've changed in my HTML code:

<canvas id="barcode"></canvas>

And add this to my typescript code:

const canvas = document.getElementById('barcode') as HTMLCanvasElement;
const jpegUrl = canvas.toDataURL('image/jpeg');
doc.addImage(jpegUrl, 'JPEG', 20, 150, 50, 50);`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM