A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporting as a PDF and adding a print option. Any advice or suggestions would be greatly appreciated!

Answer №1

Appreciate your help in enabling me to successfully extract and display the information from an HTML table. Feel free to utilize the code snippet below in your .ts file, by utilizing the ID parameter as I have demonstrated.

displayData(): void {
    let dataToPrint, newWindow;
    dataToPrint = document.getElementById('data-section').innerHTML;
    newWindow = window.open('', '_blank', 'top=0,left=0,height=auto,width=auto');
    newWindow.document.open();
    newWindow.document.write(`
  <html>
    <head>
      <title>Print Data</title>
      <style>
      //........Custom Styling.......
      </style>
    </head>
<body onload="window.print();window.close()">${dataToPrint}</body>
  </html>`
    );
    newWindow.document.close();
}

Answer №2

function createPDF()
{
    var element = document.getElementById('contentToConvert');
    html2canvas(element).then(canvas => {
        // Set necessary 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
    });
}

With the function above, you can easily convert table data into a PDF by providing the ID of the table. ....

Answer №3

If you are utilizing a Mat-Table to organize your data, the following tips will surely be beneficial: Please take note that on button click, the downloadPDF() function will execute.

    import 'jspdf-autotable';
    import * as jsPDF from 'jspdf';
    constructor(){}
    ngOnInit(){}

     documentHeaders = [
    'Work Order #',
    'Product #',
    'Asset',
    'Operator',
    'Task Name',
    'Target Minute',
    'Actual Minute',
    'Productivity %',
    'Status',
    'Start Time',
    'End Time'
     ];
    functionCall(){
    //will return an array with data which is to be displayed}
    downloadPDF() {
    doc.text('Some Text here ', 10, 10);
    const head = [this.documentHeaders];
    let tableArray = new Array();
    let data = this.functionCall('PDF');
    let header: string;
    header = 'Shift Summary ' + formatDate(this.tDate, 'yyyy/MM/dd', 'en');
    console.log(header);

    const doc = new jsPDF();
    doc.text(header, 10, 10);

    ((doc as any).autoTable as AutoTable)({
      head: head,
      body: data,
      theme: 'grid',
      styles: {
        overflow: 'visible',
        cellWidth: 17,
        minCellWidth: 17
        // fillColor: [255, 0, 0]
      },
      headStyles: {
        cellWidth: 17,
        minCellWidth: 17
      },
      didDrawCell: data => {
        console.log(data.column.index);
      }
    });

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

Answer №4

If you need to export a table to Excel, check out this helpful guide.

When it comes to printing, you can utilize JavaScript code in your TypeScript file. For reactive forms, use "this.formName.getValue()", while for traditional forms, simply assign the form value to a variable "a" and print it using document.write(${a.name}).

print(formValue){
        let popupWin;
        let a: type = JSON.parse(JSON.stringify(formValue));
        popupWin = window.open('', '_blank', 
         'top=0,left=0,height=100%,width=auto,toolbar=no,titlebar=no');
        popupWin.document.open();
        popupWin.document.write(`<html> <head>
</head><body onload="window.print();window.close()">
 heya !! ${{ a }}
</body> `)
}

You have the flexibility to incorporate TypeScript code directly into your HTML.

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

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

The ngx-datatable is returning an error message stating that it cannot read the property 'indexes' of an undefined

In my project, I am using ngx-datatable version 15.0.2 and Angular version 8.1.0. Recently, I encountered the following error: ngx-logger.js:852 2019-07-30T15:04:42.930Z ERROR [main.js:4696] TypeError: Cannot read property 'indexes' of unde ...

Adjust the scroll bar to move in the reverse direction

I'm trying to modify the behavior of an overlay div that moves when scrolling. Currently, it works as expected, but I want the scroll bar to move in the opposite direction. For example, when I scroll the content to the right, I want the scroll bar to ...

Revealing a single element in an Angular 6 application that is utilized by several modules

As I am in the process of breaking down a large module into smaller ones, I have encountered an issue that needs to be addressed. Here are the specifics: The Search component is currently being used across multiple components. Initially, it was declared i ...

Issue at 13th instance: TypeScript encountering a problem while retrieving data within an asynchronous component

CLICK HERE FOR ERROR IMAGE export const Filter = async (): Promise<JSX.Element> => { const { data: categories } = await api.get('/categories/') return ( <div className='w-full h-full relative'> <Containe ...

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

Discover the process of transitioning your animations from Angular to CSS

I have successfully implemented a fade-in/out animation using @angular/animation, but now I am looking to transfer this animation to CSS and eliminate the dependency on @angular/animation. Here is my current animation setup (triggering it with [@fadeInOut ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Is there a way to verify if multiple variables in Typescript are null or undefined?

Background To address the issue of checking whether a specific variable is null or undefined, I created the isNullish function. The implementation of this function is shown below. type Nullish = null | undefined; const isNullish = (target: unknown): targe ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Tips on how to create a loop without using a collection in Angular 2

I have a specific quantity and I need to repeat an action that many times. for (var _i = 0; _i < length; _i++) I am trying to replicate this logic in the html template. If I use ngFor, I would typically require a collection, but in this case I only ha ...

What is the process of attaching a property to every object within an array using TypeScript?

In my search for adding a property to each object in an array, I came across a solution in AngularJs on Stack Overflow. However, I attempted the following approach which did not yield the desired outcome. Any assistance would be greatly appreciated. ex ...

What is the best way to showcase a file edited in Emacs within Atom?

The coding project I'm working on is built with Typescript, but I don't believe that's relevant. I've noticed that Emacs has a unique approach to indentation. According to the documentation, in Text mode and similar major modes, the TAB ...

Utilizing Angular 5 alongside the powerful ngx-cookie library and configuring it all within the system

Currently in the process of upgrading a project from AngularJS 1 to Angular 5. In need of a package for cookie manipulation, I came across ngx-cookie. However, facing a hurdle as I cannot alter systemjs.config.js as per the instructions provided, given t ...

Is it possible to adjust the height of the dropdown menu in a mat-select component in Angular 7?

How can I adjust the height of a mat-select in Angular7 to display all items properly? Here is my component file: import { Component, ViewEncapsulation } from "@angular/core"; import { FormControl } from "@angular/forms"; /** @title Select with multiple ...

Utilizing a monorepo approach enables the inclusion of all *.d.ts files

Scenario: In our monorepo, we have 2 workspaces: foo and bar. foo contains the following files: src/file.ts src/@types/baz.d.ts The bar workspace is importing @monorepo/foo/src/file. While type-checking works for the foo workspace, it does not work fo ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Troubleshooting the Angular CLI issue: Module 'ansi-colors' not found

Having issues with my angular project, despite installing the latest version of NodeJs and NPM. When I try to run my project using the ng command, I encounter the following error message: Error: Cannot find module 'ansi-colors' Require stack: - ...

Steps for updating the value of a button in Typescript and React

I currently have a button that manages my language switcher, configured to handle cookies, URL changes, and now I want it to update the translations on the page as well. The <img> tag is utilized for changing the country flag. < ...