Divide the information in the table across several pages for easier printing

I have encountered an architectural challenge with my server-side React app. The app renders charts and tables with page breaks in between to allow a puppeteer instance to print the report for users in another application.

The issue I'm facing is making the data printable without manual pagination. The data needs to flow seamlessly, extending until a page break is necessary, then continuing onto a new page for the next set of information. The complexity lies in the dynamic nature of the data, including varying row heights and widths.

My current approach involves measuring the table's height after each row insertion to determine if it exceeds the max height limit. If it does, a new table with a page break is initiated.

I've explored existing solutions like applying CSS page break rules but found them unsuitable due to specific requirements like custom headers and footers displaying metadata related to the content.

I have provided a sample code snippet in this CodePen, demonstrating the layout I'm trying to achieve. The footer element should appear on both printed pages and reflect the number of rows displayed per page dynamically, which eliminates the possibility of using a static footer within the table structure.

I am considering hiding the table during rendering, gradually calculating its height as rows are added to implement my initial method effectively. However, I remain open to alternative suggestions or insights from others familiar with such challenges.

Answer №1

Okay, I believe I have figured it out. While there is room for improvement and optimization in the code, here is the basic idea: https://codepen.io/nicholaswilson/pen/abJpLYE. Currently, I am dividing the tables after they surpass a certain height, but I plan to refine this later on. The concept is clear.

Essentially, the approach involves constructing a 4D array to manage the instances of tables that require rendering. Then, in componentDidMount() and componentDidUpdate(), new tables are incorporated into the state when necessary:

componentDidMount() {
const { tableData } = this.props;

if (this.state.currentRowIndex === 0) {
  // initial setup
  this.setState((state, props) => {
    const tables = state.tables;
    tables.push([tableData.data[state.currentRowIndex]]); // add first new table and its first row
    return {
      tables,
      currentRowIndex: state.currentRowIndex + 1,
      currentTableIndex: 0
    };
  });
}

}

componentDidUpdate() {
    const { tableData } = this.props;
    if (this.state.currentRowIndex < tableData.data.length) {
      this.setState((state, props) => {
        const tables = state.tables;
        const currentTableHeight = this.tableRefs[this.state.currentTableIndex]
          .clientHeight;
        console.log(
          `Table ${this.state.currentTableIndex} height: ${currentTableHeight}`
        );
        if (currentTableHeight > MAX_TABLE_HEIGHT_IN_PIXELS) {
          // add a new table based on this condition
          tables.push([tableData.data[state.currentRowIndex]]);
          return {
            tables,
            currentRowIndex: state.currentRowIndex + 1,
            currentTableIndex: state.currentTableIndex + 1
          };
        } else {
          tables[state.currentTableIndex].push(
            tableData.data[state.currentRowIndex]
          ); // add new row to existing table
          return {
            tables,
            currentRowIndex: state.currentRowIndex + 1,
            currentTableIndex: state.currentTableIndex
          };
        }
      });
    }
  }

Refer to the codepen for the complete implementation details.

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

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

Retrieve the 'current' scope using a 'master' controller

I have a main controller that I refer to as my 'root' controller, which is declared using the ng-controller attribute. Additionally, I have a few other controllers that are created dynamically through a $routeProvider. I want to define a function ...

Guide on dynamically displaying a page based on the response from express/mssql middleware

I have developed a full stack application that includes a registration feature which successfully adds data to the database. Now, I am looking for a way to conditionally display the home page based on whether the login credentials are correct. Within my l ...

The error message is failing to display the mat error

I've implemented the Mat control date range input control in my project and I'm facing an issue regarding displaying an error message when the user forgets to enter either the start date or end date. Below is the HTML code: <mat-form-field> ...

What is the best way to transform an HTML table into a jQuery array of key-value pairs?

I have an HTML table (without a tbody tag) and I am trying to convert the HTML data into key-value pairs (header-data) in a jQuery array. Currently, when I run the code snippet, the output only displays data from the last row of the table. ************Cur ...

The overflow-x: scroll !important feature is not functioning properly on Samsung Internet when using translated SVGs

I'm experiencing an issue with a div container that is filled horizontally with SVG drawings generated dynamically. The width of the container exceeds the window's width, so I added overflow-x: scroll !important to enable scrolling. However, the ...

Solving the Color Change Mystery in Your Dash Application

My goal is to design a sleek black dashboard, so I acquired a CSS stylesheet that should give my dashboard a black theme. Following the instructions, I created an assets folder in the root directory of my app and added my CSS and JavaScript files there. Da ...

How about incorporating two subtly tilted SVGs for a creative twist on navigation backgrounds?

I am in the process of designing the navigation menu for my website and I have a specific vision in mind. I want to create a unique background using two rectangular SVGs that are slightly rotated off axis and overlapping each other, with their edges extend ...

Choosing between Vue.prototype, Vue.use, and import for each fileWhen it comes

Discover various techniques for implementing a global function in a Vue.js project: time.js // Option 1: if using Vue.use() export default { install: Vue => { Object.defineProperty(Vue.prototype, "time", { return new Date().getT ...

Obtain an item from an array by utilizing the property with Lodash _.find

I currently have an array of objects called memberToChange.checkboxes: ICheckbox[] structured like this: https://i.stack.imgur.com/LyKVv.png Within this setup, there is also a variable named internalNumber with the value "3419". My objective is to locate ...

Struggling to craft an accurate GraphQL request to Yelp

As a newcomer to Apollo, I am facing some challenges while trying to send a basic GraphQL query to the Yelp server. import React from 'react'; import { render } from 'react-dom'; import ApolloClient from 'apollo-boost'; impor ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

Unable to get create-react-app to function properly

Recently, I decided to kick off a new project using React and installed create-react-app via npm. However, when attempting to run the command create-react-app pseudogram, an unexpected error occurred: Aborting installation. Unexpected error. Please report ...

Maintain authentication state in React using express-session

Struggling to maintain API login session in my React e-commerce app. Initially logged in successfully, but facing a challenge upon page refresh as the state resets and I appear as not logged in on the client-side. However, attempting to log in again trigge ...

How to align an element to the bottom using CSS without relying on the parent's height

Is there a way to align an element to the bottom of its container without knowing the exact height? I'm trying to position the "links" div next to the logo text at its bottom, but since the logo size can vary and may even be an image, setting a fixed ...

Select multiple items from a list in HTML using the power of jQuery with a Multi Select

I'm facing an issue with the multi-select box. I attempted to choose multiple values using jQuery, but only the last one seems to be selected. Can someone assist me, please? Below is my code: <script> $(function(){ <?php foreach ($selectd ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

What could be causing the Custom CSS file to stop functioning properly?

Currently, I am in the process of developing an eCommerce website utilizing PHP, Bootstrap, and JQuery. In order to structure the header file for this project, I have followed the following format: <!DOCTYPE html> <html> <head> ...

Developing a typescript React component with a generic callback event handler function passed as a prop

I'm struggling with developing a callback event handler function that can be passed down as a prop to my component. My objective: Allow users to provide a custom callback function that: always accepts the same argument an event (not a react/dom even ...

Difficulty arises in bookmarking slug paths within Next.js SSG

I am currently managing a next js SSG exported application that is operating in nginx. My objective is to transfer it to S3 in the near future. However, I have encountered an obstacle where the slug paths cannot be bookmarked in a browser. Although the ro ...