Creating Tables with Horizontal Headers using drawHeaderRow in Typescript

Utilizing jsPDF, I was able to generate a table from JSON data and store it in a PDF document. To showcase this functionality, I developed an Angular2/Typescript application. This application creates a table based on my JSON data. My goal now is to use jsPDF to create a table with horizontal headers as demonstrated in the example here. The code snippet for achieving this task is provided below.

// Horizontal - shows how tables can be drawn with horizontal headers
examples.horizontal = function () {
  var doc = new jsPDF('p', 'pt');
  doc.autoTable(getColumns().splice(1,4), getData(), {
    drawHeaderRow: function() {
        // Don't draw header row
        return false;
    },
    columnStyles: {
        first_name: {fillColor: [41, 128, 185], textColor: 255, fontStyle: 'bold'}
    }
  });
  return doc;
};

The full code can be accessed here. It should be noted that this code is in JavaScript, and I am currently seeking guidance on converting it into Typescript. Any helpful insights would be greatly appreciated!

Answer №1

Here is a possible representation of your component:

@Component({
  selector: 'my-app',
  template: 
    `<h1>JSON to PDF Converter</h1>
    <div class="container" id="div1">
        <button id="create" (click)="convert('base')">Generate PDF</button> 
        <button id="create" (click)="convert('horizontal')">
           Generate PDF with horizontal table
        </button> 
    </div>
    `
})
export class AppComponent {
  cols: Array<any> = [{
      title: "Details",
      dataKey: 'details'
    }, {
      title: "Values",
      dataKey: 'values'
   }];

  optionsContainer = {
    base: {},
    horizontal: {
      drawHeaderRow: () => false,
      columnStyles: {
          details: {fillColor: [41, 128, 185], textColor: 255, fontStyle: 'bold'}
      }
    }
  };

  rows: Array<any> = [];

  constructor() {
    const item = {
      "Name" : "John Doe",
      "Age" : "30",
      "Gender" : "Male"
    }; 

    this.rows = Object.keys(item).map((key) => {  
      return { 'details': key, 'values': item[key] };
    });
  }

  convert(action){
    const doc = new jsPDF()
       .autoTable(this.cols, this.rows, this.optionsContainer[action]);
    doc.save('GeneratedPDF.pdf');
  }
}

Check out the Demo on Plunker

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

tying [inactive] to a specific attribute

I have successfully implemented the functionality to disable the button when the email is in the correct format, as shown in my code below. Now, I am looking to implement the following scenario: The Get Started button should be disabled by default If a u ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Populate a map<object, string> with values from an Angular 6 form

I'm currently setting keys and values into a map from a form, checking for validation if the field is not null for each one. I am seeking a more efficient solution to streamline my code as I have over 10 fields to handle... Below is an excerpt of my ...

Issue encountered while trying to utilize the reset function of the FormGroup with the angular2-tinymce plugin

I utilized the FormGroup feature to construct my form, and I required a textarea component. I decided to use the angular2-tinymce library/package to create the form. Here is my HTML template: <form (submit)="submitCallLog($event)" [formGroup]="callLo ...

Unable to simulate a returned value from an import in Jest

Within my module, I have a function called shuffle<T>(a: T[]): T[] that is exported by the random module. While testing two methods in another class that rely on this function, I need to mock it. Here's how I attempted to do so: jest.mock(' ...

Is it the practice of the Signalr server to dispatch a consolidated response for all pending requests when polled using longpolling?

We have been receiving a series of pending requests for a signalr client, which are grouped together as an array in the response of a poll. Here's how it looks: {"C":"s-0,9E632", "M":[ 84 {"H":"MyHub","M":"SetSomething","A":[{"myProp1":"setting","myP ...

Upgrading the import package alias from 'angular2' to '@angular'

Is there a way to update the package alias for import purposes? I am trying to utilize ng2-bootstrap, which requires @angular/core, but I have been referencing it as angular2/core. This mismatch is causing my screen to crash! ...

Tips for personalizing the JSON output with active-model-serializers

I have a Rails 4.2.6 API with active-model-serializers 0.10.0. While AMS works well, I need to return a non-column key-value pair for a letter creation endpoint. Specifically, I want to include the URL where the user can find the created letter: https://{ ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

When attempting to edit a JSON file line by line, an error is thrown: UnsupportedOperation - the file

I encounter an issue when trying to update a json file line by line. The error message UnsupportedOperation: not readable is raised every time I attempt to execute the function as shown below. def modify_json(json_file): with tempfile.TemporaryFile ...

Is there a way to merge two typed Joi schemas together?

I have two different interfaces, where the second one is an extension of the first: interface Core { id: string; } interface User extends Core { firstName: string; } To ensure validation, I utilize Joi schemas. For the Core interface, it's easy ...

Failure of regex expression when applied to a string

I am currently working with DataDog and facing a challenge in extracting the value of a variable from the JSON output to use it in subsequent requests. The issue lies in the fact that the JSON output contains escaped characters (), making it difficult for ...

Does MySQL JSON_OBJECT maintain the value order?

I'm encountering an issue with a query that returns a JSON object. I need the formatted_criteria to display the values in a specific order - first 'Location' and then 'Radius'. However, it seems like the results are sticking to the ...

A step-by-step guide on accessing a JSON configuration file and configuring the parameter for AJAX requests

I have a configuration file named server.json which contains server details in JSON format. { "server": "127.0.0.1" } My objective is to retrieve the value of 'server' from this configuration file and use it in my jQuery functions. For exa ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

Is there a way to adjust the dimensions of my Angular npm slider?

This snippet shows the Angular code I came across this npm slider on npm.js Struggling to adjust the margin of the images as they are sticking, also unsure about modifying the size and other elements using https://www.npmjs.com/package/ng-image-slider. A ...

What is the process for consolidating a TypeScript web application with node modules into a single JavaScript file using the command line

How can I efficiently set up a TypeScript web application with all node modules compiled into one JavaScript file for use in HTML? If my project structure looks like this: ├── node_modules │ └── mathjs │ └── (dependencies, etc.) ...

Angular2 Routing error. Index 1 in the requested path is undefined

Having trouble with routing in Angular 2. I am calling router.navigate from an action within a data table. The strange thing is that sometimes when I click the button to trigger this line, it works perfectly fine, but other times it doesn't. this.rou ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...