Tips for rearranging objects within a jsPDF document to prevent vertical overlap when a table grows in size

I am new to React and Javascript. I have been struggling to find a solution to my issue while trying to create a .pdf document for a customer invoice using "jsPdf" along with its plugin "jspdf-autoTable".

So far, everything is being generated correctly by assigning XY starting coordinates to each element (text, image, table) in the javascript code. My problem arises when I have two tables, Table A and Table B, positioned vertically next to each other. As Table A increases its rows, it eventually starts overlapping with Table B which has a fixed number of rows.

Is there a way to prevent the overlap between Table A and Table B, ensuring that all content below Table A dynamically moves downwards as Table A expands?

For example:

const generatePDF = () => {

        const unit = "pt";
        const size = "A4";
        const orientation = "portrait";

        const doc = new jsPDF(orientation, unit, size);

        let contentA = {
            head: [["Item", "Quantity", "Price", "Item Total"]],
           
            body: [
                ['Water Bottle A', '1', '8.99', '8.99'],
                ['Water Bottle B', '1', '8.99', '8.99'],
                ['Water Bottle C', '1', '8.99', '8.99'],
                ['Water Bottle D', '1', '8.99', '8.99'],
               ],
            foot: [['', '', 'Total:', '35.96']],
            margin: 40,
            tableLineWidth: 0.5,
            tableLineColor: "black",
            tableWidth: 'auto',
            startY: 100,
            theme: 'striped',
            pageBreak: 'auto',
        }

        let contentB = {
            head: [["Subtotal", "$35.96"]],
           
            body: [
                ['Taxes', '$4.49'],
                ['Payment Method:', 'Cash'],
               ],
            foot: [['Total:', '35.96']],
            margin: 40,
            tableLineWidth: 0.5,
            tableLineColor: "black",
            tableWidth: 'auto',
            startY: 150,
            theme: 'striped',
            pageBreak: 'auto',
        }

        doc.autoTable(contentA)
        doc.autoTable(contentB)
        doc.text('Thank you for your purchase!', 150, 800);
        doc.save("my-report-document.pdf")
}

Currently, all rows are static (in my app, I iterate through an array of objects to generate the rows). If I add 30 more rows to the body property of "contentA", the tables will overlap.

The "startY" property determines the starting 'Y' coordinate for each table. It is acceptable if the content below Table A extends to a second page, as long as the vertical overlap is eliminated.

Any assistance would be greatly appreciated.

Answer №1

Here is a helpful tip:

doc.lastAutoTable.finalY

You can incorporate it into your code like this:

doc.text('Expressing gratitude for shopping with us!', 150, doc.lastAutoTable.finalY + 30);

Answer №2

const bottomY = doc.lastAutoTable.finalY;
doc.text('Please send payments to the address in Commerce City', 10, doc.lastAutoTable.finalY + 15);

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 method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

Utilizing React for handling data exchange between child and parent components

I am still learning about React and material-ui, and I am exploring how to pass data from a child component to a parent component to update the parent state. Currently, when I try to update the state with a new date, it is being logged in the console but t ...

NextJS: encountered an error with fallback enabled

I have my NextJS setup on Vercel and here is how I configured getStaticPaths: const paths = posts.map((post) => ({ params: { player: post.player, id: post.id }, })) return { paths, fallback: true } However, when I set the fallback to true, I ...

A guide on implementing a .click function with jQuery

I have a code snippet that is supposed to add 100 to a number in a MySQL table when a button is clicked. However, the code does not work as expected. When I click the button, nothing happens, but if I refresh the page, it adds 100 to the number. Can some ...

When multiple input fields with an iterative design are using the same onChange() function, the specific event.target.values for each input

I'm in the process of developing a dynamic select button that adjusts based on the information entered into the iterative input fields I've set up. These input fields all utilize the same onChange() function. for (let i = 0; i < selectCount; i ...

The height of a DIV element can vary based on

Looking at this div structure: DIV3 has a fixed height. The nested DIV5 will be receiving content from Ajax, causing its height to change. Additionally, there are some DHTML elements inside it that also affect the height. DIV5 has a fixed min-height set. ...

The collaboration of Node.js and React.js on a single server

Separate ports are used for Node and React, but API requests from the React app can be proxied to the Node URL. I have opted not to implement server-side rendering for React in order to serve the React app. Instead, I build the React app each time there i ...

Looking to adjust the appearance of the MUI button depending on its current state

I have searched extensively for a solution to my specific React issue but have come up empty-handed. I am relatively new to React, so any help would be greatly appreciated. The problem I'm facing is with a MUI button that changes its state depending ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

How can I get Keyboard.dismiss to function properly in React Native?

I'm attempting to implement a feature where the keyboard automatically dismisses when a user logs in. Despite using Keyboard.dismiss, I'm facing an issue where the keyboard remains on screen and needs to be manually closed on the next page. Can a ...

Two separate entities link to a shared occurrence

Two namespaces are at play here: '/' and /notification If I trigger an event in the '/' namespace, how can I listen to the same event in the '/notification' namespace? It would be helpful if someone could provide an explanati ...

Ways to display or conceal text using Vanilla JavaScript

I am struggling to toggle text visibility using Vanilla JS. Currently, I can only hide the text but cannot figure out how to show it again. <button id="button">my button</button> <div> <p id="text">Hello</p& ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

Increase the jQuery Array

After successfully initializing an Array, how can I add items to it? Is it through the push() method that I've heard about? I'm having trouble finding it... ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

Looking to generate an HTML table using JavaScript?

Similar Question: Create HTML table from a Javascript array I have received an array that looks like this var univArray = new Array( {name: "Stanford University", nick: "Stanford", ownership: "private", sys: "n/a", SATh: 1550, SATl: 1360, tui ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

The renderer for PDF files in React is called React

Struggling to register a custom font in react-pdf/renderer? I found a solution by declaring it as a variable. const poppins = 'https://example.com/fonts/Poppins/poppins-regular-webfont.woff' Font.register({family: "Poppins", src: poppi ...

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

How can I convert JSON data from an array to an array of objects using JavaScript?

My goal is to load data into an ag-grid. I have obtained the json data in the following format: {"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}} In order to pass it to the grid, I need to transform it to this format: {"my_data":[{"labels" ...