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

How to create a service in angular?

September 11, 2021October 3, 2022

Services are same as class with a specific purpose of it. Services can contain method, property and any feature of an application which we can reuse multiple time in our web application. Services also contain a decorator which tell angular how to consume it in our application. Let’s create a…

Read More
Javascript get radio input value in jQuery

How to get radio input value in jQuery ?

October 31, 2021November 5, 2023

While submitting a form or validating a form using the jQuery, we can get all the values of form easily but radio button works differently and we need some extra efforts to fetch the value of radio input. So in this article i will demonstrate to fetch the value of…

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

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

  • 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 Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version