Welcome folks today in this blog post we will be exporting background image with text to pdf document in angular using the jspdf and html2canvas library in typescript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular project using the below command as shown below
ng new sampleproject
cd sampleproject
After that you need to install the below libraries using the npm
command as shown below
npm i html2canvas
npm i jspdf
After that you need to go to app.component.html
file and copy paste the below html code
app.component.html
1 2 3 4 |
<div id="content" #content> <h1>Hello world</h1> </div> <button (click)="exportPDF()">Export to PDF</button> |
As you can see we have defined a div section inside it we have a simple heading of hello world and after that we have got a button which will actually export this heading with background image to pdf document. Now we need to add some custom style css to this html. Now go to app.component.css
file and copy paste the folllowing code
app.component.css
1 2 3 4 5 6 7 8 9 |
#content{ background-image: url('C:/Users/westi/Documents/Lightshot/image.png'); width:200px; height:200px; color:white; line-height: 200px; text-align: center; text-decoration: underline; } |
Now we will write the method which will execute once you hit the button. Now go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { Component, ElementRef, ViewChild } from '@angular/core'; import html2canvas from 'html2canvas'; import jsPDF from 'jspdf'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { @ViewChild('content', { static: true }) el!: ElementRef<HTMLImageElement>; exportPDF() { html2canvas(this.el.nativeElement).then((canvas) => { const imgData = canvas.toDataURL("image/jpeg") const pdf = new jsPDF({ orientation:"portrait" }) const imageProps = pdf.getImageProperties(imgData) const pdfw = pdf.internal.pageSize.getWidth() const pdfh = (imageProps.height * pdfw) / imageProps.width pdf.addImage(imgData, 'PNG', 0, 0, pdfw, pdfh) pdf.save("output.pdf") }) } } |
As you can see we are using the html2canvas
library to take the screenshot of the div section with the background image and then we are exporting it to pdf document using the jspdf
library. And then lastly we are saving the pdf document using the save()
method