Generating PDF files from HTML using Angular 6

I am trying to export a PDF from an HTML in Angular 6 using the jspdf library. However, I am facing limitations when it comes to styling such as color and background color. Is there any other free library besides jspdf that I can use to achieve this? Feel free to check out the demo at the link below.

DEMO

.ts file

export class AppComponent  {
  @ViewChild('reportContent') reportContent: ElementRef;

    downloadPdf() {
    const doc = new jsPDF();
    const specialElementHandlers = {
      '#editor': function (element, renderer) {
        return true;
      }
    };

    const content = this.reportContent.nativeElement;

    doc.fromHTML(content.innerHTML, 15, 15, {
      'width': 190,
      'elementHandlers': specialElementHandlers
    });

    doc.save('asdfghj' + '.pdf');
  }
}

.html file

<div #reportContent class="p-col-8 p-offset-2">
  <table>
    <tr>
      <td style="color: red;background-color: blue;border:solid;">1111
      </td>
      <td style="border:solid;">2222
      </td>
    </tr>
  </table>
</div>

<button pButton type="button" label="Pdf" (click)="downloadPdf()">Export Pdf</button>

Answer №1

    captureScreen() {
        const pdf = new jsPDF('p', 'mm');
        const promises = $('.pdf-intro').map(function(index, element) {
            return new Promise(function(resolve, reject) {
                html2canvas(element, { allowTaint: true, logging: true })
                    .then(function(canvas) {
                        resolve(canvas.toDataURL('image/jpeg', 1.0));
                    })
                    .catch(function(error) {
                        reject('error in PDF page: ' + index);
                    });
            });
        });

        Promise.all(promises).then(function(dataURLS) {
            console.log(dataURLS);
            for (const ind in dataURLS) {
                if (dataURLS.hasOwnProperty(ind)) {
                    console.log(ind);
                    pdf.addImage(
                        dataURLS[ind],
                        'JPEG',
                        0,
                        0,
                        pdf.internal.pageSize.getWidth(),
                        pdf.internal.pageSize.getHeight(),
                    );
                    pdf.addPage();
                }
            }
            pdf.save('HTML-Document.pdf');
        });
    }

To utilize the code above, it is necessary to import jsPDF and html2Canvas into the project:

    import * as jsPDF from 'jspdf';
    import * as html2canvas from 'html2canvas';

For this, the following npm packages need to be installed:

    npm install jspdf --save
    npm install --save @types/jspdf
    npm install html2canvas --save
    npm install --save @types/html2canvas

The next step involves adding the paths to the scripts tag within the angular.json file:

    "node_modules/jspdf/dist/jspdf.min.js"

Add HTML content within the component.html file as shown below:

<div>
  <input type="button" value="CAPTURE" (click)="captureScreen()" />
</div>
<div class="pdf-intro">HTML content</div>
<div class="pdf-intro">HTML content</div>
<div class="pdf-intro">HTML content</div>
<div class="pdf-intro">HTML content</div>

Apply CSS styles as usual within the component.css file for proper rendering.

This approach should help address any related issues you encounter with the implementation.

Answer №2

To export an HTML div with the id='dashboard', you can utilize the jsPDF library along with the dom to image package.

Start by installing the necessary packages:

import * as domtoimage from 'dom-to-image';
import * as FileSaver from 'file-saver';
import * as jsPDF from 'jspdf';

Inside your TypeScript file, include the following code:

domtoimage.toPng(document.getElementById('dashboard'))
    .then(function (blob) {
        var pdf = new jsPDF('l', 'pt', [$('gridster').width(), $('gridster').height()]);
        pdf.addImage(blob, 'PNG', 0, 0, $('gridster').width(), $('gridster').height());
        pdf.save(`${that.dashboardName}.pdf`);
    });

In your HTML file, define the gridster element with the id 'dashboard':

<gridster id='dashboard'></gridster>

Answer №3

To overcome your problem, consider using html2canvas. Make the necessary code adjustments as shown below.

generatePDF() {
const document = new jsPDF();
const contentToCapture = this.contentToCapture.nativeElement;
html2canvas(contentToCapture).then(canvas => {
        const imageData = canvas.toDataURL('image/png');
        // Required settings
        const imageWidth = 208;
        const pageHeight = 295;
        const imageHeight = canvas.height * imageWidth / canvas.width;
        const document = new jspdf('p', 'mm');
        let remainingHeight = imageHeight;
        let currentPosition = 0;

        document.addImage(imageData, 'PNG', 0, currentPosition, imageWidth, imageHeight);
        remainingHeight -= pageHeight;
        while (remainingHeight >= 0) {
            currentPosition = remainingHeight - imageHeight;
            document.addPage();
            document.addImage(imageData, 'PNG', 0, currentPosition, imageWidth, imageHeight);
            remainingHeight -= pageHeight;
        }
        // PDF file created successfully
        document.save('document_name' + '.pdf');
    });

}

Answer №4

[ npm install jspdf
And to install html2canvas package, use given npm command. npm install html2canvas
Following the successful installation, proceed to import it into our component using an import statement.

            > import * as jspdf from 'jspdf';      import html2canvas from
            > 'html2canvas';

                <div id="content" #content>  
            <mat-card>  
                <div class="alert alert-info">  
                    <strong>Html To PDF Conversion - Angular 6</strong>  
                </div>  
                <div>  
                <input type="button" value="CAPTURE" (click)="captureScreen()"/>  
                </div>  
            </mat-card>  
            </div>  
            <div >  
            <mat-card>  
                <table id="contentToConvert">  
                    <tr>  
                    <th>Column1</th>  
                    <th>Column2</th>  
                    <th>Column3</th>  
                    </tr>  
                    <tr>  
                    <td>Row 1</td>  
                    <td>Row 1</td>  
                    <td>Row 1</td>  
                    </tr>  
                    <tr>  
                    <td>Row 2</td>  
                    <td>Row 2</td>  
                    <td>Row 2</td>  
                    </tr>  
                    <tr>  
                    <td>Row 3</td>  
                    <td>Row 3</td>  
                    <td>Row 3</td>  
                    </tr>  
                    <tr>  
                    <td>Row 4</td>  
                    <td>Row 4</td>  
                    <td>Row 4</td>  
                    </tr>  
                    <tr>  
                    <td>Row 5</td>  
                    <td>Row 5</td>  
                    <td>Row 5</td>  
                    </tr>  
                    <tr>  
                    <td>Row 6</td>  
                    <td>Row 6</td>  
                    <td>Row 6</td>  
                    </tr>  
                </table>  

            </mat-card>  
            </div>  

                import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';  
            import * as jspdf from 'jspdf';  
            import html2canvas from 'html2canvas';  

            @Component({  
            selector: 'app-htmltopdf',  
            templateUrl: './htmltopdf.component.html',  
            styleUrls: ['./htmltopdf.component.css']  
            })  
            export class HtmltopdfComponent{  
            public captureScreen()  
            {  
                var data = document.getElementById('contentToConvert');  
                html2canvas(data).then(canvas => {  
                // Few necessary setting options  
                var imgWidth = 208;   
                var pageHeight = 295;    
                var imgHeight = canvas.height * imgWidth / canvas.width;  
                var heightLeft = imgHeight;  

                const contentDataURL = canvas.toDataURL('image/png')  
                let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
                var position = 0;  
                pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)  
                pdf.save('MYPdf.pdf'); // Generated PDF   
                });  
            }  
            } 

                new JsPDF(  
                Orientation, // Landscape or Portrait  

                unit, // mm, cm, in  

                format // A2, A4 etc  
            );  

Answer №5

For a helpful guide, check out this StackBlitz example. Feel free to incorporate it into your demo.

import {jsPDF} from 'jspdf';


public generatePDF() {
   const doc = new jsPDF();
   .....
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

What is the best way to implement multiple HTTP subscriptions in a loop using Angular?

I find myself in a predicament where I need to iterate through an array of strings passed as parameters to a service, which then responds through the HTTP subscribe method. After that, some operations are performed on the response. The issue arises when t ...

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

Ways to obtain the Map object from HTTPClient in Angular

When calling a REST endpoint, the return type is as follows: ResponseEntity<Map<String, List<Object>>> How can I handle this response on the Angular side? I attempted the following approach: let requiredData = new Map<String, Array&l ...

Creating a dual style name within a single component using Styled Components

Need assistance with implementing this code using styled components or CSS for transitions. The code from style.css: .slide { opacity: 0; transition-duration: 1s ease; } .slide.active { opacity: 1; transition-duration: 1s; transform: scale(1.08 ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

Why does Angular-CLI remove an old module when installing a new module using npm?

After adding the ng-sidebar module to my app, I decided to install a new module called ng2-d&d: npm install ng2-dnd --save However, after installing the new module, the old ng-sidebar module was removed from the app-module and an error occurred: C ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...

Exploring the world of third-party APIs

I am currently working on fetching data from an external API and displaying it. In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead. Here is a brief visual ov ...

What sets React.HTMLProps<HTMLDivElement> apart from React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>?

Exploring the differences between interfaces and types in React: interface Properties1 extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> {} interface Properties2 extends React.HTMLProps<HTMLDivElement> ...

Is it possible to verify type property names using a union type?

Given type UnionType = 'prop1' | 'prop2' | 'prop3'; type DerivedType = { prop1: string; prop2: number; prop3: boolean; }; Is there a method to define DerivedType in such a way that if I introduce a new member to UnionT ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Tips for avoiding sending empty fields when using Angular's HttpClient.post method

Whenever I try to send data using the POST method to my Rest API in Angular, it ends up sending empty fields resulting in my database storing these empty values. I want to find a way to stop this from happening so that no empty fields are sent from Angula ...

Extract information from a JSON file and import it into an Angular TypeScript file

How can I retrieve data from a JSON file and use it in an Angular typescript file for displaying on web pages? this.http.get<any>('http://localhost:81/CO226/project/loginResult.json').subscribe((res: Response)=>{ }); Here ...

Is it possible in Typescript to pass method signature with parameters as an argument to another method?

I am working on a React app where I have separated the actions into a different file from the service methods hoplite.actions.ts export const fetchBattleResult = createAsyncThunk<Result>( 'battle/fetchBattleResult', HopliteService.battleRe ...

The module 'DynamicTestModule' has imported an unexpected directive called 'InformationComponent'. To resolve this issue, please include a @NgModule annotation

Even though I found a similar solution on Stackoverflow, it didn't resolve my issue. So, let me explain my scenario. When running the ng test command, I encountered the following error: Failed: Unexpected directive 'InformationComponent' i ...

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

Angular application table enclosed in a form, failing to capture checkbox values

I am working on an Angular 6 project and have a table with checkboxes. My goal is to select a row in the table by checking the checkbox, then click a "select" button to submit the data. However, my current HTML structure does not seem to be functioning as ...