Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Multiple Ways To Convert Html To Pdf In Angular

Multiple Ways to Convert Html to PDF in Angular ?

Aman Jain, April 22, 2022November 5, 2023

There is multiple ways to convert HTML to PDF in angular, some are native and some are using the packages. While creating web application we need to manage to create PDF from the same html so in this tutorial i will show you multiple ways to create html to PDF.

There is no perfect package which can create exact same html to PDF but in native we can achieve one through print method of window but its has their own limitations too.

In this article i will use multiple packages to show you the different purpose and usage of packages.

Html to PDF using pdfmake and html-to-pdfmake package

In this method we will use three packages pdfmake, html-to-pdfmake and jspdf. pdfmake is a Client/server side PDF printing in pure JavaScript. pdfmake permits to easily create a PDF with JavaScript; however there is no support of HTML code, so html-to-pdfmake package handle this feature.

Let’s start it with example

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 3: Create component

Now, create two components one for set the cookie and other for get the cookie in different pages

ng g c HtmlToPdfMake

this will create a folder html-to-pdf-make and src/app/html-to-pdf-make/html-to-pdf-make.component.html , src/app/html-to-pdf-make/html-to-pdf-make.component.ts file too as below

Step 3: Install pdfmake, html-to-pdfmake package

Install both packages using npm in project directory

npm install pdfmake @types/pdfmake html-to-pdfmake --save

Step 4: Update Component and template

We have installed the necessary packages now import packages in component and update html in template

import { Component, ElementRef, ViewChild,OnInit } from '@angular/core';
import * as pdfMake from "pdfmake/build/pdfmake";  
import * as pdfFonts from "pdfmake/build/vfs_fonts";  
declare var require: any;
const htmlToPdfmake = require("html-to-pdfmake");
(<any>pdfMake).vfs = pdfFonts.pdfMake.vfs;

@Component({
  selector: 'app-html-to-pdf-make',
  templateUrl: './html-to-pdf-make.component.html',
  styleUrls: ['./html-to-pdf-make.component.css']
})
export class HtmlToPdfMakeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @ViewChild('pdfTable')
  pdfTable!: ElementRef;
  
  public downloadAsPDF() {
    const pdfTable = this.pdfTable.nativeElement;
    var html = htmlToPdfmake(pdfTable.innerHTML);
    const documentDefinition = { content: html };
    pdfMake.createPdf(documentDefinition).download(); 
     
  }
}

and template

<div class="container">
    <div id="pdfTable" #pdfTable>
      <h2>Angular HTML To PDF Using PDFMAKE and htm-to-pdfmake Example - readerstacks.com</h2>
  
      <table class="table">
        <thead>
          <tr>
            <th>S.no.</th>
            <th>Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>Rem</td>
            <td>Rem@yopmail.com</td>
          </tr>
          <tr>
            <td>2</td>
            <td>Joe</td>
            <td>joe@yopmail.com</td>
          </tr>
          <tr>
            <td>3</td>
            <td>Kuple</td>
            <td>Kuple@yopmail.com</td>
          </tr>
        </tbody>
      </table>
    </div>
    <button class="btn btn-primary" (click)="downloadAsPDF();">Export To PDF</button>
  </div>

I also added the bootstrap to it so here is the output of html

Screenshot 2022 04 22 at 12.17.02 AM 1
HTML
Screenshot 2022 04 22 at 12.16.54 AM
GENERATED PDF

As you can see this library not loading the proper css so this is the cons of this. you can read more about thease library here html-to-pdf-make and pdfmake.

Html to pdf using native APIs of javascript

Javascript also provides its own APIs to print pdf using

window.open( '', 'PRINT', 'height=650,width=900,top=100,left=150' )

Here is the example

import { Component, ElementRef, ViewChild,OnInit } from '@angular/core';
import * as pdfMake from "pdfmake/build/pdfmake";  
import * as pdfFonts from "pdfmake/build/vfs_fonts";  
declare var require: any;
const htmlToPdfmake = require("html-to-pdfmake");
(<any>pdfMake).vfs = pdfFonts.pdfMake.vfs;

@Component({
  selector: 'app-html-to-pdf-make',
  templateUrl: './html-to-pdf-make.component.html',
  styleUrls: ['./html-to-pdf-make.component.css']
})
export class HtmlToPdfMakeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @ViewChild('pdfTable')
  pdfTable!: ElementRef;
  
  public downloadAsPDF() {
    const pdfTable = this.pdfTable.nativeElement;
    var html = htmlToPdfmake(pdfTable.innerHTML);
    const documentDefinition = { content: html };
    pdfMake.createPdf(documentDefinition).download(); 
     
  }
}

Html to pdf using jsPdf and dom-to-image library

In this method we will create the image of Dom and then pass it to jsPdf, Pros of this library is we can archive almost same layout in pdf because we are passing image of dom by taking the screenshot.

So first install the packages

npm install dom-to-image jspdf  --save
npm i --save-dev @types/dom-to-image

Now in component

import { Component, ElementRef, ViewChild,OnInit } from '@angular/core';
import domtoimage from 'dom-to-image';
import  jsPDF from 'jspdf';

@Component({
  selector: 'app-html-to-pdf-make',
  templateUrl: './html-to-pdf-make.component.html',
  styleUrls: ['./html-to-pdf-make.component.css']
})
export class HtmlToPdfMakeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @ViewChild('pdfTable')
  pdfTable!: ElementRef;
  
  public downloadAsPDF2() {
    // const pdfTable = this.pdfTable.nativeElement;
    // var html = htmlToPdfmake(pdfTable.innerHTML);
    // const documentDefinition = { content: html };
    // pdfMake.createPdf(documentDefinition).download(); 
     
  }
  public downloadAsPDF() {
    let div = this.pdfTable.nativeElement;
   
    var img:any;
    var filename;
    var newImage:any;


    domtoimage.toPng(div, { bgcolor: '#fff' })

      .then(function(dataUrl) {

        img = new Image();
        img.src = dataUrl;
        newImage = img.src;

        img.onload = function(){

        var pdfWidth = img.width;
        var pdfHeight = img.height;

          // FileSaver.saveAs(dataUrl, 'my-pdfimage.png'); // Save as Image

          var doc;

          if(pdfWidth > pdfHeight)
          {
            doc = new jsPDF('l', 'px', [pdfWidth , pdfHeight]);
          }
          else
          {
            doc = new jsPDF('p', 'px', [pdfWidth , pdfHeight]);
          }


          var width = doc.internal.pageSize.getWidth();
          var height = doc.internal.pageSize.getHeight();


          doc.addImage(newImage, 'PNG',  10, 10, width, height);
          filename = 'mypdf_' + '.pdf';
          doc.save(filename);

        };


      })
      .catch(function(error) {

       // Error Handling

      });
 
  }
}

OUTPUT :

Screenshot 2022 04 22 at 12.17.02 AM 2
HTML
Screenshot 2022 04 22 at 12.37.59 AM
PDF

As you can see its almost identical.

Now you can choose according to your need.

Related

Javascript Angular angularconvertorHTMLpdf

Post navigation

Previous post
Next post

Related Posts

Uncategorized update page data without reload

How to update page data without reload in jQuery?

October 24, 2021November 17, 2023

If you are beginner then this post is for you. For showing the new content on page without refresh we will use JQuery Reload Page without Refresh and server side PHP. In this article, I will demonstrate to show the latest content from server without refreshing the page. This is…

Read More

How to use ngFor and ngIf on same element in angular 12 ?

October 23, 2021October 23, 2021

In this tutorial we are going to resolve the issue of using *ngFor and *ngIf on same element. so, in angular ngIf and ngFor is a structural directives, and we can not use two structural directive on same element.ngIf is used for to make conditional logic and ngFor is used…

Read More
Javascript How to check user agent in angular

How to check user agent in angular ?

October 18, 2022March 16, 2024

In this post, we will show you how to check user agent in Angular. user-agent header is a string that contains information about the browser and operating system. It is set by the browser and sent to the server with every request. It can also be used to determine if…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version