What is the best way to define coordinates or set margins for the autoTable component in jsPdf when using React js?

While working with the jsPdf library to create a PDF in React, I am encountering an issue where I am unable to set margins for the autoTable when there are multiple tables on a single page.

Below is the code snippet:

import React from "react";

var { jsPDF } = require("jspdf");
require("jspdf-autotable");

function ShowPdf() {
  const [head] = React.useState(["Name", "Email", "Country"]);
  const [body] = React.useState([
    ["David", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7b7e69767b5f7a677e726f737a317c7072">[email protected]</a>", "Sweden"],
    [...]
  ]);
  const generatePDF = () => {
    let doc = new jsPDF("p", "pt", "a4");

    doc.setFont("Calibri", "bold");
    doc.setFontSize(14);
    doc.setTextColor(14, 3, 64);
    doc.text("Table 1", 20, 140);
    doc.line(20, 142, 550, 142);

    doc.text("Table 2", 20, 300);
    doc.line(20, 302, 550, 302);

    doc.autoTable({
      margin: { top: 150, left: 20, bottom: 30 },
      head: [head],
      body: [body[0], body[1], body[2], body[3], body[4]],
    });

    doc.autoTable({
      margin: { top: 400, left: 20, bottom: 30 },
      head: [head],
      body: [body[0], body[1], body[2], body[3], body[4]],
    });

    window.open(doc.output("bloburl"), "_blank");
  };
  return (
    <div>
      <button onClick={generatePDF} type="primary">
        Generate PDF
      </button>
    </div>
  );
}

export default ShowPdf;

The margin setting seems to work correctly for the first table, but it does not have any effect on the second table!

I'm wondering if it's possible to provide x and y coordinates for jsPdf autotable?

https://i.stack.imgur.com/zn1ib.png

Answer №1

Found the solution! Utilizing startY will allow us to supply y coordinates for the table.

Answer №2

By adjusting the default margins, I was able to solve my problem. Simply setting the left margin to 15 pixels made the table align correctly!

autoTable(docPDF, {
  startY: 80,
  tableWidth: 600,
  margin: {
    left: 15,
  },
  styles: {font: 'helvetica', overflow: "ellipsize"},
});

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

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

Mix div borders with varying border radius for child elements

I'm currently working on a project that involves creating border lines between divs to achieve a design similar to the one shown in this design jpeg. However, I've only managed to reach an output jpeg where the merging is not quite right. The C ...

When applying the `display:block` and `width:100%` attributes to an HTML table cell, it may

My issue lies in the usage of DISPLAY:BLOCK for the td cells with a class of column. Despite applying it appropriately, the logo and CALL US td cells do not stack vertically when resized to mobile size. While they are supposed to take up 100% width, they ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

What are some effective solutions for resolving design problems in Isotope?

When I append the ajax coding, the data is coming fine. However, when I append this style="position: absolute; left: 468px; top: 0px;" css to the new appended data, it is not working. How can I achieve this? Below is my ajax code. Please provide suggestion ...

The issue of the color CSS rule not being applied to the button element when transitioning from disabled to enabled on browsers like Safari 14+ is a common challenge

There seems to be an issue with frontend form validation code affecting the disabled attribute of a submit button within a form. Two different css rules are applied for the enabled and disabled states, including changes in the text color of the button ele ...

Tips for positioning text directly beneath another text within the same list item:

I'm currently developing a vertical menu bar from scratch. To ensure responsiveness, I am using the CSS techniques demonstrated in Responsive Web Design by W3school. The menu consists of 5 list items with Font Awesome icons embedded within. I have set ...

The Redux state fails to update despite there being no difference between the old and new states

Having trouble with my Redux state. I created a reducer to update a value in an array, following immutability principles. However, the state is not updating as expected. Even added console logs to compare old and new states, but they return false. Any ide ...

Updating the error state of a TextField Component in React MaterialUI upon clicking a button

After clicking a 'search' button, I want to validate input fields in my input form. Many solutions suggest validating the input live as it is entered, but I prefer not to do this because some of the validation processes are costly operations, su ...

Elevate the React experience by smoothly sliding a fixed navbar upwards when scrolling down, and elegantly sliding it

tl;dr Don't miss the solution at the end! Looking to create a slide up and down effect on a fixed navbar in react? What's the best approach - using refs or the componentDidMount lifecycle hook? hideNav = (navbar) => { const hide = () ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

JavaScript library unsuccessful in transferring data to PHP script

I am facing an issue while trying to transfer variables from javascript to a php file for execution. The problem is that the php file is not being called or executed, even though I have confirmed that it works properly when tested individually. $(function ...

Issue encountered while generating REST API through Postman resulting in a 500 error

I am in the process of creating a Node.js API for a web application. The GET request is functioning properly, however, when attempting to execute a POST request, I encounter an error messageError Below is the code snippet: //User Schema const mongoose ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

Displaying a dynamic progress bar across all elements in fullscreen mode

I am looking to implement a full-screen indeterminate progress bar that overlays all screen elements. Here is my specific use case: When a user fills out a form, including an email field, the email id is checked against a database via ajax. While waiting ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Obtaining the Immediate ID of a Widget using JQuery

I currently have the following setup: <div id="dualList"></div> I created a plugin but stripped it down for testing purposes. I am encountering difficulties with the plugin not displaying the ID of the div. <script> (function($) { ...

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

What is the significance of -= and += operators in JavaScript programming language?

I'm puzzled by the mathematical process behind this JavaScript code, which results in -11. let x = 2; let y = 4; console.log(x -= y += 9) ...