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

Javascript Angular Keypress Event on Input Example

Angular Keypress Event on Input Example ?

September 21, 2022March 16, 2024

Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular Keypress Event on Input with Example. In core javascript we use onkeypress event to handle the key events of input but in angular it there is different way to handle…

Read More
Javascript Angular Dynamic Style CSS with Example

Angular Dynamic Style CSS with Example

October 5, 2022March 16, 2024

In this blog post, we’ll explore Angular dynamic style CSS with example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply styles to elements. In this post, we’ll explore three…

Read More

How to make a reactive form in angular?

August 29, 2021September 10, 2021

Angular has vast library of modules so reactive form is one of the part of angular library. Prerequisites knowledge: Angular HTML CSS Javascript So, let’s start building a from . Steps to create a reactive form in angular Create a new or existing angular project, you can also read this…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version