Search code examples
javascriptarraysreactjsjspdf

How to pass an array with multiple values in the body of jsPDF?


I am trying jsPDF to display the list of products that have been ordered by the user.

I can create my columns and generate the PDF (download) But I'm having trouble with the body.

I can't send my information in the PDF body.

However, previously to display my different values of my array, I did for example "carts.map" but it does not seem to be the right method for my request.

It seems that I have a hard time understanding the array ...

Here is my code :

// Get the product name, quantity, price ...

  const [paniers, setPaniers] = useState([])
  const getPaniersDetailsCommande = () => [
        getDetails(JSON.parse(localStorage.getItem('User')).id)
        .then(response => {
            setPaniers(response.data)
            console.log(response.data)
        }).catch(err => console.log(err))
    ]

// Generation of the PDF 
    const PDFGeneration = () => {
        var doc = new jsPDF('p','px','a4','false');

        doc.text(10,15,'Résumé de votre commande : ');
        doc.autoTable({
            theme: 'grid',
            startY: 20,
            head: [['Nom', 'Quantité', 'Prix (€)']],
            body:[// Data of my product],
        });
        doc.save('CommandeInfo.pdf');
    }

If I forgot to provide more information please tell me in the comments

Thanks for the help >_< !


Solution

  • I faced a similiar issue. In your case, I would recommend, before the const PDFGeneration to use this:

    const [data] = useState(yourdata.map(item=> [item.id, item.nom, item.quantité, item.prix])); //and map all the data you require.
    

    After that when you call the doc.autoTable in the body simply call the const that was created, like so:

    doc.autoTable({
            theme: 'grid',
            startY: 20,
            head: [['Nom', 'Quantité', 'Prix (€)']],
            body:data,
        });