I have a component (Angular 6) which is an aggregation of several components. This produces a long HTML (I am using Bootstrap 4). Now I want to convert this HTML to PDF. I have
Step 1: Install required packages
npm install jspdf jspdf-autotable
Step 2: Import the installed packages to use
import jsPDF from 'jspdf';
import 'jspdf-autotable';
Step 3: If your data has images, convert images to Base64
tabledata = [{
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Joseph',
domain: 'Angular 9'
},
{
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Vani',
domain: 'Angular 8'
}, {
img: 'https://i.picsum.photos/id/258/536/354.jpg',
name: 'Raj',
domain: 'React.js'
},
];
The above is data with images converted to base64. The convert function looks like:
convertImagetoBase64(url, callback) {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
const reader = new FileReader();
reader.onloadend = () => {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
Let's convert the image URL to base64 before we bind to the table in HTML.
this.tabledata.forEach(elem => {
this.convertImagetoBase64(elem.img, (b64Img) => {
elem.img = b64Img;
});
Now bind the data to the table. If you don't want to display the table in the front end, just style to display none as in the below code:
The Generate Pdf function looks like:
app.component.ts
generatePdf(){
doc.autoTable({
html: '#imgTable',
bodyStyles: { minCellHeight: 20 },
theme: 'grid',
styles: { valign: 'middle', overflow: 'linebreak', halign: 'center', minCellHeight: 21 },
pageBreak: 'avoid',
columnStyles: {
2: { cellWidth: 22, minCellHeight: 22 },
},
headStyles: { fillColor: '#f2f2f2', textColor: '#000', fontStyle: 'bold', lineWidth: 0.5, lineColor: '#ccc' },
didDrawCell: (data) => {
if (data.column.index === 2 && data.cell.section === 'body') {
const td = data.cell.raw;
const img = td.getElementsByTagName('img')[0];
// let dim = data.cell.height - data.cell.padding('vertical');
// let textPos = data.cell.textPos;
doc.addImage(img.src, data.cell.x + 1, data.cell.y + 1, 19, 19);
}
}
});
doc.save('yourpdfname.pdf');
}
Example pdf generation looks like:
For more Pdf format without table visit helperscript.com