Date:

Share:

How to Export PDF from HTML in Angular 12

Related Articles

In this article, I will show how to convert HTML to PDF in angular 12 as well as in angular 11. I will also explain ways to create new angular applications as well as ways to install packages using the PowerShell command to export a pdf in an angular application.

While working with any web / windows software, sometimes while reporting, you need advanced functionality like auto-export, multiple export options such as export report with PDF, DOC, XLSX, XLS, CSV, RPT and many other options. Sometimes it is necessary to merge several exported documents into one document that you exported according to the customer’s need.

PDF Abbreviation of Portable Document Format, used to share information in the form of documents. PDF files are more secure than any other format because the data cannot be modified once created. Moreover, the PDF files can be shared and printed as a hard copy. Today, almost every application has the feature to download or export PDF files of different types of data. User can download invoices, bills, articles, reports etc. As a mobile document, we can save it offline for later consumption instead of viewing the same detail via the web.

Today I received a new requirement where I need to export HTML content to PDF with the exact user interface available in HTML. First, I tried it from the back end using the iTextsharp library, but the iTextsharp library provided limited features like only CSS support and basic colors, as well as no support for curves in lines and other CSS properties. Finally, I decided to keep this requirement from the front, and it works for me. Please read the whole article step by step so that you can understand the explanation given and this article can help you.

In my previous example, I explained how to merge multiple PDF files into one PDF using itextsharp in c # and an angular crud example with a web API, as well as some more interesting angular articles you might want to read.

Implementation

Let’s create a new angular app and apply pdf export functionality.

Now, first, we need to install Angular CLI in our system, if you have already installed Angular CLI in your system then you can skip this step.

To install the Angle CLI Open Package Manager Console or Command Prompt and type the command below, and press Enter.

npm install -g @angular/CLI

Note: If you are facing an issue related to npm, you need to download and install the active LTS, or maintain the LTS version of Node.js.

If you are running an older version of angular and would like to update your angular application to the latest version of angular, you can use the following command:

ng update @angular/core @angular/cli --force

Now, we need to create a new angular project.

Create an angular app

To create a new angular project, open the package manager console from API Project, type the following command and press Enter.

ng new ExportPDF

Here, Export PDF Is the name of our Angular project.

Now, we need to create a component in the created Angular project, for that we first need to change the directory and move to the Angular project, then open the package manager console from your WEB API project and write the following command.

cd NameofYourAngulerProject

Here, the name of our angular project Export PDF Then you need to write the command as shown below and click enter.

cd ExportPDF

Next, we need to install a number of directory packages that are required to convert or export HTML content to a PDF file.

npm install jspdf
npm install html2canvas

Update the app component template

Next, we need to update the HTML content, so open up app.component.html File and write the following code in this file:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
 
<div class="container">
  <div>
    <input type="button" class="btn btn-primary" value="Convert" (click)="convetToPDF()" />
  </div>
  <hr />
  <div id="contentToConvert">
    <div class="jumbotron">
      <h1>Codingvila PDF Export Example</h1>
      <p>Codingvila is a educational platform developed to help programmers/beginner by providing articles and blogs on web and software development as well as also for students to provide them free final year academic projects in various technology.</p>
    </div>
    <hr />
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Nikunj</td>
          <td>Satasiya</td>
          <td>nikunj@example.com</td>
        </tr>
        <tr>
          <td>Hiren</td>
          <td>Dobariya</td>
          <td>hiren@example.com</td>
        </tr>
        <tr>
          <td>July</td>
          <td>Dooley</td>
          <td>july@example.com</td>
        </tr>
      </tbody>
    </table>
    <hr />
  </div>
</div>

As you can see in the code above, here we have included and bootstrap CSS files as well as the jquery script. We then created an HTML button and created a click event of that button and read the convetToPDF Function in a click event. We then created a simple paragraph with plain text as well as one boot table with some sample records.

Update the app.component.ts file

Now, we need to update the app.component.ts File to perform the required operation, then you do not need to open the app.component.ts file and update it with the given code:

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 = 'ExportPDF';
  public convetToPDF() {
    var data = document.getElementById('contentToConvert');
    var width = document.getElementById('contentToConvert').offsetWidth;
    html2canvas(data).then(canvas => {
      var imgWidth = 208;
      var imgHeight = canvas.height * imgWidth / canvas.width;
      const contentDataURL = canvas.toDataURL('image/png')
      let pdf = new jspdf.jsPDF('p''mm''a4');
      var position = 5;
      pdf.addImage(contentDataURL, 'PNG', 5, position, imgWidth-7, imgHeight)
      pdf.save('newPDF.pdf');
    });
  }
}

As can be seen in the code above, at the top we will import a directory jspdf and html2canvas And below that, we have a method called by clicking a button from the HTML file, inside the method, we wrote the code to get the HTML content based on the id attribute of the HTML tag and export it to a pdf file.

Now, you just need to launch your project using the following command:

ng s --open

When a user clicks on the conversion button, a click button conversion event will be performed and all the HTML code will be converted to an image, and then the use of a single PDF file will be created and downloaded in the client’s browser.

Productivity:

Export HTML div content to PDF

Summary:

In this article we learned how to convert HTML code to a PDF file as well as the way to convert HTML code to an image and export the image to a PDF file. Here we also learned a way to create a new angular app as well as a way to install a new package library in the angular project, which might help beginners.

.

Source

Popular Articles