Home > Net >  Dynamic HTML table in React Native PDF
Dynamic HTML table in React Native PDF

Time:12-30

listData below is a dynamic array of data. I'm trying to print the data in to a PDF using expo-print. How can I dynamically populate required number of table rows based on the array length and print each result in a seperate row?

"listdata": [
    "OAG0001",
    "RAA0012",
    "RAA0098",
    "RAB0023",
    "UAE0014"
  ]

What I've tried so far below obviously prints the total array in to a single table row.

const printLoadOutData = () => {
        setPrintLoadoutLoader(true);

        const dataLoadOutToprint = `
        <html>
        <header>
        </header>
        <title></title>
            <style>
                table, th, td {
                border:1px solid black;
                }
            </style>
        <body>
            <table >
                <tr>
                    <td>"${listData}"</td>
                </tr>
            </table>
        </body>
        </html >`;

        Print.printAsync({
            html: dataLoadOutToprint,
            width: 3508,
            height: 2480,
            orientation: Print.Orientation.landscape
        })

            .then(() => {
                setPrintLoadoutLoader(false);
            })
            .catch(() => {
                setPrintLoadoutLoader(false);
            })
    }

CodePudding user response:

You need to do something like this:

const listdata = [
    "OAG0001",
    "RAA0012",
    "RAA0098",
    "RAB0023",
    "UAE0014"
  ];

const htmltable = () => {
   const newAr = []
   let t = '';
   for (let i in listdata) {
     const item = listdata[i];
     t = t  
      `<tr>
         <td>${item}</td>
       </tr>`
   }
   return t;
}

Html content be like:

const htmlContent =
`<html>
    <header></header>
    <title></title>
    <style>
        table, th, td {
           border:1px solid black;
        }
    </style>
    <body>
       <table>
          ${htmltable()}
       </table>
    </body>
</html>`;
const print = () => {
  Print.printAsync({
     html: htmlContent,
     width: 3508,
     height: 2480,
     orientation: Print.Orientation.landscape
  }).then(() => {
     setPrintLoadoutLoader(false);
  }).catch(() => {
     setPrintLoadoutLoader(false);
  })
}
  • Related