Angular 16 Convert HTML to PDF File Example

Angular 16 Convert HTML to PDF File Example

In this tutorial, you will learn how to convert html to pdf file in angular 16 applications using jspdf and html2canvas.

Convert HTML to PDF File Angular 16

Steps to convert html to pdf file in angular 16 applications using jspdf and html2canvas:

  • Step 1 – Set up an Angular project
  • Step 2 – Install required libraries
  • Step 3 – Create a PDF service
  • Step 4 – Use the PDF service in a component
  • Step 5 – Add the component to your app
  • Step 6 – Run the application

Step 1 – Set up an Angular project

First of all, open your cmd or command prompt and execute the following command on it to install and create a new Angular project using the Angular CLI:

ng new my-new-app

Step 2 – Install required libraries

Now, install the necessary libraries for converting HTML to PDF. You need to use “jspdf” to generate the PDF and “html2canvas” to convert HTML to an image, which can then be added to the PDF.

npm install jspdf html2canvas --save

Step 3 – Create a PDF service

Create a new service that will handle the conversion to PDF. Run the following command to generate a new service:

ng generate service pdf

Open the pdf.service.ts file from the src/app/pdf directory and add the following code:

import { Injectable } from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';

@Injectable({
  providedIn: 'root'
})
export class PdfService {
  public async exportToPdf(elementId: string, fileName: string) {
    const doc = new jspdf.jsPDF();
    const element = document.getElementById(elementId);

    if (!element) {
      console.error('Element not found!');
      return;
    }

    const canvas = await html2canvas(element);
    const imgData = canvas.toDataURL('image/png');
    const imgWidth = 210; // mm (A4 width)
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    doc.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
    doc.save(fileName + '.pdf');
  }
}

Step 4 – Use the PDF service in a component

For this example, you need to create a simple component with a button that, when clicked, will convert a specific HTML element to a PDF. Run the following command to generate a new component:

ng generate component pdf-converter

Open the pdf-converter.component.html file from the src/app/pdf-converter directory and add the following content:

<div #contentToConvert>
  <!-- Add the HTML content you want to convert to PDF here -->
  <h1>Hello, PDF!</h1>
  <p>This is a sample HTML content converted to PDF.</p>
</div>

<button (click)="exportToPdf()">Export to PDF</button>

Now, open the pdf-converter.component.ts file and add the following code:

import { Component, ElementRef, ViewChild } from '@angular/core';
import { PdfService } from '../pdf/pdf.service';

@Component({
  selector: 'app-pdf-converter',
  templateUrl: './pdf-converter.component.html',
  styleUrls: ['./pdf-converter.component.css']
})
export class PdfConverterComponent {
  @ViewChild('contentToConvert', { static: false }) contentToConvert: ElementRef;

  constructor(private pdfService: PdfService) {}

  exportToPdf() {
    const elementId = 'contentToConvert';
    const fileName = 'converted_file';
    this.pdfService.exportToPdf(elementId, fileName);
  }
}

Step 5 – Add the component to your app

Open the app.module.ts file from the src/app directory and import the required components and services. Add the PdfConverterComponent to the declarations and exports arrays.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PdfConverterComponent } from './pdf-converter/pdf-converter.component';
import { PdfService } from './pdf/pdf.service';

@NgModule({
  declarations: [
    PdfConverterComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [PdfService],
  bootstrap: [PdfConverterComponent]
})
export class AppModule { }

Open the app.component.ts file in the src/app directory and add the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-html-to-pdf-example';
}

Step 6 – Run the application

In this step, execute the following commands on cmd to start the angular app:

ng serve

Visit http://localhost:4200/ in your web browser, and you should see the “Hello, PDF!” content along with a “Export to PDF” button. When you click the button, it will generate a PDF file with the content of the contentToConvert div and prompt you to download the file.

Conclusion

In this tutorial, you learned how to convert HTML content to a PDF file in an Angular application using the “jspdf” and “html2canvas” libraries.

Recommended Angular Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *