JS3
JS3

Reputation: 1829

How can I print these dynamic data in jsPDF?

I have these example data:

{
    lastName: "dasdasd",
    totalAmount: 400,
    cartItems: [
      {
        color: "Black",
        size: "500",
        quantity: 2,
        cat: "ML",
        name: "Tumbler",
        price: 200
      }
    ],
    orderCreatedAt: { seconds: 1647338693, nanoseconds: 319000000 },
    Address: "France",
    houseNo: "7",
    firstName: "Anna",
  },

I wanted to print the first name, last name, houseNo, address, total amount, the cartItems(name and color only), and then the timestamp date of orderCreatedAt. I recreated this in codesandbox: https://codesandbox.io/s/js-pdf-78272j?file=/src/App.js:184-627

  const handlePrint = () => {
    console.log("clicked");
    const doc = new jsPDF();
    doc.text("Order details", 20, 10);
    const columns = [
      "First Name",
      "Last Name",
      "House No.",
      " Address",
      " Cart Items",
      "Total Amount",
      "Order Created At"
    ];
    const rows = [];
    data.map((item) => rows.push(Object.values(item)));

    doc.autoTable(columns, rows);
    doc.save("order.pdf");
  };

With these codes, it will print this data. It isn't arranged and then it shows [Object,object] enter image description here

Upvotes: 0

Views: 1496

Answers (1)

elainemakyl
elainemakyl

Reputation: 89

The reason why it shows [Object,Object] is when you do

data.map((item) => rows.push(Object.values(item)));

You are actually pushing the whole data object without any data transformation, to the rows array one by one. So on the House No. column, the [Object,Object] actually represents the cartItems object, and on the Address column the [Object,Object] actually is the value of orderCreatedAt.

Now the columns that you defined doesn't align with the data object you have, therefore you need to do some data transformation first. I have edited the codesandbox here for your reference.

Also for the orderCreatedAt column, I'm guessing you are getting the data from firebase, so you may need to import the Timestamp from the firebase/firestore package to do the conversion, but people also found out you can convert the Timestamp to Date with this formula.

Hope it helps.

Upvotes: 1

Related Questions