DEV Community

Cover image for How To Convert HTML Page To PDF In Angular 11?
Robert Look
Robert Look

Posted on

How To Convert HTML Page To PDF In Angular 11?

This tutorial will use jspdf, html2canvas, and jspdf package for generating pdf files from HTML. any project Many times we get the requirement to convert HTML to pdf in angular content to save in image format or pdf format for sending a report to users email many times. So, here I am going to explain about converting angular HTML to PDF content into PDF files in angular application. And will help you step by step on how to generate HTML to pdf angular 11 app.

How To Convert HTML Page To PDF In Angular 11?

This is image title

Install dependencies

npm install jspdf
npm install html2canvas

update app.component.ts file

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'html-to-pdf-angular-application';
    public convetToPDF() {
        var data = document.getElementById('contentToConvert');
        html2canvas(data).then(canvas => {
            // Few necessary setting options
            var imgWidth = 208;
            var pageHeight = 295;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            var heightLeft = imgHeight;

            const contentDataURL = canvas.toDataURL('image/png')
            let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
            var position = 0;
            pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
            pdf.save('new-file.pdf'); // Generated PDF
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above file, we have imported the jspdf and html2canvas library in our ts file in convert HTML to pdf angular. Below that we have a method in which we will create a button click from an HTML file...

Original Source: https://www.phpcodingstuff.com/blog/how-to-convert-html-page-to-pdf-in-angular-11.html

Top comments (0)