Home > OS >  How can I export the <a> tag using pdfhtml5 in DataTables
How can I export the <a> tag using pdfhtml5 in DataTables

Time:10-24

I want to export the <a> tag or link inside a cell in DataTables using pdfhtml5.

As of now the link is showing as plain text. How can I print it including its format?

CodePudding user response:

This is a two-step process:

Step 1

Use the DataTables generated PDF


Note: If you have other HTML in other columns that you do not want to handle, then you may need to refine your body function - so, something like:

if ($(node).children('a').length > 0) {
  return whatever you need here;
} else {
  return inner;
}

Follow-Up Question (from comments):

How about if I have multiple links in one cell? How can I export it?

Yes, there are various ways you can do this.

Since you are already using jQuery (for DataTables), you can use jQuery's parseHTML() function. This converts a string of HTML (as text) into an array of the related HTML nodes.

And then you can iterate over the array to process each link one at a time (and also handle any other text which may be in the same data cell).

A basic example:

Let's assume a DataTable cell containing the following content:

Some text <a href="whateverA">Edinburgh</a> and then <a href="whateverB">New York</a> the end.

The parseHTML() function will split this into an array containing the following 5 separate nodes - which you can then handle as 5 separate strings:

Some text 
<a href="whateverA">Edinburgh</a>
 and then 
<a href="whateverB">New York</a>
 the end.

Here is a demo of that:

let str = 'Some text <a href="whateverA">Edinburgh</a> and then <a href="whateverB">New York</a> the end.'
let nodes = $.parseHTML( str );
nodes.forEach(function( node ) {
  if ( node.nodeType === Node.TEXT_NODE ) {
    console.log( node.data ); // handle as PDF plain string
  } else {
    console.log( node.outerHTML ); // handle as PDF link
  }
})
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>New tab</title>
        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    </head>
    <body>
        <div>See the results in the console, below.</div>
    </body>
</html>

Final steps:

Now, instead of creating a PDF cell containing only a single PDF-formatted link, you will need to create an array of 5 PDF elements (see an example here), and add that array to the cell.

myPdfCellContent: [ 
  'Some text ',
  { text: 'Edinburgh', link: 'whateverA' },
  ' and then ',
  { text: 'New York', link: 'whateverB' },
  ' the end.'
]

You can integrate this approach into the existing DataTables solution to handle multiple links in one cell.

  • Related