I need help creating a PDF from HTML content within an Angular application.
Check out my main component:
Main Component HTML:
<div class="container-fluid">
<!-- ... other HTML content ... -->
<div class="table-responsive">
<table class="table" #pdfTable>
<!-- Table content -->
</table>
</div>
<app-pdf-explosion-insumos-proyecto [tableElement]="pdfTable"></app-pdf-explosion-insumos-proyecto>
</div>
Main Component TypeScript:
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
// ... other imports ...
@Component({
selector: 'app-explosion-insumos-concepto',
templateUrl: './explosion-insumos-concepto.component.html',
styleUrls: ['./explosion-insumos-concepto.component.css']
})
export class ExplosionInsumosConceptoComponent implements OnInit {
// ... other properties ...
@ViewChild('pdfTable', { static: false }) pdfTable: ElementRef;
// ... constructor and ngOnInit ...
}
Now, let's take a look at the child component:
Child Component HTML:
<button type="button" mat-raised-button mat-min-fab class="btn btn-error btn-round btn-fab float-right" (click)="downloadPDF()">
<i class="material-icons">picture_as_pdf</i>
</button>
Child Component TypeScript:
import { Component, ElementRef, OnInit, Input, ViewChild } from '@angular/core';
import 'moment/locale/es';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
@Component({
selector: 'app-pdf-explosion-insumos-proyecto',
templateUrl: './pdf-explosion-insumos-proyecto.component.html',
styleUrls: ['./pdf-explosion-insumos-proyecto.component.css']
})
export class PdfExplosionInsumosProyectoComponent implements OnInit {
@Input() tableElement: ElementRef;
constructor() {}
ngOnInit(): void {}
downloadPDF() {
if (this.tableElement) {
html2canvas(this.tableElement.nativeElement).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const doc = new jsPDF({
orientation: 'landscape',
unit: 'px',
format: [canvas.width, canvas.height]
});
doc.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
doc.save('tabla-explosion-insumos.pdf');
});
}
}
}
I've managed to pass the HTML table data from the parent component to the child successfully. However, I'm facing issues with nativeElement
being undefined when performing certain operations.