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

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require(&apos ...

Using useEffect with promises causing TypeScript errors

useEffect(login, []) In this case, the login function returns a promise and the useEffect hook is triggered without expecting a return value. However, TypeScript shows errors like: Argument of type '() => Promise<void>' is not assi ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Assembly of Components

As someone new to angular, I am currently in the process of building an angular2 application. My goal is to dynamically create a series of DOM components using the data provided below: // Class construct with properties sorted alphabetically export class ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Is there a way to apply a single mongoose hook to multiple methods in TypeScript?

Referencing the response on How to register same mongoose hook for multiple methods? const hooks = [ 'find', 'findOne', 'update' ]; UserSchema.pre( hooks, function( next ) { // stuff } The provided code functions well wi ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

Utilizing aframe in conjunction with Angular 2

Currently I am attempting to integrate Aframe into my angular 2 project. Although I have imported the library in my index.html file, I am still encountering difficulties using the aframe directive. For instance: <a-scene> <a-box color="red"& ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Error: nvm command not found

I downloaded nvm for windows and successfully installed two versions of nodes by following the steps provided in this article. https://medium.com/appseed-io/how-to-run-multiple-versions-of-node-js-with-nvm-for-windows-ffbe5c7a2b47 The node versions I hav ...

Obtain a Service instance using the console

Back in the days of Angular 1, accessing the injector through the console was a convenient way to retrieve any service: angular.element(document.querySelector('html')).injector().get('MyService') This feature proved to be very helpful ...

Guide on displaying tooltip messages for a custom directive in Visual Studio Code

I have developed a custom directive called app-subscriber. When I hover the mouse over it, I want to display a tooltip message saying "This is for subscribers and requires an email address". Is this achievable? Do I need to create a new VS Code extension f ...

Error: Module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef' does not export 'ProSidebar' as requested

Using the pro-side-bar library in React is causing an issue for me. When I run the code, the console shows the following error using the dev tools: Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-pro-sidebar.js?v=913080ef& ...

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...

Receiving a null value when accessing process.env[serviceBus]

Currently, I am focusing on the backend side of a project. In my environment, there are multiple service bus URLs that I need to access dynamically. This is how my environment setup looks like: SB1 = 'Endpoint=link1' SB2 = 'Endpoint=link2&a ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

The browser is failing to send cookies to the backend and is also not properly setting them initially

Greetings everyone, I am currently in the process of securing my spring boot application with HTTP only cookies, transitioning from local storage. However, I have encountered some challenges along the way that even chatGPT couldn't resolve :) Let&apo ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...