typescript - Hur konverterar jag med Angular: HTML till PDF
Jag använder Angular och jag vill konvertera en tabell från HTML till PDF, detta är min kod i component.ts:
downloadPDF() {
const doc = new jsPDF();
const specialElememtHandlers = {
'#editor'(element, renderer) {
return true;
}
};
doc.fromHTML(this.content.nativeElement.innerHTML, 15, 15, {
width: 190,
elementHandlers: specialElememtHandlers
});
doc.save('test.pdf');
}
och min HTML-kod är:
<button (click)="downloadPDF()">Save as PDF</button>
Jag kan faktiskt ladda ner en pdf, men den är helt vit.
Svar #1
Installera först det här paketet
npm install jspdf
Och att installera html2canvas-paketet.
npm install html2canvas
Importera det till vår komponent med import-satsen.
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
i din TS-kod:
import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
@Component({
selector: 'app-htmltopdf',
templateUrl: './htmltopdf.component.html',
styleUrls: ['./htmltopdf.component.css']
})
export class HtmltopdfComponent{
public captureScreen()
{
var data = document.getElementById('contentToConvert'); //Id of the table
html2canvas(data).then(canvas => {
// Few necessary setting options
let imgWidth = 208;
let pageHeight = 295;
let imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
let position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
pdf.save('MYPdf.pdf'); // Generated PDF
});
}
}
